blob: 2e8a27606ad1601f81f5456b9be48646acee042a [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");
639 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800644
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800645 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
646 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800647 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700648 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649
Steven Thomasb02664d2017-07-26 18:48:28 -0700650 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800651 getBE().mRenderEngine =
652 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
653 hasWideColorDisplay
654 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
655 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800656 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800660 getBE().mHwc.reset(
661 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700662 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800663 // Process any initial hotplug and resulting display changes.
664 processDisplayHotplugEventsLocked();
665 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
666 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668 // make the default display GLContext current so that we can create textures
669 // when creating Layers (which may happens before we render something)
670 getDefaultDisplayDeviceLocked()->makeCurrent();
671
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (useVrFlinger) {
673 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700674 // This callback is called from the vr flinger dispatch thread. We
675 // need to call signalTransaction(), which requires holding
676 // mStateLock when we're not on the main thread. Acquiring
677 // mStateLock from the vr flinger dispatch thread might trigger a
678 // deadlock in surface flinger (see b/66916578), so post a message
679 // to be handled on the main thread instead.
680 sp<LambdaMessage> message = new LambdaMessage([=]() {
681 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
682 mVrFlingerRequestsDisplay = requestDisplay;
683 signalTransaction();
684 });
685 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800686 };
David Sodman105b7dc2017-11-04 20:28:14 -0700687 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
688 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800695 mEventControlThread = std::make_unique<impl::EventControlThread>(
696 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700697
Mathias Agopian92a979a2012-08-02 18:32:23 -0700698 // initialize our drawing state
699 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700700
Andy McFadden13a082e2012-08-24 10:16:42 -0700701 // set initial conditions (e.g. unblank default device)
702 initializeDisplays();
703
David Sodmanbc815282017-11-05 18:57:52 -0800704 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700705
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 // Inform native graphics APIs whether the present timestamp is supported:
707 if (getHwComposer().hasCapability(
708 HWC2::Capability::PresentFenceIsNotReliable)) {
709 mStartPropertySetThread = new StartPropertySetThread(false);
710 } else {
711 mStartPropertySetThread = new StartPropertySetThread(true);
712 }
713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
719 Dataspace::SRGB_LINEAR);
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
736 ALOGV("Display Color Setting is set to %s.",
737 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800755 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dan Stoza7f7da322014-05-02 15:26:25 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
794 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800795 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500799 if (!display.get())
800 return NAME_NOT_FOUND;
801
Jesse Hall692c7232012-11-08 15:41:56 -0800802 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700803 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800804 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
816 static int getDensityFromProperty(char const* propName) {
817 char property[PROPERTY_VALUE_MAX];
818 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 density = atoi(property);
821 }
822 return density;
823 }
824 public:
825 static int getEmuDensity() {
826 return getDensityFromProperty("qemu.sf.lcd_density"); }
827 static int getBuildDensity() {
828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 if (type == DisplayDevice::DISPLAY_PRIMARY) {
842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700858 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800859 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900872 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800887 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Michael Wright28f24d02016-07-12 13:30:53 -0700892 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700893 }
894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 return NO_ERROR;
896}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700897
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800898status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800900 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return BAD_VALUE;
902 }
903
904 // FIXME for now we always return stats for the primary display
905 memset(stats, 0, sizeof(*stats));
906 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
907 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
908 return NO_ERROR;
909}
910
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (display == nullptr) {
913 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800914 return BAD_VALUE;
915 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700916
917 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700919 return device->getActiveConfig();
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
926 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
927 this);
928 int32_t type = hw->getDisplayType();
929 int currentMode = hw->getActiveConfig();
930
931 if (mode == currentMode) {
932 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
933 return;
934 }
935
936 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
937 ALOGW("Trying to set config for virtual display");
938 return;
939 }
940
941 hw->setActiveConfig(mode);
942 getHwComposer().setActiveConfig(type, mode);
943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
946 class MessageSetActiveConfig: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 int mMode;
950 public:
951 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 int mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700955 Vector<DisplayInfo> configs;
956 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700957 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700958 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700959 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700961 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
967 ALOGW("Attempt to set active config = %d for virtual display",
968 mMode);
969 } else {
970 mFlinger.setActiveConfigInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
976 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700977 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978}
Michael Wright28f24d02016-07-12 13:30:53 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
982 return BAD_VALUE;
983 }
984
985 if (!display.get()) {
986 return NAME_NOT_FOUND;
987 }
988
989 int32_t type = NAME_NOT_FOUND;
990 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
991 if (display == mBuiltinDisplays[i]) {
992 type = i;
993 break;
994 }
995 }
996
997 if (type < 0) {
998 return type;
999 }
1000
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 {
1003 ConditionalLock _l(mStateLock,
1004 std::this_thread::get_id() != mMainThreadId);
1005 modes = getHwComposer().getColorModes(type);
1006 }
Michael Wright28f24d02016-07-12 13:30:53 -07001007 outColorModes->clear();
1008 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1009
1010 return NO_ERROR;
1011}
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001015 if (device != nullptr) {
1016 return device->getActiveColorMode();
1017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
1021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001022 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001023 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001027
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028 // Natural Mode means it's color managed and the color must be right,
1029 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1030 // Native Mode means the display is not color managed, and whichever
1031 // render intent is picked doesn't matter, thus return
1032 // RenderIntent::COLORIMETRIC as default here.
1033 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1034
1035 // In Auto Color Mode, we want to strech to panel color space, right now
1036 // only the built-in display supports it.
1037 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1038 mBuiltinDisplaySupportsEnhance &&
1039 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1040 renderIntent = RenderIntent::ENHANCE;
1041 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042
1043 if (mode == currentMode && dataSpace == currentDataSpace &&
1044 renderIntent == currentRenderIntent) {
1045 return;
1046 }
1047
1048 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 ALOGW("Trying to set config for virtual display");
1050 return;
1051 }
1052
1053 hw->setActiveColorMode(mode);
1054 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055 hw->setActiveRenderIntent(renderIntent);
1056 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1057
1058 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1059 decodeColorMode(mode).c_str(), mode,
1060 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1061 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001062}
1063
1064
1065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001067 class MessageSetActiveColorMode: public MessageBase {
1068 SurfaceFlinger& mFlinger;
1069 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 public:
1072 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1075 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 mFlinger.getDisplayColorModes(mDisplay, &modes);
1078 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return true;
1083 }
1084 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1085 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001089 ALOGW("Attempt to set active color mode %s %d for virtual display",
1090 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
1094 return true;
1095 }
1096 };
1097 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1098 postMessageSync(msg);
1099 return NO_ERROR;
1100}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001101
Svetoslavd85084b2014-03-20 10:28:31 -07001102status_t SurfaceFlinger::clearAnimationFrameStats() {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.clearStats();
1105 return NO_ERROR;
1106}
1107
1108status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1109 Mutex::Autolock _l(mStateLock);
1110 mAnimFrameTracker.getStats(outStats);
1111 return NO_ERROR;
1112}
1113
Dan Stozac4f471e2016-03-24 09:31:08 -07001114status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1115 HdrCapabilities* outCapabilities) const {
1116 Mutex::Autolock _l(mStateLock);
1117
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001119 if (displayDevice == nullptr) {
1120 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1121 return BAD_VALUE;
1122 }
1123
Peiyong Linfb069302018-04-25 14:34:31 -07001124 // At this point the DisplayDeivce should already be set up,
1125 // meaning the luminance information is already queried from
1126 // hardware composer and stored properly.
1127 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1128 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1129 capabilities.getDesiredMaxLuminance(),
1130 capabilities.getDesiredMaxAverageLuminance(),
1131 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001132
1133 return NO_ERROR;
1134}
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1138 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 if (mInjectVSyncs == enable) {
1141 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143
1144 if (enable) {
1145 ALOGV("VSync Injections enabled");
1146 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001147 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001148 mInjectorEventThread =
1149 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1150 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001152 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 } else {
1154 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001155 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 }
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 });
1160 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 return NO_ERROR;
1162}
1163
1164status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 if (!mInjectVSyncs) {
1168 ALOGE("VSync Injections not enabled");
1169 return BAD_VALUE;
1170 }
1171 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1172 ALOGV("Injecting VSync inside SurfaceFlinger");
1173 mVSyncInjector->onInjectSyncEvent(when);
1174 }
1175 return NO_ERROR;
1176}
1177
Lloyd Pique755e3192018-01-31 16:46:15 -08001178status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1179 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001180 IPCThreadState* ipc = IPCThreadState::self();
1181 const int pid = ipc->getCallingPid();
1182 const int uid = ipc->getCallingUid();
1183 if ((uid != AID_SHELL) &&
1184 !PermissionCache::checkPermission(sDump, pid, uid)) {
1185 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1186 return PERMISSION_DENIED;
1187 }
1188
1189 // Try to acquire a lock for 1s, fail gracefully
1190 const status_t err = mStateLock.timedLock(s2ns(1));
1191 const bool locked = (err == NO_ERROR);
1192 if (!locked) {
1193 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1194 return TIMED_OUT;
1195 }
1196
1197 outLayers->clear();
1198 mCurrentState.traverseInZOrder([&](Layer* layer) {
1199 outLayers->push_back(layer->getLayerDebugInfo());
1200 });
1201
1202 mStateLock.unlock();
1203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
1210 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1211 return mSFEventThread->createEventConnection();
1212 } else {
1213 return mEventThread->createEventConnection();
1214 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001215}
1216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001218
1219void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001232 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001237 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001238 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001242 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001243 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244 if (res == NO_ERROR) {
1245 msg->wait();
1246 }
1247 return res;
1248}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001250void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001251 do {
1252 waitForEvent();
1253 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254}
1255
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256void SurfaceFlinger::enableHardwareVsync() {
1257 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1261 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001263 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 if (makeAvailable) {
1270 mHWVsyncAvailable = true;
1271 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001272 // Hardware vsync is not currently available, so abort the resync
1273 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 return;
1275 }
1276
David Sodman105b7dc2017-11-04 20:28:14 -07001277 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279
1280 mPrimaryDispSync.reset();
1281 mPrimaryDispSync.setPeriod(period);
1282
1283 if (!mPrimaryHWVsyncEnabled) {
1284 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001285 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1286 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 mPrimaryHWVsyncEnabled = true;
1288 }
1289}
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 Mutex::Autolock _l(mHWVsyncLock);
1293 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1295 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.endResync();
1297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1317 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
1324 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 return;
1327 }
1328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 { // Scope for the lock
1332 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001336 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001337
1338 if (needsHwVsync) {
1339 enableHardwareVsync();
1340 } else {
1341 disableHardwareVsync(false);
1342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343}
1344
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001346 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1347 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348}
1349
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1351 HWC2::Connection connection) {
1352 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1353 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 // Ignore events that do not have the right sequenceId.
1356 if (sequenceId != getBE().mComposerSequenceId) {
1357 return;
1358 }
1359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Only lock if we're not on the main thread. This function is normally
1361 // called on a hwbinder thread, but for the primary display it's called on
1362 // the main thread with the state lock already held, so don't attempt to
1363 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365
Lloyd Pique715a2c12017-12-14 17:18:08 -08001366 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001368 if (std::this_thread::get_id() == mMainThreadId) {
1369 // Process all pending hot plug events immediately if we are on the main thread.
1370 processDisplayHotplugEventsLocked();
1371 }
1372
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::onRefreshReceived(int sequenceId,
1377 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001382 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001383}
1384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 getHwComposer().setVsyncEnabled(disp,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001390}
1391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 // Clear the drawing state so that the logic inside of
1396 // handleTransactionLocked will fire. It will determine the delta between
1397 // mCurrentState and mDrawingState and re-apply all changes when we make the
1398 // transition.
1399 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001400 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 mDisplays.clear();
1402}
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404void SurfaceFlinger::updateVrFlinger() {
1405 if (!mVrFlinger)
1406 return;
1407 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 return;
1410 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 ALOGE("Vr flinger is only supported for remote hardware composer"
1414 " service connections. Ignoring request to transition to vr"
1415 " flinger.");
1416 mVrFlingerRequestsDisplay = false;
1417 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 int currentDisplayPowerMode = getDisplayDeviceLocked(
1423 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001430 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001431 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1432 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434
David Sodman105b7dc2017-11-04 20:28:14 -07001435 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1436 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001437
1438 if (vrFlingerRequestsDisplay) {
1439 mVrFlinger->GrantDisplayOwnership();
1440 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
1444 mVisibleRegionsDirty = true;
1445 invalidateHwcGeometry();
1446
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1449 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1450 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001453 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 const nsecs_t period = activeConfig->getVsyncPeriod();
1455 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Use phase of 0 since phase is not known.
1458 // Use latency of 0, which will snap to the ideal latency.
1459 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 android_atomic_or(1, &mRepaintEverything);
1462 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463}
1464
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001466 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001469 bool frameMissed = !mHadClientComposition &&
1470 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001471 (mPreviousPresentFence->getSignalTime() ==
1472 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001473 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001474 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001475 mTimeStats.incrementMissedFrames();
1476 if (mPropagateBackpressure) {
1477 signalLayerUpdate();
1478 break;
1479 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001480 }
Dan Stoza50182882016-07-08 12:02:20 -07001481
Steven Thomas050b2c82017-03-06 11:45:16 -08001482 // Now that we're going to make it to the handleMessageTransaction()
1483 // call below it's safe to call updateVrFlinger(), which will
1484 // potentially trigger a display handoff.
1485 updateVrFlinger();
1486
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 bool refreshNeeded = handleMessageTransaction();
1488 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001489 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001491 // Signal a refresh if a transaction modified the window state,
1492 // a new buffer was latched, or if HWC has requested a full
1493 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 signalRefresh();
1495 }
1496 break;
1497 }
1498 case MessageQueue::REFRESH: {
1499 handleMessageRefresh();
1500 break;
1501 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001502 }
1503}
1504
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001506 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001508 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517}
1518
1519void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001521
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001522 mRefreshPending = false;
1523
Pablo Ceballos40845df2016-01-25 17:41:15 -08001524 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001525
Brian Andersond6927fb2016-07-23 23:37:30 -07001526 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001527 rebuildLayerStacks();
1528 setUpHWComposer();
1529 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001530 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001531 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001532 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001534
David Sodman105b7dc2017-11-04 20:28:14 -07001535 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001536
1537 mHadClientComposition = false;
1538 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1539 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1540 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001541 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001542 }
Dan Stoza2713c302018-03-28 17:07:36 -07001543 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001544
Dan Stoza9e56aa02015-11-02 13:00:03 -08001545 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001547
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548void SurfaceFlinger::doDebugFlashRegions()
1549{
1550 // is debugging enabled
1551 if (CC_LIKELY(!mDebugRegion))
1552 return;
1553
1554 const bool repaintEverything = mRepaintEverything;
1555 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1556 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001557 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 // transform the dirty region into this screen's coordinate space
1559 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1560 if (!dirtyRegion.isEmpty()) {
1561 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001562 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563
1564 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001566 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001567 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1568
Mathias Agopianda27af92012-09-13 18:17:13 -07001569 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 }
1571 }
1572 }
1573
1574 postFramebuffer();
1575
1576 if (mDebugRegion > 1) {
1577 usleep(mDebugRegion * 1000);
1578 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001579
Dan Stoza9e56aa02015-11-02 13:00:03 -08001580 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001581 auto& displayDevice = mDisplays[displayId];
1582 if (!displayDevice->isDisplayOn()) {
1583 continue;
1584 }
1585
David Sodman105b7dc2017-11-04 20:28:14 -07001586 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1587 ALOGE_IF(result != NO_ERROR,
1588 "prepareFrame for display %zd failed:"
1589 " %d (%s)",
1590 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001591 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592}
1593
Adrian Roos1e1a1282017-11-01 19:05:31 +01001594void SurfaceFlinger::doTracing(const char* where) {
1595 ATRACE_CALL();
1596 ATRACE_NAME(where);
1597 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001598 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001599 }
1600}
1601
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001602void SurfaceFlinger::logLayerStats() {
1603 ATRACE_CALL();
1604 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1605 int32_t hwcId = -1;
1606 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1607 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1608 if (displayDevice->isPrimary()) {
1609 hwcId = displayDevice->getHwcDisplayId();
1610 break;
1611 }
1612 }
1613 if (hwcId < 0) {
1614 ALOGE("LayerStats: Hmmm, no primary display?");
1615 return;
1616 }
1617 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1618 }
1619}
1620
Brian Andersond6927fb2016-07-23 23:37:30 -07001621void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001623 ATRACE_CALL();
1624 ALOGV("preComposition");
1625
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001627 mDrawingState.traverseInZOrder([&](Layer* layer) {
1628 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 needExtraInvalidate = true;
1630 }
Robert Carr2047fae2016-11-28 14:09:09 -08001631 });
1632
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633 if (needExtraInvalidate) {
1634 signalLayerUpdate();
1635 }
1636}
1637
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638void SurfaceFlinger::updateCompositorTiming(
1639 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1640 std::shared_ptr<FenceTime>& presentFenceTime) {
1641 // Update queue of past composite+present times and determine the
1642 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001643 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001645 while (!getBE().mCompositePresentTimes.empty()) {
1646 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 // Cached values should have been updated before calling this method,
1648 // which helps avoid duplicate syscalls.
1649 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1650 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1651 break;
1652 }
1653 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001654 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 }
1656
1657 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001658 while (getBE().mCompositePresentTimes.size() > 16) {
1659 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660 }
1661
Brian Andersond0010582017-03-07 13:20:31 -08001662 setCompositorTimingSnapped(
1663 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1664}
1665
1666void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1667 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 // Integer division and modulo round toward 0 not -inf, so we need to
1669 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001670 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1672 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1673
Brian Andersond0010582017-03-07 13:20:31 -08001674 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1675 if (idealLatency <= 0) {
1676 idealLatency = vsyncInterval;
1677 }
1678
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 // Snap the latency to a value that removes scheduling jitter from the
1680 // composition and present times, which often have >1ms of jitter.
1681 // Reducing jitter is important if an app attempts to extrapolate
1682 // something (such as user input) to an accurate diasplay time.
1683 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1684 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001685 nsecs_t bias = vsyncInterval / 2;
1686 int64_t extraVsyncs =
1687 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1688 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1689 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690
David Sodman99974d22017-11-28 12:04:33 -08001691 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1692 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1693 getBE().mCompositorTiming.interval = vsyncInterval;
1694 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695}
1696
1697void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001699 ATRACE_CALL();
1700 ALOGV("postComposition");
1701
Brian Anderson3546a3f2016-07-14 11:51:14 -07001702 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001703 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001704 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001705 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001706 }
1707
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001708 // |mStateLock| not needed as we are on the main thread
1709 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001710
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001713 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714 glCompositionDoneFenceTime =
1715 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001716 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717 } else {
1718 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1719 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720
David Sodman73beded2017-11-15 11:56:06 -08001721 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001722 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001724 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001725
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1727 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1728
1729 // We use the refreshStartTime which might be sampled a little later than
1730 // when we started doing work for this frame, but that should be okay
1731 // since updateCompositorTiming has snapping logic.
1732 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001733 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001734 CompositorTiming compositorTiming;
1735 {
David Sodman99974d22017-11-28 12:04:33 -08001736 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1737 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001738 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739
Robert Carr2047fae2016-11-28 14:09:09 -08001740 mDrawingState.traverseInZOrder([&](Layer* layer) {
1741 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001742 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001743 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001744 recordBufferingStats(layer->getName().string(),
1745 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001746 }
Robert Carr2047fae2016-11-28 14:09:09 -08001747 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001748
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001749 if (presentFenceTime->isValid()) {
1750 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001751 enableHardwareVsync();
1752 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001753 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001754 }
1755 }
1756
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001757 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001758 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001759 enableHardwareVsync();
1760 }
1761 }
1762
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001763 if (mAnimCompositionPending) {
1764 mAnimCompositionPending = false;
1765
Brian Anderson4e606e32017-03-16 15:34:57 -07001766 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001768 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001769 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001770 // The HWC doesn't support present fences, so use the refresh
1771 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001773 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001774 mAnimFrameTracker.setActualPresentTime(presentTime);
1775 }
1776 mAnimFrameTracker.advanceFrame();
1777 }
Dan Stozab90cf072015-03-05 11:05:59 -08001778
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001779 mTimeStats.incrementTotalFrames();
1780 if (mHadClientComposition) {
1781 mTimeStats.incrementClientCompositionFrames();
1782 }
1783
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001784 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1785 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001786 return;
1787 }
1788
1789 nsecs_t currentTime = systemTime();
1790 if (mHasPoweredOff) {
1791 mHasPoweredOff = false;
1792 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001793 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001794 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001795 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1796 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001797 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001798 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001799 }
David Sodman4a36e932017-11-07 14:29:47 -08001800 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001801 }
David Sodman4a36e932017-11-07 14:29:47 -08001802 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001803}
1804
1805void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 ATRACE_CALL();
1807 ALOGV("rebuildLayerStacks");
1808
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001811 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 mVisibleRegionsDirty = false;
1813 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001814
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1816 Region opaqueRegion;
1817 Region dirtyRegion;
1818 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001819 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1821 const Transform& tr(displayDevice->getTransform());
1822 const Rect bounds(displayDevice->getBounds());
1823 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001824 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001827 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001828 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1829 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 Region drawRegion(tr.transform(
1831 layer->visibleNonTransparentRegion));
1832 drawRegion.andSelf(bounds);
1833 if (!drawRegion.isEmpty()) {
1834 layersSortedByZ.add(layer);
1835 } else {
1836 // Clear out the HWC layer if this layer was
1837 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001838 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001839 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001840 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001841 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001842 // WM changes displayDevice->layerStack upon sleep/awake.
1843 // Here we make sure we delete the HWC layers even if
1844 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001845 hwcLayerDestroyed = layer->destroyHwcLayer(
1846 displayDevice->getHwcDisplayId());
1847 }
1848
1849 // If a layer is not going to get a release fence because
1850 // it is invisible, but it is also going to release its
1851 // old buffer, add it to the list of layers needing
1852 // fences.
1853 if (hwcLayerDestroyed) {
1854 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1855 mLayersWithQueuedFrames.cend(), layer);
1856 if (found != mLayersWithQueuedFrames.cend()) {
1857 layersNeedingFences.add(layer);
1858 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001859 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 });
1861 }
1862 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001863 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 displayDevice->undefinedRegion.set(bounds);
1865 displayDevice->undefinedRegion.subtractSelf(
1866 tr.transform(opaqueRegion));
1867 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001871
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872// Returns a dataspace that fits all visible layers. The returned dataspace
1873// can only be one of
1874//
1875// - Dataspace::V0_SRGB
1876// - Dataspace::DISPLAY_P3
1877// - Dataspace::V0_SCRGB_LINEAR
1878// TODO(b/73825729) Add BT2020 data space.
1879ui::Dataspace SurfaceFlinger::getBestDataspace(
1880 const sp<const DisplayDevice>& displayDevice) const {
1881 Dataspace bestDataspace = Dataspace::V0_SRGB;
1882 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1883 switch (layer->getDataSpace()) {
1884 case Dataspace::V0_SCRGB:
1885 case Dataspace::V0_SCRGB_LINEAR:
1886 // return immediately
1887 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 case Dataspace::DISPLAY_P3:
1889 bestDataspace = Dataspace::DISPLAY_P3;
1890 break;
1891 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1892 // since SurfaceFlinger simulates HDR support now, it should honor
1893 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 case Dataspace::BT2020_PQ:
1895 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001896 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897 return Dataspace::V0_SCRGB_LINEAR;
1898 }
1899 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001900 case Dataspace::BT2020_HLG:
1901 case Dataspace::BT2020_ITU_HLG:
1902 if (!displayDevice->hasHLGSupport()) {
1903 return Dataspace::V0_SCRGB_LINEAR;
1904 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905 break;
1906 default:
1907 break;
1908 }
Romain Guy54f154a2017-10-24 21:40:32 +01001909 }
1910
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001912}
1913
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914// Pick the ColorMode / Dataspace for the display device.
1915// TODO(b/73825729) Add BT2020 color mode.
1916void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1917 ColorMode* outMode, Dataspace* outDataSpace) const {
1918 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1919 *outMode = ColorMode::NATIVE;
1920 *outDataSpace = Dataspace::UNKNOWN;
1921 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001922 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001923
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924 switch (getBestDataspace(displayDevice)) {
1925 case Dataspace::DISPLAY_P3:
1926 case Dataspace::V0_SCRGB_LINEAR:
1927 *outMode = ColorMode::DISPLAY_P3;
1928 *outDataSpace = Dataspace::DISPLAY_P3;
1929 break;
1930 default:
1931 *outMode = ColorMode::SRGB;
1932 *outDataSpace = Dataspace::V0_SRGB;
1933 break;
1934 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001935}
1936
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 ATRACE_CALL();
1939 ALOGV("setUpHWComposer");
1940
Jesse Hall028dc8f2013-08-20 16:35:32 -07001941 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001942 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001943 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1944 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1945
1946 // If nothing has changed (!dirty), don't recompose.
1947 // If something changed, but we don't currently have any visible layers,
1948 // and didn't when we last did a composition, then skip it this time.
1949 // The second rule does two things:
1950 // - When all layers are removed from a display, we'll emit one black
1951 // frame, then nothing more until we get new layers.
1952 // - When a display is created with a private layer stack, we won't
1953 // emit any black frames until a layer is added to the layer stack.
1954 bool mustRecompose = dirty && !(empty && wasEmpty);
1955
1956 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1957 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1958 mustRecompose ? "doing" : "skipping",
1959 dirty ? "+" : "-",
1960 empty ? "+" : "-",
1961 wasEmpty ? "+" : "-");
1962
Dan Stoza71433162014-02-04 16:22:36 -08001963 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001964
1965 if (mustRecompose) {
1966 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1967 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001968 }
1969
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 // build the h/w work list
1971 if (CC_UNLIKELY(mGeometryInvalid)) {
1972 mGeometryInvalid = false;
1973 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1974 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1975 const auto hwcId = displayDevice->getHwcDisplayId();
1976 if (hwcId >= 0) {
1977 const Vector<sp<Layer>>& currentLayers(
1978 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001979 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001980 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001982 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001985 }
1986 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001987
Robert Carrae060832016-11-28 10:51:00 -08001988 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001989 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001991 }
1992 }
1993 }
1994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 }
Riley Andrews03414a12014-07-01 14:22:59 -07001996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 // Set the per-frame data
1998 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1999 auto& displayDevice = mDisplays[displayId];
2000 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002001
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 if (hwcId < 0) {
2003 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002004 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002005 if (mDrawingState.colorMatrixChanged) {
2006 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2007 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002008 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2009 "display %zd: %d", displayId, result);
2010 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002012 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2013 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002014 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002015 layer->forceClientComposition(hwcId);
2016 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002017 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2018 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2019 !displayDevice->hasHLGSupport()) {
2020 layer->forceClientComposition(hwcId);
2021 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002022
chaviwc9232ed2017-11-14 15:31:15 -08002023 if (layer->getForceClientComposition(hwcId)) {
2024 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2025 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2026 continue;
2027 }
2028
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029 layer->setPerFrameData(displayDevice);
2030 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002031
2032 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002033 ColorMode colorMode;
2034 Dataspace dataSpace;
2035 pickColorMode(displayDevice, &colorMode, &dataSpace);
2036 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002037 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 }
2039
Chia-I Wu28f320b2018-05-03 11:02:56 -07002040 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002041
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002043 auto& displayDevice = mDisplays[displayId];
2044 if (!displayDevice->isDisplayOn()) {
2045 continue;
2046 }
2047
David Sodman105b7dc2017-11-04 20:28:14 -07002048 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2050 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002051 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002052}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002053
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054void SurfaceFlinger::doComposition() {
2055 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 ALOGV("doComposition");
2057
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002058 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002059 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002060 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002061 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062 // transform the dirty region into this screen's coordinate space
2063 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002064
2065 // repaint the framebuffer (if needed)
2066 doDisplayComposition(hw, dirtyRegion);
2067
Mathias Agopiancd60f992012-08-16 16:28:27 -07002068 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002069 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002070 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002071 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002073}
2074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002075void SurfaceFlinger::postFramebuffer()
2076{
Mathias Agopian841cde52012-03-01 15:44:37 -08002077 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002079
Mathias Agopiana44b0412011-10-16 18:46:35 -07002080 const nsecs_t now = systemTime();
2081 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2084 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002085 if (!displayDevice->isDisplayOn()) {
2086 continue;
2087 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 const auto hwcId = displayDevice->getHwcDisplayId();
2089 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002090 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002091 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002092 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002093 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002095 // The layer buffer from the previous frame (if any) is released
2096 // by HWC only when the release fence from this frame (if any) is
2097 // signaled. Always get the release fence from HWC first.
2098 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002099 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002100
2101 // If the layer was client composited in the previous frame, we
2102 // need to merge with the previous client target acquire fence.
2103 // Since we do not track that, always merge with the current
2104 // client target acquire fence when it is available, even though
2105 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002107 releaseFence = Fence::merge("LayerRelease", releaseFence,
2108 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002109 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002110
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 layer->onLayerDisplayed(releaseFence);
2112 }
Chia-I Wu83806892017-11-16 10:50:20 -08002113
2114 // We've got a list of layers needing fences, that are disjoint with
2115 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2116 // supply them with the present fence.
2117 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002118 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002119 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2120 layer->onLayerDisplayed(presentFence);
2121 }
2122 }
2123
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002125 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002126 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002127 }
2128
Mathias Agopiana44b0412011-10-16 18:46:35 -07002129 mLastSwapBufferTime = systemTime() - now;
2130 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002131
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002132 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002133 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2134 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2135 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2136 logFrameStats();
2137 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002138 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139}
2140
Mathias Agopian87baae12012-07-31 12:38:26 -07002141void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142{
Mathias Agopian841cde52012-03-01 15:44:37 -08002143 ATRACE_CALL();
2144
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002145 // here we keep a copy of the drawing state (that is the state that's
2146 // going to be overwritten by handleTransactionLocked()) outside of
2147 // mStateLock so that the side-effects of the State assignment
2148 // don't happen with mStateLock held (which can cause deadlocks).
2149 State drawingState(mDrawingState);
2150
Mathias Agopianca4d3602011-05-19 15:38:14 -07002151 Mutex::Autolock _l(mStateLock);
2152 const nsecs_t now = systemTime();
2153 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154
Mathias Agopianca4d3602011-05-19 15:38:14 -07002155 // Here we're guaranteed that some transaction flags are set
2156 // so we can call handleTransactionLocked() unconditionally.
2157 // We call getTransactionFlags(), which will also clear the flags,
2158 // with mStateLock held to guarantee that mCurrentState won't change
2159 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002160
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002161 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002162 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002163 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002164
Mathias Agopianca4d3602011-05-19 15:38:14 -07002165 mLastTransactionTime = systemTime() - now;
2166 mDebugInTransaction = 0;
2167 invalidateHwcGeometry();
2168 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002169}
2170
Lloyd Pique715a2c12017-12-14 17:18:08 -08002171DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002172 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002173 // Figure out whether the event is for the primary display or an
2174 // external display by matching the Hwc display id against one for a
2175 // connected display. If we did not find a match, we then check what
2176 // displays are not already connected to determine the type. If we don't
2177 // have a connected primary display, we assume the new display is meant to
2178 // be the primary display, and then if we don't have an external display,
2179 // we assume it is that.
2180 const auto primaryDisplayId =
2181 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2182 const auto externalDisplayId =
2183 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2184 if (primaryDisplayId && primaryDisplayId == display) {
2185 return DisplayDevice::DISPLAY_PRIMARY;
2186 } else if (externalDisplayId && externalDisplayId == display) {
2187 return DisplayDevice::DISPLAY_EXTERNAL;
2188 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2189 return DisplayDevice::DISPLAY_PRIMARY;
2190 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2191 return DisplayDevice::DISPLAY_EXTERNAL;
2192 }
2193
2194 return DisplayDevice::DISPLAY_ID_INVALID;
2195}
2196
Lloyd Piqueba04e622017-12-14 17:11:26 -08002197void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2198 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002199 auto displayType = determineDisplayType(event.display, event.connection);
2200 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2201 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2202 continue;
2203 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204
2205 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2206 ALOGE("External displays are not supported by the vr hardware composer.");
2207 continue;
2208 }
2209
Lloyd Pique715a2c12017-12-14 17:18:08 -08002210 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002211
2212 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002213 if (!mBuiltinDisplays[displayType].get()) {
2214 ALOGV("Creating built in display %d", displayType);
2215 mBuiltinDisplays[displayType] = new BBinder();
2216 // All non-virtual displays are currently considered secure.
2217 DisplayDeviceState info(displayType, true);
2218 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2219 "Built-in Screen" : "External Screen";
2220 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002221 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002222 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002223 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002224 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002225
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2227 if (idx >= 0) {
2228 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002229 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002230 mCurrentState.displays.removeItemsAt(idx);
2231 }
2232 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002233 }
2234
2235 processDisplayChangesLocked();
2236 }
2237
2238 mPendingHotplugEvents.clear();
2239}
2240
Lloyd Pique09594832018-01-22 17:48:03 -08002241sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2242 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2243 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002244 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002245 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002247 for (ColorMode colorMode : modes) {
2248 switch (colorMode) {
2249 case ColorMode::DISPLAY_P3:
2250 case ColorMode::ADOBE_RGB:
2251 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002253 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002254 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002255 default:
2256 break;
2257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258
2259 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2260 colorMode);
2261 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2262 for (auto intent : renderIntents) {
2263 if (intent == RenderIntent::ENHANCE) {
2264 mBuiltinDisplaySupportsEnhance = true;
2265 break;
2266 }
2267 }
2268 }
Lloyd Pique09594832018-01-22 17:48:03 -08002269 }
2270 }
2271
Peiyong Lin62665892018-04-16 11:07:44 -07002272 HdrCapabilities hdrCapabilities;
2273 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002274
2275 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2276 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2277
2278 /*
2279 * Create our display's surface
2280 */
2281 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2282 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2283 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2284 renderSurface->setNativeWindow(nativeWindow.get());
2285 const int displayWidth = renderSurface->queryWidth();
2286 const int displayHeight = renderSurface->queryHeight();
2287
2288 // Make sure that composition can never be stalled by a virtual display
2289 // consumer that isn't processing buffers fast enough. We have to do this
2290 // in two places:
2291 // * Here, in case the display is composed entirely by HWC.
2292 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2293 // window's swap interval in eglMakeCurrent, so they'll override the
2294 // interval we set here.
2295 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2296 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2297 }
2298
2299 // virtual displays are always considered enabled
2300 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2301 : HWC_POWER_MODE_OFF;
2302
2303 sp<DisplayDevice> hw =
2304 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2305 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002306 hasWideColorGamut, hdrCapabilities,
2307 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2308 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002309
2310 if (maxFrameBufferAcquiredBuffers >= 3) {
2311 nativeWindowSurface->preallocateBuffers();
2312 }
2313
2314 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2316 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002317 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002319 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002321 hw->setLayerStack(state.layerStack);
2322 hw->setProjection(state.orientation, state.viewport, state.frame);
2323 hw->setDisplayName(state.displayName);
2324
2325 return hw;
2326}
2327
Lloyd Pique347200f2017-12-14 17:00:15 -08002328void SurfaceFlinger::processDisplayChangesLocked() {
2329 // here we take advantage of Vector's copy-on-write semantics to
2330 // improve performance by skipping the transaction entirely when
2331 // know that the lists are identical
2332 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2333 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2334 if (!curr.isIdenticalTo(draw)) {
2335 mVisibleRegionsDirty = true;
2336 const size_t cc = curr.size();
2337 size_t dc = draw.size();
2338
2339 // find the displays that were removed
2340 // (ie: in drawing state but not in current state)
2341 // also handle displays that changed
2342 // (ie: displays that are in both lists)
2343 for (size_t i = 0; i < dc;) {
2344 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2345 if (j < 0) {
2346 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002347 // Call makeCurrent() on the primary display so we can
2348 // be sure that nothing associated with this display
2349 // is current.
2350 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2351 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2352 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2353 if (hw != nullptr) hw->disconnect(getHwComposer());
2354 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2355 mEventThread->onHotplugReceived(draw[i].type, false);
2356 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 } else {
2358 // this display is in both lists. see if something changed.
2359 const DisplayDeviceState& state(curr[j]);
2360 const wp<IBinder>& display(curr.keyAt(j));
2361 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2362 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2363 if (state_binder != draw_binder) {
2364 // changing the surface is like destroying and
2365 // recreating the DisplayDevice, so we just remove it
2366 // from the drawing state, so that it get re-added
2367 // below.
2368 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2369 if (hw != nullptr) hw->disconnect(getHwComposer());
2370 mDisplays.removeItem(display);
2371 mDrawingState.displays.removeItemsAt(i);
2372 dc--;
2373 // at this point we must loop to the next item
2374 continue;
2375 }
2376
2377 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2378 if (disp != nullptr) {
2379 if (state.layerStack != draw[i].layerStack) {
2380 disp->setLayerStack(state.layerStack);
2381 }
2382 if ((state.orientation != draw[i].orientation) ||
2383 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2384 disp->setProjection(state.orientation, state.viewport, state.frame);
2385 }
2386 if (state.width != draw[i].width || state.height != draw[i].height) {
2387 disp->setDisplaySize(state.width, state.height);
2388 }
2389 }
2390 }
2391 ++i;
2392 }
2393
2394 // find displays that were added
2395 // (ie: in current state but not in drawing state)
2396 for (size_t i = 0; i < cc; i++) {
2397 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2398 const DisplayDeviceState& state(curr[i]);
2399
2400 sp<DisplaySurface> dispSurface;
2401 sp<IGraphicBufferProducer> producer;
2402 sp<IGraphicBufferProducer> bqProducer;
2403 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002404 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002405
2406 int32_t hwcId = -1;
2407 if (state.isVirtualDisplay()) {
2408 // Virtual displays without a surface are dormant:
2409 // they have external state (layer stack, projection,
2410 // etc.) but no internal state (i.e. a DisplayDevice).
2411 if (state.surface != nullptr) {
2412 // Allow VR composer to use virtual displays.
2413 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2414 int width = 0;
2415 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2416 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2417 int height = 0;
2418 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2419 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2420 int intFormat = 0;
2421 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2422 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002423 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002424
2425 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2426 }
2427
2428 // TODO: Plumb requested format back up to consumer
2429
2430 sp<VirtualDisplaySurface> vds =
2431 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2432 bqProducer, bqConsumer,
2433 state.displayName);
2434
2435 dispSurface = vds;
2436 producer = vds;
2437 }
2438 } else {
2439 ALOGE_IF(state.surface != nullptr,
2440 "adding a supported display, but rendering "
2441 "surface is provided (%p), ignoring it",
2442 state.surface.get());
2443
2444 hwcId = state.type;
2445 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2446 producer = bqProducer;
2447 }
2448
2449 const wp<IBinder>& display(curr.keyAt(i));
2450 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002451 mDisplays.add(display,
2452 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2453 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 if (!state.isVirtualDisplay()) {
2455 mEventThread->onHotplugReceived(state.type, true);
2456 }
2457 }
2458 }
2459 }
2460 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002461
2462 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002463}
2464
Mathias Agopian87baae12012-07-31 12:38:26 -07002465void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002466{
Dan Stoza7dde5992015-05-22 09:51:44 -07002467 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002468 mCurrentState.traverseInZOrder([](Layer* layer) {
2469 layer->notifyAvailableFrames();
2470 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 /*
2473 * Traversal of the children
2474 * (perform the transaction for each of them if needed)
2475 */
2476
Mathias Agopian3559b072012-08-15 13:46:03 -07002477 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002478 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002480 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
2482 const uint32_t flags = layer->doTransaction(0);
2483 if (flags & Layer::eVisibleRegion)
2484 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002485 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 }
2487
2488 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002489 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 */
2491
Mathias Agopiane57f2922012-08-09 16:29:12 -07002492 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002497 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 // The transform hint might have changed for some layers
2499 // (either because a display has changed, or because a layer
2500 // as changed).
2501 //
2502 // Walk through all the layers in currentLayers,
2503 // and update their transform hint.
2504 //
2505 // If a layer is visible only on a single display, then that
2506 // display is used to calculate the hint, otherwise we use the
2507 // default display.
2508 //
2509 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2510 // the hint is set before we acquire a buffer from the surface texture.
2511 //
2512 // NOTE: layer transactions have taken place already, so we use their
2513 // drawing state. However, SurfaceFlinger's own transaction has not
2514 // happened yet, so we must use the current state layer list
2515 // (soon to become the drawing state list).
2516 //
2517 sp<const DisplayDevice> disp;
2518 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002519 bool first = true;
2520 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002521 // NOTE: we rely on the fact that layers are sorted by
2522 // layerStack first (so we don't have to traverse the list
2523 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002525 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 currentlayerStack = layerStack;
2527 // figure out if this layerstack is mirrored
2528 // (more than one display) if so, pick the default display,
2529 // if not, pick the only display it's on.
2530 disp.clear();
2531 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2532 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002533 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002534 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002535 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002536 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002537 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002538 break;
2539 }
2540 }
2541 }
2542 }
Chet Haase91d25932013-04-11 15:24:55 -07002543
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002544 if (disp == nullptr) {
2545 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2546 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002547
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002548 // could be null when this layer is using a layerStack
2549 // that is not visible on any display. Also can occur at
2550 // screen off/on times.
2551 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002552 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002553
2554 // disp can be null if there is no display available at all to get
2555 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002556 if (disp != nullptr) {
2557 layer->updateTransformHint(disp);
2558 }
Robert Carr2047fae2016-11-28 14:09:09 -08002559
2560 first = false;
2561 });
Mathias Agopian84300952012-11-21 16:02:13 -08002562 }
2563
2564
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 /*
2566 * Perform our own transaction if needed
2567 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002568
2569 if (mLayersAdded) {
2570 mLayersAdded = false;
2571 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 mVisibleRegionsDirty = true;
2573 }
2574
2575 // some layers might have been removed, so
2576 // we need to update the regions they're exposing.
2577 if (mLayersRemoved) {
2578 mLayersRemoved = false;
2579 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002580 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002581 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 // this layer is not visible anymore
2583 // TODO: we could traverse the tree from front to back and
2584 // compute the actual visible region
2585 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 Region visibleReg;
2587 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002588 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 }
2592
2593 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002594
2595 updateCursorAsync();
2596}
2597
2598void SurfaceFlinger::updateCursorAsync()
2599{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2601 auto& displayDevice = mDisplays[displayId];
2602 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002603 continue;
2604 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605
2606 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2607 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002608 }
2609 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002610}
2611
2612void SurfaceFlinger::commitTransaction()
2613{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002614 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 for (const auto& l : mLayersPendingRemoval) {
2617 recordBufferingStats(l->getName().string(),
2618 l->getOccupancyHistory(true));
2619 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620 }
2621 mLayersPendingRemoval.clear();
2622 }
2623
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002624 // If this transaction is part of a window animation then the next frame
2625 // we composite should be considered an animation as well.
2626 mAnimCompositionPending = mAnimTransactionPending;
2627
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002629 // clear the "changed" flags in current state
2630 mCurrentState.colorMatrixChanged = false;
2631
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 mDrawingState.traverseInZOrder([](Layer* layer) {
2633 layer->commitChildList();
2634 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002635 mTransactionPending = false;
2636 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638}
2639
Chia-I Wuab0c3192017-08-01 11:29:00 -07002640void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002641 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642{
Mathias Agopian841cde52012-03-01 15:44:37 -08002643 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region aboveOpaqueLayers;
2647 Region aboveCoveredLayers;
2648 Region dirty;
2649
Mathias Agopian87baae12012-07-31 12:38:26 -07002650 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Robert Carr2047fae2016-11-28 14:09:09 -08002652 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002654 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655
Jesse Hall01e29052013-02-19 16:13:35 -08002656 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002657 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002658 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002659
Mathias Agopianab028732010-03-16 16:41:46 -07002660 /*
2661 * opaqueRegion: area of a surface that is fully opaque.
2662 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002664
2665 /*
2666 * visibleRegion: area of a surface that is visible on screen
2667 * and not fully transparent. This is essentially the layer's
2668 * footprint minus the opaque regions above it.
2669 * Areas covered by a translucent surface are considered visible.
2670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002672
2673 /*
2674 * coveredRegion: area of a surface that is covered by all
2675 * visible regions above it (which includes the translucent areas).
2676 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002678
Jesse Halla8026d22012-09-25 13:25:04 -07002679 /*
2680 * transparentRegion: area of a surface that is hinted to be completely
2681 * transparent. This is only used to tell when the layer has no visible
2682 * non-transparent regions and can be removed from the layer list. It
2683 * does not affect the visibleRegion of this layer or any layers
2684 * beneath it. The hint may not be correct if apps don't respect the
2685 * SurfaceView restrictions (which, sadly, some don't).
2686 */
2687 Region transparentRegion;
2688
Mathias Agopianab028732010-03-16 16:41:46 -07002689
2690 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002691 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002692 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002696 if (!visibleRegion.isEmpty()) {
2697 // Remove the transparent area from the visible region
2698 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002699 if (tr.preserveRects()) {
2700 // transform the transparent region
2701 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002703 // transformation too complex, can't do the
2704 // transparent region optimization.
2705 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 }
Mathias Agopianab028732010-03-16 16:41:46 -07002707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708
Mathias Agopianab028732010-03-16 16:41:46 -07002709 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002711 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002712 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2713 // the opaque region is the layer's footprint
2714 opaqueRegion = visibleRegion;
2715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 }
2717 }
2718
Robert Carre5f4f692018-01-12 13:12:28 -08002719 if (visibleRegion.isEmpty()) {
2720 layer->clearVisibilityRegions();
2721 return;
2722 }
2723
Mathias Agopianab028732010-03-16 16:41:46 -07002724 // Clip the covered region to the visible region
2725 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2726
2727 // Update aboveCoveredLayers for next (lower) layer
2728 aboveCoveredLayers.orSelf(visibleRegion);
2729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 // subtract the opaque region covered by the layers above us
2731 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732
2733 // compute this layer's dirty region
2734 if (layer->contentDirty) {
2735 // we need to invalidate the whole region
2736 dirty = visibleRegion;
2737 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 layer->contentDirty = false;
2740 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002741 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002742 * the exposed region consists of two components:
2743 * 1) what's VISIBLE now and was COVERED before
2744 * 2) what's EXPOSED now less what was EXPOSED before
2745 *
2746 * note that (1) is conservative, we start with the whole
2747 * visible region but only keep what used to be covered by
2748 * something -- which mean it may have been exposed.
2749 *
2750 * (2) handles areas that were not covered by anything but got
2751 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002752 */
Mathias Agopianab028732010-03-16 16:41:46 -07002753 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002754 const Region oldVisibleRegion = layer->visibleRegion;
2755 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002756 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2757 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 }
2759 dirty.subtractSelf(aboveOpaqueLayers);
2760
2761 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002762 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Mathias Agopianab028732010-03-16 16:41:46 -07002764 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002766
Jesse Halla8026d22012-09-25 13:25:04 -07002767 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 layer->setVisibleRegion(visibleRegion);
2769 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002770 layer->setVisibleNonTransparentRegion(
2771 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002772 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Mathias Agopian87baae12012-07-31 12:38:26 -07002774 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775}
2776
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002778 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002779 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002781 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002782 }
2783 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002784}
2785
Dan Stoza6b9454d2014-11-07 16:00:59 -08002786bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 ALOGV("handlePageFlip");
2789
Brian Andersond6927fb2016-07-23 23:37:30 -07002790 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002793 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002794 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002795
2796 // Store the set of layers that need updates. This set must not change as
2797 // buffers are being latched, as this could result in a deadlock.
2798 // Example: Two producers share the same command stream and:
2799 // 1.) Layer 0 is latched
2800 // 2.) Layer 0 gets a new frame
2801 // 2.) Layer 1 gets a new frame
2802 // 3.) Layer 1 is latched.
2803 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2804 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002805 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002806 if (layer->hasQueuedFrame()) {
2807 frameQueued = true;
2808 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002810 } else {
2811 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002813 } else {
2814 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815 }
Robert Carr2047fae2016-11-28 14:09:09 -08002816 });
2817
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002819 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002821 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002822 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002823 newDataLatched = true;
2824 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002826
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002827 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002828
2829 // If we will need to wake up at some time in the future to deal with a
2830 // queued frame that shouldn't be displayed during this vsync period, wake
2831 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002832 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 signalLayerUpdate();
2834 }
2835
2836 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002837 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838}
2839
Mathias Agopianad456f92011-01-13 17:53:01 -08002840void SurfaceFlinger::invalidateHwcGeometry()
2841{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002843}
2844
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002845
Fabien Sanglard830b8472016-11-30 16:35:58 -08002846void SurfaceFlinger::doDisplayComposition(
2847 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002848 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849{
Dan Stoza71433162014-02-04 16:22:36 -08002850 // We only need to actually compose the display if:
2851 // 1) It is being handled by hardware composer, which may need this to
2852 // keep its virtual display state machine in sync, or
2853 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002854 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002855 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002857 return;
2858 }
2859
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002861 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002862
2863 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002864 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Chia-I Wub02087d2017-11-09 10:19:54 -08002867bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002870
Chia-I Wub02087d2017-11-09 10:19:54 -08002871 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002872 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002873 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002874 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2875 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2876 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2877 HWC2::Capability::SkipClientColorTransform);
2878 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002879
2880 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002881 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2882 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002883 if (applyColorMatrix) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07002884 oldColorMatrix = getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
2885 legacySrgbSaturationMatrix = mDrawingState.colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002886 }
2887
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 if (hasClientComposition) {
2889 ALOGV("hasClientComposition");
2890
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002891 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002892 if (displayDevice->hasWideColorGamut()) {
2893 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002894 }
2895 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002896 getBE().mRenderEngine->setDisplayMaxLuminance(
2897 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002898
Chia-I Wu7f402902017-11-09 12:51:10 -08002899 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002900 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002901 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002902 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002903
2904 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002905 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002906 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2907 }
2908 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002909 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002910
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002911 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002913 // when using overlays, we assume a fully transparent framebuffer
2914 // NOTE: we could reduce how much we need to clear, for instance
2915 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002916 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002917 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002918 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002920 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002921 // we're left with the letterbox region
2922 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002924
2925 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002927
Mathias Agopianb9494d52012-04-18 02:28:45 -07002928 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002929 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002930 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002932 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002933 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002934
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002936 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002937 // scissor on the main display. It should never be needed
2938 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 const Rect& bounds(displayDevice->getBounds());
2940 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941 if (scissor != bounds) {
2942 // scissor doesn't match the screen's dimensions, so we
2943 // need to clear everything outside of it and enable
2944 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002945
Mathias Agopianf45c5102012-10-24 16:29:17 -07002946 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002948 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002949 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002950 }
2951 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002952 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002953
Mathias Agopian85d751c2012-08-29 16:59:24 -07002954 /*
2955 * and then, render the layers targeted at the framebuffer
2956 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002957
Dan Stoza9e56aa02015-11-02 13:00:03 -08002958 ALOGV("Rendering client layers");
2959 const Transform& displayTransform = displayDevice->getTransform();
2960 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 bool firstLayer = true;
2963 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002964 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 displayTransform.transform(layer->visibleRegion)));
2966 ALOGV("Layer: %s", layer->getName().string());
2967 ALOGV(" Composition type: %s",
2968 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002969 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 switch (layer->getCompositionType(hwcId)) {
2971 case HWC2::Composition::Cursor:
2972 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002973 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002975 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002977 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002979 // never clear the very first layer since we're
2980 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002981 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002982 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002983 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002984 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002986 // Only apply saturation matrix layer that is legacy SRGB dataspace
2987 // when auto color mode is on.
2988 bool restore = false;
2989 mat4 savedMatrix;
2990 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2991 layer->isLegacySrgbDataSpace()) {
2992 savedMatrix =
2993 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
2994 restore = true;
2995 }
chaviwa76b2712017-09-20 12:02:26 -07002996 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002997 if (restore) {
2998 getRenderEngine().setupColorTransform(savedMatrix);
2999 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003000 break;
3001 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003003 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003004 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 } else {
3006 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003007 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003009 }
3010 } else {
3011 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003013 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003015 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003016 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003017 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003018 }
3019 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003020
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003021 if (applyColorMatrix) {
3022 getRenderEngine().setupColorTransform(oldColorMatrix);
3023 }
3024
Mathias Agopianf45c5102012-10-24 16:29:17 -07003025 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003026 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003027 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028}
3029
Fabien Sanglard830b8472016-11-30 16:35:58 -08003030void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3031 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003032 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003033 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034}
3035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003037 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003038 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003039 const sp<Layer>& lbc,
3040 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003041{
Dan Stoza7d89d062015-04-30 13:29:25 -07003042 // add this layer to the current state list
3043 {
3044 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003046 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3047 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003048 return NO_MEMORY;
3049 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 if (parent == nullptr) {
3051 mCurrentState.layersSortedByZ.add(lbc);
3052 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003053 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003054 ALOGE("addClientLayer called with a removed parent");
3055 return NAME_NOT_FOUND;
3056 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 parent->addChild(lbc);
3058 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003059
Dan Stoza101d8dc2018-02-27 15:42:25 -08003060 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003061 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3062 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3063 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3064 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3065 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 mLayersAdded = true;
3067 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003068 }
3069
Mathias Agopian96f08192010-06-02 23:28:45 -07003070 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003071 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003072
Dan Stoza7d89d062015-04-30 13:29:25 -07003073 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003074}
3075
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003076status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003077 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003078 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3079}
Robert Carr7f9b8992017-03-10 11:08:39 -08003080
chaviwca27f252018-02-06 16:46:39 -08003081status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3082 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003083 if (layer->isPendingRemoval()) {
3084 return NO_ERROR;
3085 }
3086
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003088 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003089 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003090 if (topLevelOnly) {
3091 return NO_ERROR;
3092 }
3093
Chia-I Wu98f1c102017-05-30 14:54:08 -07003094 sp<Layer> ancestor = p;
3095 while (ancestor->getParent() != nullptr) {
3096 ancestor = ancestor->getParent();
3097 }
3098 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3099 ALOGE("removeLayer called with a layer whose parent has been removed");
3100 return NAME_NOT_FOUND;
3101 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003102
3103 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003104 } else {
3105 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003106 }
3107
Robert Carr136e2f62017-02-08 17:54:29 -08003108 // As a matter of normal operation, the LayerCleaner will produce a second
3109 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3110 // so we will succeed in promoting it, but it's already been removed
3111 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3112 // otherwise something has gone wrong and we are leaking the layer.
3113 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003114 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3115 layer->getName().string(),
3116 (p != nullptr) ? p->getName().string() : "no-parent");
3117 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003118 } else if (index < 0) {
3119 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003120 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121
Chia-I Wuc6657022017-08-15 11:18:17 -07003122 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003123 mLayersPendingRemoval.add(layer);
3124 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003125 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126 setTransactionFlags(eTransactionNeeded);
3127 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128}
3129
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003130uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003131 return android_atomic_release_load(&mTransactionFlags);
3132}
3133
Mathias Agopian3f844832013-08-07 21:24:32 -07003134uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3136}
3137
Mathias Agopian3f844832013-08-07 21:24:32 -07003138uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003139 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3140}
3141
3142uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3143 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003145 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003147 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 }
3149 return old;
3150}
3151
chaviwca27f252018-02-06 16:46:39 -08003152bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3153 for (const ComposerState& state : states) {
3154 // Here we need to check that the interface we're given is indeed
3155 // one of our own. A malicious client could give us a nullptr
3156 // IInterface, or one of its own or even one of our own but a
3157 // different type. All these situations would cause us to crash.
3158 if (state.client == nullptr) {
3159 return true;
3160 }
3161
3162 sp<IBinder> binder = IInterface::asBinder(state.client);
3163 if (binder == nullptr) {
3164 return true;
3165 }
3166
3167 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3168 return true;
3169 }
3170 }
3171 return false;
3172}
3173
Mathias Agopian8b33f032012-07-24 20:43:54 -07003174void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003175 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003176 const Vector<DisplayState>& displays,
3177 uint32_t flags)
3178{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003179 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003180 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003181 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003182
chaviwca27f252018-02-06 16:46:39 -08003183 if (containsAnyInvalidClientState(states)) {
3184 return;
3185 }
3186
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003187 if (flags & eAnimation) {
3188 // For window updates that are part of an animation we must wait for
3189 // previous animation "frames" to be handled.
3190 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003191 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 if (CC_UNLIKELY(err != NO_ERROR)) {
3193 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003194 // caller after a few seconds.
3195 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3196 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003197 mAnimTransactionPending = false;
3198 break;
3199 }
3200 }
3201 }
3202
chaviwca27f252018-02-06 16:46:39 -08003203 for (const DisplayState& display : displays) {
3204 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003205 }
3206
chaviwca27f252018-02-06 16:46:39 -08003207 for (const ComposerState& state : states) {
3208 transactionFlags |= setClientStateLocked(state);
3209 }
3210
3211 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3212 // as destroyed should only occur after setting all other states. This is to allow for a
3213 // child re-parent to happen before marking its original parent as destroyed (which would
3214 // then mark the child as destroyed).
3215 for (const ComposerState& state : states) {
3216 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003217 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003218
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003219 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3220 // anyway. This can be used as a flush mechanism for previous async transactions.
3221 // Empty animation transaction can be used to simulate back-pressure, so also force a
3222 // transaction for empty animation transactions.
3223 if (transactionFlags == 0 &&
3224 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003225 transactionFlags = eTransactionNeeded;
3226 }
3227
Mathias Agopian386aa982011-11-07 21:58:03 -08003228 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003229 if (mInterceptor->isEnabled()) {
3230 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003231 }
Irvel468051e2016-06-13 16:44:44 -07003232
Mathias Agopian386aa982011-11-07 21:58:03 -08003233 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003234 const auto start = (flags & eEarlyWakeup)
3235 ? VSyncModulator::TransactionStart::EARLY
3236 : VSyncModulator::TransactionStart::NORMAL;
3237 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003238
3239 // if this is a synchronous transaction, wait for it to take effect
3240 // before returning.
3241 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003242 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003243 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 if (flags & eAnimation) {
3245 mAnimTransactionPending = true;
3246 }
3247 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003248 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3249 if (CC_UNLIKELY(err != NO_ERROR)) {
3250 // just in case something goes wrong in SF, return to the
3251 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003252 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3253 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003254 break;
3255 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003256 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257 }
3258}
3259
Mathias Agopiane57f2922012-08-09 16:29:12 -07003260uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3261{
Jesse Hall9a143922012-10-04 16:29:19 -07003262 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3263 if (dpyIdx < 0)
3264 return 0;
3265
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003267 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003268 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003269 const uint32_t what = s.what;
3270 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003271 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003272 disp.surface = s.surface;
3273 flags |= eDisplayTransactionNeeded;
3274 }
3275 }
3276 if (what & DisplayState::eLayerStackChanged) {
3277 if (disp.layerStack != s.layerStack) {
3278 disp.layerStack = s.layerStack;
3279 flags |= eDisplayTransactionNeeded;
3280 }
3281 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003282 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283 if (disp.orientation != s.orientation) {
3284 disp.orientation = s.orientation;
3285 flags |= eDisplayTransactionNeeded;
3286 }
3287 if (disp.frame != s.frame) {
3288 disp.frame = s.frame;
3289 flags |= eDisplayTransactionNeeded;
3290 }
3291 if (disp.viewport != s.viewport) {
3292 disp.viewport = s.viewport;
3293 flags |= eDisplayTransactionNeeded;
3294 }
3295 }
Michael Lentine47e45402014-07-18 15:34:25 -07003296 if (what & DisplayState::eDisplaySizeChanged) {
3297 if (disp.width != s.width) {
3298 disp.width = s.width;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 if (disp.height != s.height) {
3302 disp.height = s.height;
3303 flags |= eDisplayTransactionNeeded;
3304 }
3305 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003306 }
3307 return flags;
3308}
3309
chaviwca27f252018-02-06 16:46:39 -08003310uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3311 const layer_state_t& s = composerState.state;
3312 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3313
Mathias Agopian13127d82013-03-05 17:47:11 -08003314 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003315 if (layer == nullptr) {
3316 return 0;
3317 }
3318
3319 if (layer->isPendingRemoval()) {
3320 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3321 return 0;
3322 }
3323
3324 uint32_t flags = 0;
3325
3326 const uint32_t what = s.what;
3327 bool geometryAppliesWithResize =
3328 what & layer_state_t::eGeometryAppliesWithResize;
3329 if (what & layer_state_t::ePositionChanged) {
3330 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3331 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 }
chaviw8b3871a2017-11-01 17:41:01 -07003333 }
3334 if (what & layer_state_t::eLayerChanged) {
3335 // NOTE: index needs to be calculated before we update the state
3336 const auto& p = layer->getParent();
3337 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003339 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003340 mCurrentState.layersSortedByZ.removeAt(idx);
3341 mCurrentState.layersSortedByZ.add(layer);
3342 // we need traversal (state changed)
3343 // AND transaction (list changed)
3344 flags |= eTransactionNeeded|eTraversalNeeded;
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 } else {
3347 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003348 flags |= eTransactionNeeded|eTraversalNeeded;
3349 }
3350 }
chaviw8b3871a2017-11-01 17:41:01 -07003351 }
3352 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003353 // NOTE: index needs to be calculated before we update the state
3354 const auto& p = layer->getParent();
3355 if (p == nullptr) {
3356 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3357 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3358 mCurrentState.layersSortedByZ.removeAt(idx);
3359 mCurrentState.layersSortedByZ.add(layer);
3360 // we need traversal (state changed)
3361 // AND transaction (list changed)
3362 flags |= eTransactionNeeded|eTraversalNeeded;
3363 }
3364 } else {
3365 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3366 flags |= eTransactionNeeded|eTraversalNeeded;
3367 }
chaviw8b3871a2017-11-01 17:41:01 -07003368 }
3369 }
3370 if (what & layer_state_t::eSizeChanged) {
3371 if (layer->setSize(s.w, s.h)) {
3372 flags |= eTraversalNeeded;
3373 }
3374 }
3375 if (what & layer_state_t::eAlphaChanged) {
3376 if (layer->setAlpha(s.alpha))
3377 flags |= eTraversalNeeded;
3378 }
3379 if (what & layer_state_t::eColorChanged) {
3380 if (layer->setColor(s.color))
3381 flags |= eTraversalNeeded;
3382 }
3383 if (what & layer_state_t::eMatrixChanged) {
3384 if (layer->setMatrix(s.matrix))
3385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eTransparentRegionChanged) {
3388 if (layer->setTransparentRegionHint(s.transparentRegion))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eFlagsChanged) {
3392 if (layer->setFlags(s.flags, s.mask))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eCropChanged) {
3396 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eFinalCropChanged) {
3400 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3401 flags |= eTraversalNeeded;
3402 }
3403 if (what & layer_state_t::eLayerStackChanged) {
3404 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3405 // We only allow setting layer stacks for top level layers,
3406 // everything else inherits layer stack from its parent.
3407 if (layer->hasParent()) {
3408 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3409 layer->getName().string());
3410 } else if (idx < 0) {
3411 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3412 "that also does not appear in the top level layer list. Something"
3413 " has gone wrong.", layer->getName().string());
3414 } else if (layer->setLayerStack(s.layerStack)) {
3415 mCurrentState.layersSortedByZ.removeAt(idx);
3416 mCurrentState.layersSortedByZ.add(layer);
3417 // we need traversal (state changed)
3418 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003419 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003420 }
3421 }
3422 if (what & layer_state_t::eDeferTransaction) {
3423 if (s.barrierHandle != nullptr) {
3424 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3425 } else if (s.barrierGbp != nullptr) {
3426 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3427 if (authenticateSurfaceTextureLocked(gbp)) {
3428 const auto& otherLayer =
3429 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3430 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3431 } else {
3432 ALOGE("Attempt to defer transaction to to an"
3433 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003434 }
3435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 // We don't trigger a traversal here because if no other state is
3437 // changed, we don't want this to cause any more work
3438 }
3439 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003440 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003441 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003442 if (!hadParent) {
3443 mCurrentState.layersSortedByZ.remove(layer);
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 if (what & layer_state_t::eReparentChildren) {
3449 if (layer->reparentChildren(s.reparentHandle)) {
3450 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003451 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 if (what & layer_state_t::eDetachChildren) {
3454 layer->detachChildren();
3455 }
3456 if (what & layer_state_t::eOverrideScalingModeChanged) {
3457 layer->setOverrideScalingMode(s.overrideScalingMode);
3458 // We don't trigger a traversal here because if no other state is
3459 // changed, we don't want this to cause any more work
3460 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003461 return flags;
3462}
3463
chaviwca27f252018-02-06 16:46:39 -08003464void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3465 const layer_state_t& state = composerState.state;
3466 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3467
3468 sp<Layer> layer(client->getLayerUser(state.surface));
3469 if (layer == nullptr) {
3470 return;
3471 }
3472
3473 if (layer->isPendingRemoval()) {
3474 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3475 return;
3476 }
3477
3478 if (state.what & layer_state_t::eDestroySurface) {
3479 removeLayerLocked(mStateLock, layer);
3480 }
3481}
3482
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003484 const String8& name,
3485 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003486 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003487 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003488 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003490 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003491 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003492 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003494 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003495
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003496 status_t result = NO_ERROR;
3497
3498 sp<Layer> layer;
3499
Cody Northropbc755282017-03-31 12:00:08 -06003500 String8 uniqueName = getUniqueLayerName(name);
3501
Mathias Agopian3165cc22012-08-08 19:42:09 -07003502 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3503 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003504 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003505 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003506 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 break;
chaviw13fdc492017-06-27 12:40:18 -07003509 case ISurfaceComposerClient::eFXSurfaceColor:
3510 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003511 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003512 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 break;
3514 default:
3515 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 break;
3517 }
3518
Dan Stoza7d89d062015-04-30 13:29:25 -07003519 if (result != NO_ERROR) {
3520 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003522
Chia-I Wuab0c3192017-08-01 11:29:00 -07003523 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3524 // TODO b/64227542
3525 if (windowType == 441731) {
3526 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3527 layer->setPrimaryDisplayOnly();
3528 }
3529
Albert Chaulk479c60c2017-01-27 14:21:34 -05003530 layer->setInfo(windowType, ownerUid);
3531
Robert Carr1f0a16a2016-10-24 16:27:39 -07003532 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003533 if (result != NO_ERROR) {
3534 return result;
3535 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003536 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003537
3538 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540}
3541
Cody Northropbc755282017-03-31 12:00:08 -06003542String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3543{
3544 bool matchFound = true;
3545 uint32_t dupeCounter = 0;
3546
3547 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3548 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3549
3550 // Loop over layers until we're sure there is no matching name
3551 while (matchFound) {
3552 matchFound = false;
3553 mDrawingState.traverseInZOrder([&](Layer* layer) {
3554 if (layer->getName() == uniqueName) {
3555 matchFound = true;
3556 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3557 }
3558 });
3559 }
3560
3561 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3562
3563 return uniqueName;
3564}
3565
David Sodman0c69cad2017-08-21 12:12:51 -07003566status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003567 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3568 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569{
3570 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003571 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 case PIXEL_FORMAT_TRANSPARENT:
3573 case PIXEL_FORMAT_TRANSLUCENT:
3574 format = PIXEL_FORMAT_RGBA_8888;
3575 break;
3576 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003577 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578 break;
3579 }
3580
David Sodman0c69cad2017-08-21 12:12:51 -07003581 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3582 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003584 *handle = layer->getHandle();
3585 *gbp = layer->getProducer();
3586 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003587 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588
David Sodman0c69cad2017-08-21 12:12:51 -07003589 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591}
3592
chaviw13fdc492017-06-27 12:40:18 -07003593status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003595 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596{
chaviw13fdc492017-06-27 12:40:18 -07003597 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003600}
3601
Mathias Agopianac9fa422013-02-11 16:40:36 -08003602status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603{
Robert Carr9524cb32017-02-13 11:32:32 -08003604 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003605 status_t err = NO_ERROR;
3606 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003607 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003608 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003609 err = removeLayer(l);
3610 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3611 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003612 }
3613 return err;
3614}
3615
Mathias Agopian13127d82013-03-05 17:47:11 -08003616status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003617{
Mathias Agopian67106042013-03-14 19:18:13 -07003618 // called by ~LayerCleaner() when all references to the IBinder (handle)
3619 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003620 sp<Layer> l = layer.promote();
3621 if (l == nullptr) {
3622 // The layer has already been removed, carry on
3623 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003624 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003625 // If we have a parent, then we can continue to live as long as it does.
3626 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627}
3628
Mathias Agopianb60314a2012-04-10 22:09:54 -07003629// ---------------------------------------------------------------------------
3630
Andy McFadden13a082e2012-08-24 10:16:42 -07003631void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003632 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003633 Vector<ComposerState> state;
3634 Vector<DisplayState> displays;
3635 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003636 d.what = DisplayState::eDisplayProjectionChanged |
3637 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003638 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003639 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003640 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003641 d.frame.makeInvalid();
3642 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003643 d.width = 0;
3644 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003645 displays.add(d);
3646 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003647 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3648 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003649
David Sodman105b7dc2017-11-04 20:28:14 -07003650 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003651 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003652 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003653
Brian Andersond0010582017-03-07 13:20:31 -08003654 // Use phase of 0 since phase is not known.
3655 // Use latency of 0, which will snap to the ideal latency.
3656 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003657}
3658
3659void SurfaceFlinger::initializeDisplays() {
3660 class MessageScreenInitialized : public MessageBase {
3661 SurfaceFlinger* flinger;
3662 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003663 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003664 virtual bool handler() {
3665 flinger->onInitializeDisplays();
3666 return true;
3667 }
3668 };
3669 sp<MessageBase> msg = new MessageScreenInitialized(this);
3670 postMessageAsync(msg); // we may be called from main thread, use async message
3671}
3672
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003673void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003674 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003675 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3676 this);
3677 int32_t type = hw->getDisplayType();
3678 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681 return;
3682 }
3683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684 hw->setPowerMode(mode);
3685 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3686 ALOGW("Trying to set power mode for virtual display");
3687 return;
3688 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003689
Lloyd Pique4d234852018-01-22 17:21:36 -08003690 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003691 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003692 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3693 if (idx < 0) {
3694 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3695 return;
3696 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003697 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003698 }
3699
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003700 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003701 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003703 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3704 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 // FIXME: eventthread only knows about the main display right now
3706 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003707 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003711 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003712 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003713
3714 struct sched_param param = {0};
3715 param.sched_priority = 1;
3716 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3717 ALOGW("Couldn't set SCHED_FIFO on display on");
3718 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003719 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003720 // Turn off the display
3721 struct sched_param param = {0};
3722 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3723 ALOGW("Couldn't set SCHED_OTHER on display off");
3724 }
3725
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003726 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3727 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003728 disableHardwareVsync(true); // also cancels any in-progress resync
3729
Mathias Agopiancde87a32012-09-13 14:09:01 -07003730 // FIXME: eventthread only knows about the main display right now
3731 mEventThread->onScreenReleased();
3732 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 getHwComposer().setPowerMode(type, mode);
3735 mVisibleRegionsDirty = true;
3736 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003737 } else if (mode == HWC_POWER_MODE_DOZE ||
3738 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003739 // Update display while dozing
3740 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003741 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3742 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003743 // FIXME: eventthread only knows about the main display right now
3744 mEventThread->onScreenAcquired();
3745 resyncToHardwareVsync(true);
3746 }
3747 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3748 // Leave display going to doze
3749 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3750 disableHardwareVsync(true); // also cancels any in-progress resync
3751 // FIXME: eventthread only knows about the main display right now
3752 mEventThread->onScreenReleased();
3753 }
3754 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003755 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003756 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003758 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003759 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003760}
3761
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3763 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003764 SurfaceFlinger& mFlinger;
3765 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003767 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003768 MessageSetPowerMode(SurfaceFlinger& flinger,
3769 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3770 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003771 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003773 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003775 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003776 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 ALOGW("Attempt to set power mode = %d for virtual display",
3778 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003779 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003780 mFlinger.setPowerModeInternal(
3781 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003782 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783 return true;
3784 }
3785 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003786 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003787 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003788}
3789
3790// ---------------------------------------------------------------------------
3791
Lloyd Pique755e3192018-01-31 16:46:15 -08003792status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3793 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003794 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003795
Mathias Agopianbd115332013-04-18 16:41:04 -07003796 IPCThreadState* ipc = IPCThreadState::self();
3797 const int pid = ipc->getCallingPid();
3798 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003799
Mathias Agopianbd115332013-04-18 16:41:04 -07003800 if ((uid != AID_SHELL) &&
3801 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003802 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003803 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003805 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003806 // (this would indicate SF is stuck, but we want to be able to
3807 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003808 status_t err = mStateLock.timedLock(s2ns(1));
3809 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003810 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003811 result.appendFormat(
3812 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3813 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003814 }
3815
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003816 bool dumpAll = true;
3817 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003819
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821 if ((index < numArgs) &&
3822 (args[index] == String16("--list"))) {
3823 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003825 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826 }
3827
3828 if ((index < numArgs) &&
3829 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003832 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834
3835 if ((index < numArgs) &&
3836 (args[index] == String16("--latency-clear"))) {
3837 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003839 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003841
3842 if ((index < numArgs) &&
3843 (args[index] == String16("--dispsync"))) {
3844 index++;
3845 mPrimaryDispSync.dump(result);
3846 dumpAll = false;
3847 }
Dan Stozab90cf072015-03-05 11:05:59 -08003848
3849 if ((index < numArgs) &&
3850 (args[index] == String16("--static-screen"))) {
3851 index++;
3852 dumpStaticScreenStats(result);
3853 dumpAll = false;
3854 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003855
3856 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003857 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003858 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003859 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003860 dumpAll = false;
3861 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003862
3863 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3864 index++;
3865 dumpWideColorInfo(result);
3866 dumpAll = false;
3867 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003868
3869 if ((index < numArgs) &&
3870 (args[index] == String16("--enable-layer-stats"))) {
3871 index++;
3872 mLayerStats.enable();
3873 dumpAll = false;
3874 }
3875
3876 if ((index < numArgs) &&
3877 (args[index] == String16("--disable-layer-stats"))) {
3878 index++;
3879 mLayerStats.disable();
3880 dumpAll = false;
3881 }
3882
3883 if ((index < numArgs) &&
3884 (args[index] == String16("--clear-layer-stats"))) {
3885 index++;
3886 mLayerStats.clear();
3887 dumpAll = false;
3888 }
3889
3890 if ((index < numArgs) &&
3891 (args[index] == String16("--dump-layer-stats"))) {
3892 index++;
3893 mLayerStats.dump(result);
3894 dumpAll = false;
3895 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003896
3897 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3898 index++;
3899 mTimeStats.parseArgs(asProto, args, index, result);
3900 dumpAll = false;
3901 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003903
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003904 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003905 if (asProto) {
3906 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3907 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3908 } else {
3909 dumpAllLocked(args, index, result);
3910 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003911 }
3912
Mathias Agopian9795c422009-08-26 16:36:26 -07003913 if (locked) {
3914 mStateLock.unlock();
3915 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 }
3917 write(fd, result.string(), result.size());
3918 return NO_ERROR;
3919}
3920
Dan Stozac7014012014-02-14 15:03:43 -08003921void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3922 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003923{
Robert Carr2047fae2016-11-28 14:09:09 -08003924 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003925 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003926 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003927}
3928
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003931{
3932 String8 name;
3933 if (index < args.size()) {
3934 name = String8(args[index]);
3935 index++;
3936 }
3937
David Sodman105b7dc2017-11-04 20:28:14 -07003938 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003939 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003940 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003941
3942 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003943 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003944 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003945 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003947 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003948 }
Robert Carr2047fae2016-11-28 14:09:09 -08003949 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950 }
3951}
3952
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003954 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003955{
3956 String8 name;
3957 if (index < args.size()) {
3958 name = String8(args[index]);
3959 index++;
3960 }
3961
Robert Carr2047fae2016-11-28 14:09:09 -08003962 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003964 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965 }
Robert Carr2047fae2016-11-28 14:09:09 -08003966 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967
Svetoslavd85084b2014-03-20 10:28:31 -07003968 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003969}
3970
Jamie Gennis6547ff42013-07-16 20:12:42 -07003971// This should only be called from the main thread. Otherwise it would need
3972// the lock and should use mCurrentState rather than mDrawingState.
3973void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003974 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003976 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003977
3978 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3979}
3980
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003981void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003982{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003983 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003984
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003985 if (isLayerTripleBufferingDisabled())
3986 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003987
3988 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003989 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003990 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003991 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003992 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3993 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003994 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003995}
3996
Dan Stozab90cf072015-03-05 11:05:59 -08003997void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3998{
3999 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004000 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4001 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004002 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004003 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004004 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4005 b + 1, bucketTimeSec, percent);
4006 }
David Sodman4a36e932017-11-07 14:29:47 -08004007 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004008 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004009 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004010 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004011 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004012}
4013
Dan Stozae77c7662016-05-13 11:37:28 -07004014void SurfaceFlinger::recordBufferingStats(const char* layerName,
4015 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004016 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4017 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004018 for (const auto& segment : history) {
4019 if (!segment.usedThirdBuffer) {
4020 stats.twoBufferTime += segment.totalTime;
4021 }
4022 if (segment.occupancyAverage < 1.0f) {
4023 stats.doubleBufferedTime += segment.totalTime;
4024 } else if (segment.occupancyAverage < 2.0f) {
4025 stats.tripleBufferedTime += segment.totalTime;
4026 }
4027 ++stats.numSegments;
4028 stats.totalTime += segment.totalTime;
4029 }
4030}
4031
Brian Andersond6927fb2016-07-23 23:37:30 -07004032void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4033 result.appendFormat("Layer frame timestamps:\n");
4034
4035 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4036 const size_t count = currentLayers.size();
4037 for (size_t i=0 ; i<count ; i++) {
4038 currentLayers[i]->dumpFrameEvents(result);
4039 }
4040}
4041
Dan Stozae77c7662016-05-13 11:37:28 -07004042void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4043 result.append("Buffering stats:\n");
4044 result.append(" [Layer name] <Active time> <Two buffer> "
4045 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004046 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004047 typedef std::tuple<std::string, float, float, float> BufferTuple;
4048 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004049 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004050 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004051 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004052 if (stats.numSegments == 0) {
4053 continue;
4054 }
4055 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4056 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4057 stats.totalTime;
4058 float doubleBufferRatio = static_cast<float>(
4059 stats.doubleBufferedTime) / stats.totalTime;
4060 float tripleBufferRatio = static_cast<float>(
4061 stats.tripleBufferedTime) / stats.totalTime;
4062 sorted.insert({activeTime, {name, twoBufferRatio,
4063 doubleBufferRatio, tripleBufferRatio}});
4064 }
4065 for (const auto& sortedPair : sorted) {
4066 float activeTime = sortedPair.first;
4067 const BufferTuple& values = sortedPair.second;
4068 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4069 std::get<0>(values).c_str(), activeTime,
4070 std::get<1>(values), std::get<2>(values),
4071 std::get<3>(values));
4072 }
4073 result.append("\n");
4074}
4075
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004076void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4077 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004078 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079
4080 // TODO: print out if wide-color mode is active or not
4081
4082 for (size_t d = 0; d < mDisplays.size(); d++) {
4083 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4084 int32_t hwcId = displayDevice->getHwcDisplayId();
4085 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4086 continue;
4087 }
4088
4089 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004090 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004091 for (auto&& mode : modes) {
4092 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4093 }
4094
Peiyong Lina52f0292018-03-14 17:26:31 -07004095 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004096 result.appendFormat(" Current color mode: %s (%d)\n",
4097 decodeColorMode(currentMode).c_str(), currentMode);
4098 }
4099 result.append("\n");
4100}
4101
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004102LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004103 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004104 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4105 const State& state = useDrawing ? mDrawingState : mCurrentState;
4106 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004107 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004108 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004109 });
4110
4111 return layersProto;
4112}
4113
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004114LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4115 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004116 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004117
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004118 SizeProto* resolution = layersProto.mutable_resolution();
4119 resolution->set_w(displayDevice->getWidth());
4120 resolution->set_h(displayDevice->getHeight());
4121
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004122 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4123 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4124 layersProto.set_global_transform(
4125 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4126
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004127 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004128 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004129 LayerProto* layerProto = layersProto.add_layers();
4130 layer->writeToProto(layerProto, hwcId);
4131 }
4132 });
4133
4134 return layersProto;
4135}
4136
Mathias Agopian74d211a2013-04-22 16:55:35 +02004137void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4138 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004139{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004140 bool colorize = false;
4141 if (index < args.size()
4142 && (args[index] == String16("--color"))) {
4143 colorize = true;
4144 index++;
4145 }
4146
4147 Colorizer colorizer(colorize);
4148
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 // figure out if we're stuck somewhere
4150 const nsecs_t now = systemTime();
4151 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4152 const nsecs_t inTransaction(mDebugInTransaction);
4153 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4154 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4155
4156 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004157 * Dump library configuration.
4158 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004159
4160 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004161 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004162 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004163 appendSfConfigString(result);
4164 appendUiConfigString(result);
4165 appendGuiConfigString(result);
4166 result.append("\n");
4167
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004168 result.append("\nWide-Color information:\n");
4169 dumpWideColorInfo(result);
4170
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004171 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004172 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004173 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004174 result.append(SyncFeatures::getInstance().toString());
4175 result.append("\n");
4176
David Sodman105b7dc2017-11-04 20:28:14 -07004177 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004178
Andy McFadden41d67d72014-04-25 16:58:34 -07004179 colorizer.bold(result);
4180 result.append("DispSync configuration: ");
4181 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004182 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4183 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4184 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004185 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004186 result.append("\n");
4187
Dan Stozab90cf072015-03-05 11:05:59 -08004188 // Dump static screen stats
4189 result.append("\n");
4190 dumpStaticScreenStats(result);
4191 result.append("\n");
4192
Dan Stozae77c7662016-05-13 11:37:28 -07004193 dumpBufferingStats(result);
4194
Andy McFadden4803b742012-09-24 19:07:20 -07004195 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004196 * Dump the visible layer list
4197 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004198 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004199 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004200 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4201 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004203
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004204 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004205 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004206 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004207 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208
4209 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004210 * Dump Display state
4211 */
4212
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004214 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004216 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4217 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004218 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004219 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004220 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004221
4222 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223 * Dump SurfaceFlinger global state
4224 */
4225
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004227 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004229
Mathias Agopian888c8222012-08-04 21:10:38 -07004230 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004231 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004232
David Sodmanbc815282017-11-05 18:57:52 -08004233 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004235 if (hw) {
4236 hw->undefinedRegion.dump(result, "undefinedRegion");
4237 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4238 hw->getOrientation(), hw->isDisplayOn());
4239 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004240 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004241 " last eglSwapBuffers() time: %f us\n"
4242 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004243 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244 " refresh-rate : %f fps\n"
4245 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004246 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004247 " gpu_to_cpu_unsupported : %d\n"
4248 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249 mLastSwapBufferTime/1000.0,
4250 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004251 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004252 1e9 / activeConfig->getVsyncPeriod(),
4253 activeConfig->getDpiX(),
4254 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004255 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259
Mathias Agopian74d211a2013-04-22 16:55:35 +02004260 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004262
4263 /*
4264 * VSYNC state
4265 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004266 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004267 result.append("\n");
4268
4269 /*
4270 * HWC layer minidump
4271 */
4272 for (size_t d = 0; d < mDisplays.size(); d++) {
4273 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4274 int32_t hwcId = displayDevice->getHwcDisplayId();
4275 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4276 continue;
4277 }
4278
4279 result.appendFormat("Display %d HWC layers:\n", hwcId);
4280 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004281 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004282 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004283 });
Dan Stozae22aec72016-08-01 13:20:59 -07004284 result.append("\n");
4285 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004286
4287 /*
4288 * Dump HWComposer state
4289 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004291 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004293 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004294 result.appendFormat(" h/w composer %s\n",
4295 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004296 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297
4298 /*
4299 * Dump gralloc state
4300 */
4301 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4302 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004303
4304 /*
4305 * Dump VrFlinger state if in use.
4306 */
4307 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4308 result.append("VrFlinger state:\n");
4309 result.append(mVrFlinger->Dump().c_str());
4310 result.append("\n");
4311 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312}
4313
Mathias Agopian13127d82013-03-05 17:47:11 -08004314const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004315SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004316 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004317 wp<IBinder> dpy;
4318 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4319 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4320 dpy = mDisplays.keyAt(i);
4321 break;
4322 }
4323 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004324 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004325 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4326 // Just use the primary display so we have something to return
4327 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4328 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004329 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004330}
4331
Keun young Park63f165f2012-08-31 10:53:36 -07004332bool SurfaceFlinger::startDdmConnection()
4333{
4334 void* libddmconnection_dso =
4335 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4336 if (!libddmconnection_dso) {
4337 return false;
4338 }
4339 void (*DdmConnection_start)(const char* name);
4340 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004341 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004342 if (!DdmConnection_start) {
4343 dlclose(libddmconnection_dso);
4344 return false;
4345 }
4346 (*DdmConnection_start)(getServiceName());
4347 return true;
4348}
4349
Chia-I Wu28f320b2018-05-03 11:02:56 -07004350void SurfaceFlinger::updateColorMatrixLocked() {
4351 mat4 colorMatrix;
4352 if (mGlobalSaturationFactor != 1.0f) {
4353 // Rec.709 luma coefficients
4354 float3 luminance{0.213f, 0.715f, 0.072f};
4355 luminance *= 1.0f - mGlobalSaturationFactor;
4356 mat4 saturationMatrix = mat4(
4357 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4358 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4359 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4360 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4361 );
4362 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4363 } else {
4364 colorMatrix = mClientColorMatrix * mDaltonizer();
4365 }
4366
4367 if (mCurrentState.colorMatrix != colorMatrix) {
4368 mCurrentState.colorMatrix = colorMatrix;
4369 mCurrentState.colorMatrixChanged = true;
4370 setTransactionFlags(eTransactionNeeded);
4371 }
4372}
4373
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004374status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 switch (code) {
4376 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004377 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004379 case CLEAR_ANIMATION_FRAME_STATS:
4380 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004381 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004382 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004383 case ENABLE_VSYNC_INJECTIONS:
4384 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385 {
4386 // codes that require permission check
4387 IPCThreadState* ipc = IPCThreadState::self();
4388 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004389 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004390 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004391 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004392 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004393 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 break;
4396 }
Robert Carr1db73f62016-12-21 12:58:51 -08004397 /*
4398 * Calling setTransactionState is safe, because you need to have been
4399 * granted a reference to Client* and Handle* to do anything with it.
4400 *
4401 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4402 */
4403 case SET_TRANSACTION_STATE:
4404 case CREATE_SCOPED_CONNECTION:
4405 {
4406 return OK;
4407 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004408 case CAPTURE_SCREEN:
4409 {
4410 // codes that require permission check
4411 IPCThreadState* ipc = IPCThreadState::self();
4412 const int pid = ipc->getCallingPid();
4413 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004414 if ((uid != AID_GRAPHICS) &&
4415 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004416 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004417 return PERMISSION_DENIED;
4418 }
4419 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004420 }
chaviwa76b2712017-09-20 12:02:26 -07004421 case CAPTURE_LAYERS: {
4422 IPCThreadState* ipc = IPCThreadState::self();
4423 const int pid = ipc->getCallingPid();
4424 const int uid = ipc->getCallingUid();
4425 if ((uid != AID_GRAPHICS) &&
4426 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4427 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4428 return PERMISSION_DENIED;
4429 }
4430 break;
4431 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004433 return OK;
4434}
4435
4436status_t SurfaceFlinger::onTransact(
4437 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4438{
4439 status_t credentialCheck = CheckTransactCodeCredentials(code);
4440 if (credentialCheck != OK) {
4441 return credentialCheck;
4442 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4445 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004446 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004447 IPCThreadState* ipc = IPCThreadState::self();
4448 const int uid = ipc->getCallingUid();
4449 if (CC_UNLIKELY(uid != AID_SYSTEM
4450 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004451 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004452 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004453 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 return PERMISSION_DENIED;
4455 }
4456 int n;
4457 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004458 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004459 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004460 return NO_ERROR;
4461 case 1002: // SHOW_UPDATES
4462 n = data.readInt32();
4463 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004464 invalidateHwcGeometry();
4465 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004466 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004467 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004468 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004469 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004471 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004472 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004473 setTransactionFlags(
4474 eTransactionNeeded|
4475 eDisplayTransactionNeeded|
4476 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004477 return NO_ERROR;
4478 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004479 case 1006:{ // send empty update
4480 signalRefresh();
4481 return NO_ERROR;
4482 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004483 case 1008: // toggle use of hw composer
4484 n = data.readInt32();
4485 mDebugDisableHWC = n ? 1 : 0;
4486 invalidateHwcGeometry();
4487 repaintEverything();
4488 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004489 case 1009: // toggle use of transform hint
4490 n = data.readInt32();
4491 mDebugDisableTransformHint = n ? 1 : 0;
4492 invalidateHwcGeometry();
4493 repaintEverything();
4494 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004495 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004496 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 reply->writeInt32(0);
4498 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004499 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004500 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004501 return NO_ERROR;
4502 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004503 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004504 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004505 return NO_ERROR;
4506 }
4507 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004508 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004509 // daltonize
4510 n = data.readInt32();
4511 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004512 case 1:
4513 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4514 break;
4515 case 2:
4516 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4517 break;
4518 case 3:
4519 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4520 break;
4521 default:
4522 mDaltonizer.setType(ColorBlindnessType::None);
4523 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004524 }
4525 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004526 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004527 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004528 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004529 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004530
4531 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004534 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004535 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004536 // apply a color matrix
4537 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004538 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004539 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004540 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004541 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004542 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004543 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004544 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004545 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004546 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004547 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004548
4549 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4550 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004551 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004552 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4553 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4554 }
4555
Chia-I Wu28f320b2018-05-03 11:02:56 -07004556 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004557 return NO_ERROR;
4558 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004559 // This is an experimental interface
4560 // Needs to be shifted to proper binder interface when we productize
4561 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004562 n = data.readInt32();
4563 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004564 return NO_ERROR;
4565 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004566 case 1017: {
4567 n = data.readInt32();
4568 mForceFullDamage = static_cast<bool>(n);
4569 return NO_ERROR;
4570 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004571 case 1018: { // Modify Choreographer's phase offset
4572 n = data.readInt32();
4573 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4574 return NO_ERROR;
4575 }
4576 case 1019: { // Modify SurfaceFlinger's phase offset
4577 n = data.readInt32();
4578 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4579 return NO_ERROR;
4580 }
Irvel468051e2016-06-13 16:44:44 -07004581 case 1020: { // Layer updates interceptor
4582 n = data.readInt32();
4583 if (n) {
4584 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004585 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004586 }
4587 else{
4588 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004589 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004590 }
4591 return NO_ERROR;
4592 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004593 case 1021: { // Disable HWC virtual displays
4594 n = data.readInt32();
4595 mUseHwcVirtualDisplays = !n;
4596 return NO_ERROR;
4597 }
Romain Guy0147a172017-06-01 13:53:56 -07004598 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004599 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004600 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004601
Chia-I Wu28f320b2018-05-03 11:02:56 -07004602 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004603 return NO_ERROR;
4604 }
Romain Guy54f154a2017-10-24 21:40:32 +01004605 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004606 int32_t value = data.readInt32();
4607 if (value > 2) {
4608 return BAD_VALUE;
4609 }
4610 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4611 return BAD_VALUE;
4612 }
Romain Guy54f154a2017-10-24 21:40:32 +01004613
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004614 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004615 invalidateHwcGeometry();
4616 repaintEverything();
4617 return NO_ERROR;
4618 }
4619 case 1024: { // Is wide color gamut rendering/color management supported?
4620 reply->writeBool(hasWideColorDisplay);
4621 return NO_ERROR;
4622 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004623 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004624 n = data.readInt32();
4625 if (n) {
4626 ALOGV("LayerTracing enabled");
4627 mTracing.enable();
4628 doTracing("tracing.enable");
4629 reply->writeInt32(NO_ERROR);
4630 } else {
4631 ALOGV("LayerTracing disabled");
4632 status_t err = mTracing.disable();
4633 reply->writeInt32(err);
4634 }
4635 return NO_ERROR;
4636 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004637 case 1026: { // Get layer tracing status
4638 reply->writeBool(mTracing.isEnabled());
4639 return NO_ERROR;
4640 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004641 // Is a DisplayColorSetting supported?
4642 case 1027: {
4643 int32_t value = data.readInt32();
4644 switch (value) {
4645 case 0:
4646 reply->writeBool(hasWideColorDisplay);
4647 return NO_ERROR;
4648 case 1:
4649 reply->writeBool(true);
4650 return NO_ERROR;
4651 case 2:
4652 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4653 return NO_ERROR;
4654 default:
4655 return BAD_VALUE;
4656 }
4657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 }
4659 }
4660 return err;
4661}
4662
Steven Thomas6d8110b2017-08-31 18:24:21 -07004663void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004664 android_atomic_or(1, &mRepaintEverything);
4665 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004666}
4667
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4669class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004670public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004671 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4672 ~WindowDisconnector() {
4673 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004674 }
4675
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004676private:
4677 ANativeWindow* mWindow;
4678 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004679};
4680
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004681status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4682 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4683 int32_t minLayerZ, int32_t maxLayerZ,
4684 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004685 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004686 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004687
chaviwa76b2712017-09-20 12:02:26 -07004688 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4689
4690 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004691 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4692
chaviwa76b2712017-09-20 12:02:26 -07004693 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4694
4695 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4696 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004697 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004698}
4699
4700status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004701 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004702 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004703 ATRACE_CALL();
4704
4705 class LayerRenderArea : public RenderArea {
4706 public:
Robert Carr578038f2018-03-09 12:25:24 -08004707 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4708 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004709 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004710 mLayer(layer),
4711 mCrop(crop),
4712 mFlinger(flinger),
4713 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004714 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004715 Rect getBounds() const override {
4716 const Layer::State& layerState(mLayer->getDrawingState());
4717 return Rect(layerState.active.w, layerState.active.h);
4718 }
4719 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4720 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4721 bool isSecure() const override { return false; }
4722 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004723 Rect getSourceCrop() const override {
4724 if (mCrop.isEmpty()) {
4725 return getBounds();
4726 } else {
4727 return mCrop;
4728 }
4729 }
4730 bool getWideColorSupport() const override { return false; }
4731 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004732 float getDisplayMaxLuminance() const override {
4733 return DisplayDevice::sDefaultMaxLumiance;
4734 }
Robert Carr578038f2018-03-09 12:25:24 -08004735
4736 class ReparentForDrawing {
4737 public:
4738 const sp<Layer>& oldParent;
4739 const sp<Layer>& newParent;
4740
4741 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4742 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004743 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004744 }
Robert Carr15eae092018-03-23 13:43:53 -07004745 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004746 };
4747
4748 void render(std::function<void()> drawLayers) override {
4749 if (!mChildrenOnly) {
4750 mTransform = mLayer->getTransform().inverse();
4751 drawLayers();
4752 } else {
4753 Rect bounds = getBounds();
4754 screenshotParentLayer =
4755 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4756 bounds.getWidth(), bounds.getHeight(), 0);
4757
4758 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4759 drawLayers();
4760 }
4761 }
chaviwa76b2712017-09-20 12:02:26 -07004762
chaviwa76b2712017-09-20 12:02:26 -07004763 private:
chaviw7206d492017-11-10 16:16:12 -08004764 const sp<Layer> mLayer;
4765 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004766
4767 // In the "childrenOnly" case we reparent the children to a screenshot
4768 // layer which has no properties set and which does not draw.
4769 sp<ContainerLayer> screenshotParentLayer;
4770 Transform mTransform;
4771
4772 SurfaceFlinger* mFlinger;
4773 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004774 };
4775
4776 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4777 auto parent = layerHandle->owner.promote();
4778
chaviw7206d492017-11-10 16:16:12 -08004779 if (parent == nullptr || parent->isPendingRemoval()) {
4780 ALOGE("captureLayers called with a removed parent");
4781 return NAME_NOT_FOUND;
4782 }
4783
Robert Carr578038f2018-03-09 12:25:24 -08004784 const int uid = IPCThreadState::self()->getCallingUid();
4785 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4786 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4787 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4788 return PERMISSION_DENIED;
4789 }
4790
chaviw7206d492017-11-10 16:16:12 -08004791 Rect crop(sourceCrop);
4792 if (sourceCrop.width() <= 0) {
4793 crop.left = 0;
4794 crop.right = parent->getCurrentState().active.w;
4795 }
4796
4797 if (sourceCrop.height() <= 0) {
4798 crop.top = 0;
4799 crop.bottom = parent->getCurrentState().active.h;
4800 }
4801
4802 int32_t reqWidth = crop.width() * frameScale;
4803 int32_t reqHeight = crop.height() * frameScale;
4804
Robert Carr578038f2018-03-09 12:25:24 -08004805 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004806
Robert Carr578038f2018-03-09 12:25:24 -08004807 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004808 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4809 if (!layer->isVisible()) {
4810 return;
Robert Carr578038f2018-03-09 12:25:24 -08004811 } else if (childrenOnly && layer == parent.get()) {
4812 return;
chaviwa76b2712017-09-20 12:02:26 -07004813 }
4814 visitor(layer);
4815 });
4816 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004817 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004818}
4819
4820status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4821 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004822 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004823 bool useIdentityTransform) {
4824 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004825
chaviwa76b2712017-09-20 12:02:26 -07004826 renderArea.updateDimensions();
4827
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004828 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4829 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4830 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4831 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004832
4833 // This mutex protects syncFd and captureResult for communication of the return values from the
4834 // main thread back to this Binder thread
4835 std::mutex captureMutex;
4836 std::condition_variable captureCondition;
4837 std::unique_lock<std::mutex> captureLock(captureMutex);
4838 int syncFd = -1;
4839 std::optional<status_t> captureResult;
4840
Robert Carr03480e22018-01-04 16:02:06 -08004841 const int uid = IPCThreadState::self()->getCallingUid();
4842 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4843
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004844 sp<LambdaMessage> message = new LambdaMessage([&]() {
4845 // If there is a refresh pending, bug out early and tell the binder thread to try again
4846 // after the refresh.
4847 if (mRefreshPending) {
4848 ATRACE_NAME("Skipping screenshot for now");
4849 std::unique_lock<std::mutex> captureLock(captureMutex);
4850 captureResult = std::make_optional<status_t>(EAGAIN);
4851 captureCondition.notify_one();
4852 return;
4853 }
4854
4855 status_t result = NO_ERROR;
4856 int fd = -1;
4857 {
4858 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004859 renderArea.render([&]() {
4860 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4861 useIdentityTransform, forSystem, &fd);
4862 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863 }
4864
4865 {
4866 std::unique_lock<std::mutex> captureLock(captureMutex);
4867 syncFd = fd;
4868 captureResult = std::make_optional<status_t>(result);
4869 captureCondition.notify_one();
4870 }
4871 });
4872
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004873 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874 if (result == NO_ERROR) {
4875 captureCondition.wait(captureLock, [&]() { return captureResult; });
4876 while (*captureResult == EAGAIN) {
4877 captureResult.reset();
4878 result = postMessageAsync(message);
4879 if (result != NO_ERROR) {
4880 return result;
4881 }
4882 captureCondition.wait(captureLock, [&]() { return captureResult; });
4883 }
4884 result = *captureResult;
4885 }
4886
4887 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004888 sync_wait(syncFd, -1);
4889 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004890 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004891
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004892 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004893}
4894
chaviwa76b2712017-09-20 12:02:26 -07004895void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4896 TraverseLayersFunction traverseLayers, bool yswap,
4897 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004898 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004899
Lloyd Pique144e1162017-12-20 16:44:52 -08004900 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004901
4902 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004903 const auto raWidth = renderArea.getWidth();
4904 const auto raHeight = renderArea.getHeight();
4905
4906 const auto reqWidth = renderArea.getReqWidth();
4907 const auto reqHeight = renderArea.getReqHeight();
4908 Rect sourceCrop = renderArea.getSourceCrop();
4909
4910 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4911 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004912
Dan Stozac1879002014-05-22 15:59:05 -07004913 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004914 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004915 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004916 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004917 }
4918
4919 // ensure that sourceCrop is inside screen
4920 if (sourceCrop.left < 0) {
4921 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4922 }
chaviwa76b2712017-09-20 12:02:26 -07004923 if (sourceCrop.right > raWidth) {
4924 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004925 }
4926 if (sourceCrop.top < 0) {
4927 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4928 }
chaviwa76b2712017-09-20 12:02:26 -07004929 if (sourceCrop.bottom > raHeight) {
4930 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004931 }
4932
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004933 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004934 if (renderArea.getWideColorSupport()) {
4935 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004936 }
Peiyong Linfb069302018-04-25 14:34:31 -07004937 engine.setOutputDataSpace(outputDataspace);
4938 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004939
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004941 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004942
4943 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004944 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4945 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004946 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004947
chaviw50da5042018-04-09 13:49:37 -07004948 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004949 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004950 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004951
chaviwa76b2712017-09-20 12:02:26 -07004952 traverseLayers([&](Layer* layer) {
4953 if (filtering) layer->setFiltering(true);
4954 layer->draw(renderArea, useIdentityTransform);
4955 if (filtering) layer->setFiltering(false);
4956 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004957}
4958
chaviwa76b2712017-09-20 12:02:26 -07004959status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4960 TraverseLayersFunction traverseLayers,
4961 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004962 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004963 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004964 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004965 ATRACE_CALL();
4966
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004967 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004968
4969 traverseLayers([&](Layer* layer) {
4970 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4971 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004972
Robert Carr03480e22018-01-04 16:02:06 -08004973 // We allow the system server to take screenshots of secure layers for
4974 // use in situations like the Screen-rotation animation and place
4975 // the impetus on WindowManager to not persist them.
4976 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004977 ALOGW("FB is protected: PERMISSION_DENIED");
4978 return PERMISSION_DENIED;
4979 }
4980
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004981 // this binds the given EGLImage as a framebuffer for the
4982 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004983 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004984 if (bufferBond.getStatus() != NO_ERROR) {
4985 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004986 return INVALID_OPERATION;
4987 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004988
Dan Stozaabcda352017-06-01 14:37:39 -07004989 // this will in fact render into our dequeued buffer
4990 // via an FBO, which means we didn't have to create
4991 // an EGLSurface and therefore we're not
4992 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004993 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004994
Dan Stozaabcda352017-06-01 14:37:39 -07004995 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004996 getRenderEngine().finish();
4997 *outSyncFd = -1;
4998
chaviwa76b2712017-09-20 12:02:26 -07004999 const auto reqWidth = renderArea.getReqWidth();
5000 const auto reqHeight = renderArea.getReqHeight();
5001
Dan Stozaabcda352017-06-01 14:37:39 -07005002 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5003 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005004 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005005 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005006 } else {
5007 base::unique_fd syncFd = getRenderEngine().flush();
5008 if (syncFd < 0) {
5009 getRenderEngine().finish();
5010 }
5011 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005012 }
5013
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005014 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005015}
5016
Mathias Agopiand5556842013-09-19 17:08:37 -07005017void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005018 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005019 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005020 for (size_t y = 0; y < h; y++) {
5021 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5022 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005023 if (p[x] != 0xFF000000) return;
5024 }
5025 }
chaviwa76b2712017-09-20 12:02:26 -07005026 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005027
Robert Carr2047fae2016-11-28 14:09:09 -08005028 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005029 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005030 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005031 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5032 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5033 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5034 static_cast<float>(state.color.a));
5035 i++;
5036 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005037 }
5038}
5039
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005040// ---------------------------------------------------------------------------
5041
Dan Stoza412903f2017-04-27 13:42:17 -07005042void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5043 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005044}
5045
Dan Stoza412903f2017-04-27 13:42:17 -07005046void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5047 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005048}
5049
chaviwa76b2712017-09-20 12:02:26 -07005050void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5051 int32_t maxLayerZ,
5052 const LayerVector::Visitor& visitor) {
5053 // We loop through the first level of layers without traversing,
5054 // as we need to interpret min/max layer Z in the top level Z space.
5055 for (const auto& layer : mDrawingState.layersSortedByZ) {
5056 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5057 continue;
5058 }
5059 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005060 // relative layers are traversed in Layer::traverseInZOrder
5061 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005062 continue;
5063 }
5064 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005065 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5066 return;
5067 }
chaviwa76b2712017-09-20 12:02:26 -07005068 if (!layer->isVisible()) {
5069 return;
5070 }
5071 visitor(layer);
5072 });
5073 }
5074}
5075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005077
5078
5079#if defined(__gl_h_)
5080#error "don't include gl/gl.h in this file"
5081#endif
5082
5083#if defined(__gl2_h_)
5084#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005085#endif