blob: 5be79519724ca5daf280a40d32ece347273df8c2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700109using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110
Steven Thomasb02664d2017-07-26 18:48:28 -0700111namespace {
112class ConditionalLock {
113public:
114 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
115 if (lock) {
116 mMutex.lock();
117 }
118 }
119 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
120private:
121 Mutex& mMutex;
122 bool mLocked;
123};
124} // namespace anonymous
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126// ---------------------------------------------------------------------------
127
Mathias Agopian99b49842011-06-27 16:05:52 -0700128const String16 sHardwareTest("android.permission.HARDWARE_TEST");
129const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
130const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
131const String16 sDump("android.permission.DUMP");
132
133// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800134int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
135int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700136int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700137bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800138uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800139bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800140bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800141int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800142// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600143bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700144
Kalle Raitaa099a242017-01-11 11:17:29 -0800145
146std::string getHwcServiceName() {
147 char value[PROPERTY_VALUE_MAX] = {};
148 property_get("debug.sf.hwc_service_name", value, "default");
149 ALOGI("Using HWComposer service: '%s'", value);
150 return std::string(value);
151}
152
153bool useTrebleTestingOverride() {
154 char value[PROPERTY_VALUE_MAX] = {};
155 property_get("debug.sf.treble_testing_override", value, "false");
156 ALOGI("Treble testing override: '%s'", value);
157 return std::string(value) == "true";
158}
159
Lloyd Pique09594832018-01-22 17:48:03 -0800160NativeWindowSurface::~NativeWindowSurface() = default;
161
162namespace impl {
163
164class NativeWindowSurface final : public android::NativeWindowSurface {
165public:
166 static std::unique_ptr<android::NativeWindowSurface> create(
167 const sp<IGraphicBufferProducer>& producer) {
168 return std::make_unique<NativeWindowSurface>(producer);
169 }
170
171 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
172 : surface(new Surface(producer, false)) {}
173
174 ~NativeWindowSurface() override = default;
175
176private:
177 sp<ANativeWindow> getNativeWindow() const override { return surface; }
178
179 void preallocateBuffers() override { surface->allocateBuffers(); }
180
181 sp<Surface> surface;
182};
183
184} // namespace impl
185
David Sodmanbc815282017-11-05 18:57:52 -0800186SurfaceFlingerBE::SurfaceFlingerBE()
187 : mHwcServiceName(getHwcServiceName()),
188 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800189 mFrameBuckets(),
190 mTotalTime(0),
191 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800192 mComposerSequenceId(0) {
193}
194
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800195SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800196 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700198 mTransactionPending(false),
199 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700200 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700201 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700202 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800204 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800206 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800207 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700209 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700210 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700211 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700212 mDebugInSwapBuffers(0),
213 mLastSwapBufferTime(0),
214 mDebugInTransaction(0),
215 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700216 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700217 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000218 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700219 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700220 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700221 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800222 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800223 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700224 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800225 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800226 mCreateBufferQueue(&BufferQueue::createBufferQueue),
227 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800228
229SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800230 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800231
232 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
233 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
234
235 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
236 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
237
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800238 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
239 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700241 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
242 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
243
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700244 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
245 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
246
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800247 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
248 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
249
Steven Thomas050b2c82017-03-06 11:45:16 -0800250 // Vr flinger is only enabled on Daydream ready devices.
251 useVrFlinger = getBool< ISurfaceFlingerConfigs,
252 &ISurfaceFlingerConfigs::useVrFlinger>(false);
253
Fabien Sanglard1971b632017-03-10 14:50:03 -0800254 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
255 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
256
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600257 hasWideColorDisplay =
258 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
259
David Sodman99974d22017-11-28 12:04:33 -0800260 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700261
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 // debugging stuff...
263 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700264
Mathias Agopianb4b17302013-03-20 18:36:41 -0700265 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700266 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 property_get("debug.sf.showupdates", value, "0");
269 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700270
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700271 property_get("debug.sf.ddms", value, "0");
272 mDebugDDMS = atoi(value);
273 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700274 if (!startDdmConnection()) {
275 // start failed, and DDMS debugging not enabled
276 mDebugDDMS = 0;
277 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700278 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700279 ALOGI_IF(mDebugRegion, "showupdates enabled");
280 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700281
282 property_get("debug.sf.disable_backpressure", value, "0");
283 mPropagateBackpressure = !atoi(value);
284 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700285
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800286 property_get("debug.sf.enable_hwc_vds", value, "0");
287 mUseHwcVirtualDisplays = atoi(value);
288 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800289
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800290 property_get("ro.sf.disable_triple_buffer", value, "1");
291 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800292 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700293
Dan Stoza0a0158c2018-03-16 13:38:54 -0700294 // TODO (b/74616334): Reduce the default value once we isolate the leak
295 const size_t defaultListSize = 4 * MAX_LAYERS;
296 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
297 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
298
Romain Guy11d63f42017-07-20 12:47:14 -0700299 // We should be reading 'persist.sys.sf.color_saturation' here
300 // but since /data may be encrypted, we need to wait until after vold
301 // comes online to attempt to read the property. The property is
302 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800303
304 if (useTrebleTestingOverride()) {
305 // Without the override SurfaceFlinger cannot connect to HIDL
306 // services that are not listed in the manifests. Considered
307 // deriving the setting from the set service name, but it
308 // would be brittle if the name that's not 'default' is used
309 // for production purposes later on.
310 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
311 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312}
313
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800314void SurfaceFlinger::onFirstRef()
315{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800316 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800317}
318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319SurfaceFlinger::~SurfaceFlinger()
320{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Dan Stozac7014012014-02-14 15:03:43 -0800323void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800324{
325 // the window manager died on us. prepare its eulogy.
326
Andy McFadden13a082e2012-08-24 10:16:42 -0700327 // restore initial conditions (default device unblank, etc)
328 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800329
330 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700331 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800332}
333
Robert Carr1db73f62016-12-21 12:58:51 -0800334static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700335 status_t err = client->initCheck();
336 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800337 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 }
Robert Carr1db73f62016-12-21 12:58:51 -0800339 return nullptr;
340}
341
342sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
343 return initClient(new Client(this));
344}
345
346sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
347 const sp<IGraphicBufferProducer>& gbp) {
348 if (authenticateSurfaceTexture(gbp) == false) {
349 return nullptr;
350 }
351 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
352 if (layer == nullptr) {
353 return nullptr;
354 }
355
356 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357}
358
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700359sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
360 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700361{
362 class DisplayToken : public BBinder {
363 sp<SurfaceFlinger> flinger;
364 virtual ~DisplayToken() {
365 // no more references, this display must be terminated
366 Mutex::Autolock _l(flinger->mStateLock);
367 flinger->mCurrentState.displays.removeItem(this);
368 flinger->setTransactionFlags(eDisplayTransactionNeeded);
369 }
370 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700371 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372 : flinger(flinger) {
373 }
374 };
375
376 sp<BBinder> token = new DisplayToken(this);
377
378 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700379 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700380 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800382 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383 return token;
384}
385
Jesse Hall6c913be2013-08-08 12:15:49 -0700386void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
387 Mutex::Autolock _l(mStateLock);
388
389 ssize_t idx = mCurrentState.displays.indexOfKey(display);
390 if (idx < 0) {
391 ALOGW("destroyDisplay: invalid display token");
392 return;
393 }
394
395 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
396 if (!info.isVirtualDisplay()) {
397 ALOGE("destroyDisplay called for non-virtual display");
398 return;
399 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800400 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700401 mCurrentState.displays.removeItemsAt(idx);
402 setTransactionFlags(eDisplayTransactionNeeded);
403}
404
Mathias Agopiane57f2922012-08-09 16:29:12 -0700405sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700406 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700407 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800408 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409 }
Jesse Hall692c7232012-11-08 15:41:56 -0800410 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700411}
412
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413void SurfaceFlinger::bootFinished()
414{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700415 if (mStartPropertySetThread->join() != NO_ERROR) {
416 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418 const nsecs_t now = systemTime();
419 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000420 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700421
422 // wait patiently for the window manager death
423 const String16 name("window");
424 sp<IBinder> window(defaultServiceManager()->getService(name));
425 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700427 }
428
Steven Thomas050b2c82017-03-06 11:45:16 -0800429 if (mVrFlinger) {
430 mVrFlinger->OnBootFinished();
431 }
432
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700433 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 // formerly we would just kill the process, but we now ask it to exit so it
435 // can choose where to stop the animation.
436 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700437
438 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
439 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
440 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700441
Thierry Strudel2924d012017-08-14 15:19:37 -0700442 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700443 readPersistentProperties();
444 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700445 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446}
447
Mathias Agopian3f844832013-08-07 21:24:32 -0700448void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700449 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800450 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700451 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700452 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800453 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
454 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700455 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700456 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700457 return true;
458 }
459 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700460 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700461}
462
Lloyd Piquee83f9312018-02-01 12:53:17 -0800463class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700465 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 const char* name) :
467 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700468 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700469 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000470 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
471 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 mDispSync(dispSync),
473 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 mVsyncMutex(),
475 mPhaseOffset(phaseOffset),
476 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700477
Lloyd Piquee83f9312018-02-01 12:53:17 -0800478 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479
Lloyd Piquee83f9312018-02-01 12:53:17 -0800480 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700481 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000483 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 static_cast<DispSync::Callback*>(this));
485 if (err != NO_ERROR) {
486 ALOGE("error registering vsync callback: %s (%d)",
487 strerror(-err), err);
488 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700489 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 } else {
491 status_t err = mDispSync->removeEventListener(
492 static_cast<DispSync::Callback*>(this));
493 if (err != NO_ERROR) {
494 ALOGE("error unregistering vsync callback: %s (%d)",
495 strerror(-err), err);
496 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 }
501
Lloyd Piquee83f9312018-02-01 12:53:17 -0800502 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700504 mCallback = callback;
505 }
506
Lloyd Piquee83f9312018-02-01 12:53:17 -0800507 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508 Mutex::Autolock lock(mVsyncMutex);
509
510 // Normalize phaseOffset to [0, period)
511 auto period = mDispSync->getPeriod();
512 phaseOffset %= period;
513 if (phaseOffset < 0) {
514 // If we're here, then phaseOffset is in (-period, 0). After this
515 // operation, it will be in (0, period)
516 phaseOffset += period;
517 }
518 mPhaseOffset = phaseOffset;
519
520 // If we're not enabled, we don't need to mess with the listeners
521 if (!mEnabled) {
522 return;
523 }
524
525 // Remove the listener with the old offset
526 status_t err = mDispSync->removeEventListener(
527 static_cast<DispSync::Callback*>(this));
528 if (err != NO_ERROR) {
529 ALOGE("error unregistering vsync callback: %s (%d)",
530 strerror(-err), err);
531 }
532
533 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000534 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535 static_cast<DispSync::Callback*>(this));
536 if (err != NO_ERROR) {
537 ALOGE("error registering vsync callback: %s (%d)",
538 strerror(-err), err);
539 }
540 }
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542private:
543 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700546 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 callback = mCallback;
548
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549 if (mTraceVsync) {
550 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700551 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700552 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 }
554
Peiyong Lin566a3b42018-01-09 18:22:43 -0800555 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 callback->onVSyncEvent(when);
557 }
558 }
559
Tim Murray4a4e4a22016-04-19 16:29:23 +0000560 const char* const mName;
561
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700562 int mValue;
563
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700564 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700565 const String8 mVsyncOnLabel;
566 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700567
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569
570 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800571 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572
573 Mutex mVsyncMutex; // Protects the following
574 nsecs_t mPhaseOffset;
575 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700576};
577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700579public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 InjectVSyncSource() = default;
581 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700582
Lloyd Piquee83f9312018-02-01 12:53:17 -0800583 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700584 std::lock_guard<std::mutex> lock(mCallbackMutex);
585 mCallback = callback;
586 }
587
Lloyd Piquee83f9312018-02-01 12:53:17 -0800588 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700589 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700590 if (mCallback) {
591 mCallback->onVSyncEvent(when);
592 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700593 }
594
Lloyd Piquee83f9312018-02-01 12:53:17 -0800595 void setVSyncEnabled(bool) override {}
596 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700597
598private:
599 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700601};
602
Wei Wangf9b05ee2017-07-19 20:59:39 -0700603// Do not call property_set on main thread which will be blocked by init
604// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700606 ALOGI( "SurfaceFlinger's main thread ready to run. "
607 "Initializing graphics H/W...");
608
Thierry Strudel2924d012017-08-14 15:19:37 -0700609 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800614 mEventThreadSource =
615 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
616 true, "app");
617 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
618 "appEventThread");
619 mSfEventThreadSource =
620 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
621 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800622
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800623 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
624 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800625 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800628 getBE().mRenderEngine =
629 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
630 hasWideColorDisplay
631 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
632 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800633 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700634
635 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
636 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800637 getBE().mHwc.reset(
638 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700639 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800640 // Process any initial hotplug and resulting display changes.
641 processDisplayHotplugEventsLocked();
642 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
643 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800644
Lloyd Piquefcd86612017-12-14 17:15:36 -0800645 // make the default display GLContext current so that we can create textures
646 // when creating Layers (which may happens before we render something)
647 getDefaultDisplayDeviceLocked()->makeCurrent();
648
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 if (useVrFlinger) {
650 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700651 // This callback is called from the vr flinger dispatch thread. We
652 // need to call signalTransaction(), which requires holding
653 // mStateLock when we're not on the main thread. Acquiring
654 // mStateLock from the vr flinger dispatch thread might trigger a
655 // deadlock in surface flinger (see b/66916578), so post a message
656 // to be handled on the main thread instead.
657 sp<LambdaMessage> message = new LambdaMessage([=]() {
658 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
659 mVrFlingerRequestsDisplay = requestDisplay;
660 signalTransaction();
661 });
662 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 };
David Sodman105b7dc2017-11-04 20:28:14 -0700664 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
665 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800666 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 if (!mVrFlinger) {
668 ALOGE("Failed to start vrflinger");
669 }
670 }
671
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800672 mEventControlThread = std::make_unique<impl::EventControlThread>(
673 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700674
Mathias Agopian92a979a2012-08-02 18:32:23 -0700675 // initialize our drawing state
676 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700677
Andy McFadden13a082e2012-08-24 10:16:42 -0700678 // set initial conditions (e.g. unblank default device)
679 initializeDisplays();
680
David Sodmanbc815282017-11-05 18:57:52 -0800681 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700682
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 // Inform native graphics APIs whether the present timestamp is supported:
684 if (getHwComposer().hasCapability(
685 HWC2::Capability::PresentFenceIsNotReliable)) {
686 mStartPropertySetThread = new StartPropertySetThread(false);
687 } else {
688 mStartPropertySetThread = new StartPropertySetThread(true);
689 }
690
691 if (mStartPropertySetThread->Start() != NO_ERROR) {
692 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800693 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800694
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700696}
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698void SurfaceFlinger::readPersistentProperties() {
699 char value[PROPERTY_VALUE_MAX];
700
701 property_get("persist.sys.sf.color_saturation", value, "1.0");
702 mSaturation = atof(value);
703 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100704
705 property_get("persist.sys.sf.native_mode", value, "0");
706 mForceNativeColorMode = atoi(value) == 1;
707 if (mForceNativeColorMode) {
708 ALOGV("Forcing native color mode");
709 }
Romain Guy11d63f42017-07-20 12:47:14 -0700710}
711
Mathias Agopiana67e4182012-06-19 17:26:12 -0700712void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Start boot animation service by setting a property mailbox
714 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800716 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 if (mStartPropertySetThread->join() != NO_ERROR) {
718 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800723 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
Mathias Agopian875d8e12013-06-07 15:35:48 -0700726size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800727 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700728}
729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800731
Jamie Gennis582270d2011-08-17 18:19:00 -0700732bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800733 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800734 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800735 return authenticateSurfaceTextureLocked(bufferProducer);
736}
737
738bool SurfaceFlinger::authenticateSurfaceTextureLocked(
739 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800740 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800741 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800742}
743
Brian Anderson6b376712017-04-04 10:51:39 -0700744status_t SurfaceFlinger::getSupportedFrameTimestamps(
745 std::vector<FrameEvent>* outSupported) const {
746 *outSupported = {
747 FrameEvent::REQUESTED_PRESENT,
748 FrameEvent::ACQUIRE,
749 FrameEvent::LATCH,
750 FrameEvent::FIRST_REFRESH_START,
751 FrameEvent::LAST_REFRESH_START,
752 FrameEvent::GPU_COMPOSITION_DONE,
753 FrameEvent::DEQUEUE_READY,
754 FrameEvent::RELEASE,
755 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700756 ConditionalLock _l(mStateLock,
757 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700758 if (!getHwComposer().hasCapability(
759 HWC2::Capability::PresentFenceIsNotReliable)) {
760 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
761 }
762 return NO_ERROR;
763}
764
Dan Stoza7f7da322014-05-02 15:26:25 -0700765status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
766 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800767 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700768 return BAD_VALUE;
769 }
770
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500771 if (!display.get())
772 return NAME_NOT_FOUND;
773
Jesse Hall692c7232012-11-08 15:41:56 -0800774 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700775 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800776 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700777 type = i;
778 break;
779 }
780 }
781
782 if (type < 0) {
783 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700784 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700785
Mathias Agopian8b736f12012-08-13 17:54:26 -0700786 // TODO: Not sure if display density should handled by SF any longer
787 class Density {
788 static int getDensityFromProperty(char const* propName) {
789 char property[PROPERTY_VALUE_MAX];
790 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800791 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700792 density = atoi(property);
793 }
794 return density;
795 }
796 public:
797 static int getEmuDensity() {
798 return getDensityFromProperty("qemu.sf.lcd_density"); }
799 static int getBuildDensity() {
800 return getDensityFromProperty("ro.sf.lcd_density"); }
801 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700804
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 ConditionalLock _l(mStateLock,
806 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 DisplayInfo info = DisplayInfo();
809
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 float xdpi = hwConfig->getDpiX();
811 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700812
813 if (type == DisplayDevice::DISPLAY_PRIMARY) {
814 // The density of the device is provided by a build property
815 float density = Density::getBuildDensity() / 160.0f;
816 if (density == 0) {
817 // the build doesn't provide a density -- this is wrong!
818 // use xdpi instead
819 ALOGE("ro.sf.lcd_density must be defined as a build property");
820 density = xdpi / 160.0f;
821 }
822 if (Density::getEmuDensity()) {
823 // if "qemu.sf.lcd_density" is specified, it overrides everything
824 xdpi = ydpi = density = Density::getEmuDensity();
825 density /= 160.0f;
826 }
827 info.density = density;
828
829 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800831 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 } else {
833 // TODO: where should this value come from?
834 static const int TV_DENSITY = 213;
835 info.density = TV_DENSITY / 160.0f;
836 info.orientation = 0;
837 }
838
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 info.w = hwConfig->getWidth();
840 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 info.xdpi = xdpi;
842 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900844 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845
Andy McFadden91b2ca82014-06-13 14:04:23 -0700846 // This is how far in advance a buffer must be queued for
847 // presentation at a given time. If you want a buffer to appear
848 // on the screen at time N, you must submit the buffer before
849 // (N - presentationDeadline).
850 //
851 // Normally it's one full refresh period (to give SF a chance to
852 // latch the buffer), but this can be reduced by configuring a
853 // DispSync offset. Any additional delays introduced by the hardware
854 // composer or panel must be accounted for here.
855 //
856 // We add an additional 1ms to allow for processing time and
857 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800859 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860
861 // All non-virtual displays are currently considered secure.
862 info.secure = true;
863
Michael Wright28f24d02016-07-12 13:30:53 -0700864 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700865 }
866
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 return NO_ERROR;
868}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700869
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800870status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800872 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700873 return BAD_VALUE;
874 }
875
876 // FIXME for now we always return stats for the primary display
877 memset(stats, 0, sizeof(*stats));
878 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
879 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
880 return NO_ERROR;
881}
882
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700883int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800884 if (display == nullptr) {
885 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800886 return BAD_VALUE;
887 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700888
889 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800890 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700891 return device->getActiveConfig();
892 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700893
Dan Stoza24a42e92015-03-09 10:04:11 -0700894 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700896
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700897void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
898 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
899 this);
900 int32_t type = hw->getDisplayType();
901 int currentMode = hw->getActiveConfig();
902
903 if (mode == currentMode) {
904 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
905 return;
906 }
907
908 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
909 ALOGW("Trying to set config for virtual display");
910 return;
911 }
912
913 hw->setActiveConfig(mode);
914 getHwComposer().setActiveConfig(type, mode);
915}
916
917status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
918 class MessageSetActiveConfig: public MessageBase {
919 SurfaceFlinger& mFlinger;
920 sp<IBinder> mDisplay;
921 int mMode;
922 public:
923 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
924 int mode) :
925 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
926 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700927 Vector<DisplayInfo> configs;
928 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700929 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700930 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700931 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700932 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700933 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800935 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700937 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
939 ALOGW("Attempt to set active config = %d for virtual display",
940 mMode);
941 } else {
942 mFlinger.setActiveConfigInternal(hw, mMode);
943 }
944 return true;
945 }
946 };
947 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
948 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700949 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700950}
Michael Wright28f24d02016-07-12 13:30:53 -0700951status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700952 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700953 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
954 return BAD_VALUE;
955 }
956
957 if (!display.get()) {
958 return NAME_NOT_FOUND;
959 }
960
961 int32_t type = NAME_NOT_FOUND;
962 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
963 if (display == mBuiltinDisplays[i]) {
964 type = i;
965 break;
966 }
967 }
968
969 if (type < 0) {
970 return type;
971 }
972
Peiyong Lina52f0292018-03-14 17:26:31 -0700973 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700974 {
975 ConditionalLock _l(mStateLock,
976 std::this_thread::get_id() != mMainThreadId);
977 modes = getHwComposer().getColorModes(type);
978 }
Michael Wright28f24d02016-07-12 13:30:53 -0700979 outColorModes->clear();
980 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
981
982 return NO_ERROR;
983}
984
Peiyong Lina52f0292018-03-14 17:26:31 -0700985ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700986 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700987 if (device != nullptr) {
988 return device->getActiveColorMode();
989 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700991}
992
993void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700997
998 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return;
1000 }
1001
1002 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1003 ALOGW("Trying to set config for virtual display");
1004 return;
1005 }
1006
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1008 hw->getDisplayType());
1009
Michael Wright28f24d02016-07-12 13:30:53 -07001010 hw->setActiveColorMode(mode);
Peiyong Lin0e7a7912018-04-05 14:36:36 -07001011 getHwComposer().setActiveColorMode(type, mode, RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001012}
1013
1014
1015status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001017 class MessageSetActiveColorMode: public MessageBase {
1018 SurfaceFlinger& mFlinger;
1019 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001021 public:
1022 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001024 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1025 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001027 mFlinger.getDisplayColorModes(mDisplay, &modes);
1028 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001029 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001030 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1031 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001032 return true;
1033 }
1034 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1035 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1037 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001038 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001039 ALOGW("Attempt to set active color mode %s %d for virtual display",
1040 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001041 } else {
1042 mFlinger.setActiveColorModeInternal(hw, mMode);
1043 }
1044 return true;
1045 }
1046 };
1047 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1048 postMessageSync(msg);
1049 return NO_ERROR;
1050}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001051
Svetoslavd85084b2014-03-20 10:28:31 -07001052status_t SurfaceFlinger::clearAnimationFrameStats() {
1053 Mutex::Autolock _l(mStateLock);
1054 mAnimFrameTracker.clearStats();
1055 return NO_ERROR;
1056}
1057
1058status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1059 Mutex::Autolock _l(mStateLock);
1060 mAnimFrameTracker.getStats(outStats);
1061 return NO_ERROR;
1062}
1063
Dan Stozac4f471e2016-03-24 09:31:08 -07001064status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1065 HdrCapabilities* outCapabilities) const {
1066 Mutex::Autolock _l(mStateLock);
1067
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001068 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001069 if (displayDevice == nullptr) {
1070 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1071 return BAD_VALUE;
1072 }
1073
1074 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001075 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001076 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001077 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1078 // insert HDR10 as we will force client composition for HDR10
1079 // layers
1080 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1081 types.push_back(HAL_HDR_HDR10);
1082
1083 *outCapabilities = HdrCapabilities(types,
1084 capabilities->getDesiredMaxLuminance(),
1085 capabilities->getDesiredMaxAverageLuminance(),
1086 capabilities->getDesiredMinLuminance());
1087 } else {
1088 *outCapabilities = std::move(*capabilities);
1089 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 } else {
1091 return BAD_VALUE;
1092 }
1093
1094 return NO_ERROR;
1095}
1096
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1099 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101 if (mInjectVSyncs == enable) {
1102 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001103 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104
1105 if (enable) {
1106 ALOGV("VSync Injections enabled");
1107 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001108 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001109 mInjectorEventThread =
1110 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1111 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 } else {
1115 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001116 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
1118
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001120 });
1121 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122 return NO_ERROR;
1123}
1124
1125status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 Mutex::Autolock _l(mStateLock);
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 if (!mInjectVSyncs) {
1129 ALOGE("VSync Injections not enabled");
1130 return BAD_VALUE;
1131 }
1132 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1133 ALOGV("Injecting VSync inside SurfaceFlinger");
1134 mVSyncInjector->onInjectSyncEvent(when);
1135 }
1136 return NO_ERROR;
1137}
1138
Lloyd Pique755e3192018-01-31 16:46:15 -08001139status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1140 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001141 IPCThreadState* ipc = IPCThreadState::self();
1142 const int pid = ipc->getCallingPid();
1143 const int uid = ipc->getCallingUid();
1144 if ((uid != AID_SHELL) &&
1145 !PermissionCache::checkPermission(sDump, pid, uid)) {
1146 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1147 return PERMISSION_DENIED;
1148 }
1149
1150 // Try to acquire a lock for 1s, fail gracefully
1151 const status_t err = mStateLock.timedLock(s2ns(1));
1152 const bool locked = (err == NO_ERROR);
1153 if (!locked) {
1154 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1155 return TIMED_OUT;
1156 }
1157
1158 outLayers->clear();
1159 mCurrentState.traverseInZOrder([&](Layer* layer) {
1160 outLayers->push_back(layer->getLayerDebugInfo());
1161 });
1162
1163 mStateLock.unlock();
1164 return NO_ERROR;
1165}
1166
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001167// ----------------------------------------------------------------------------
1168
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001169sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1170 ISurfaceComposer::VsyncSource vsyncSource) {
1171 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1172 return mSFEventThread->createEventConnection();
1173 } else {
1174 return mEventThread->createEventConnection();
1175 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001176}
1177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001179
1180void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001181 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001182}
1183
1184void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001185 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186}
1187
1188void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001189 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001193 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001194 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001195}
1196
1197status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001198 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001199 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200}
1201
1202status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001203 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001204 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001205 if (res == NO_ERROR) {
1206 msg->wait();
1207 }
1208 return res;
1209}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001210
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001211void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001212 do {
1213 waitForEvent();
1214 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215}
1216
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217void SurfaceFlinger::enableHardwareVsync() {
1218 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001219 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001221 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1222 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001224 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225}
1226
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 Mutex::Autolock _l(mHWVsyncLock);
1229
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 if (makeAvailable) {
1231 mHWVsyncAvailable = true;
1232 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001233 // Hardware vsync is not currently available, so abort the resync
1234 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 return;
1236 }
1237
David Sodman105b7dc2017-11-04 20:28:14 -07001238 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001240
1241 mPrimaryDispSync.reset();
1242 mPrimaryDispSync.setPeriod(period);
1243
1244 if (!mPrimaryHWVsyncEnabled) {
1245 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1247 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 mPrimaryHWVsyncEnabled = true;
1249 }
1250}
1251
Jesse Hall948fe0c2013-10-14 12:56:09 -07001252void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 Mutex::Autolock _l(mHWVsyncLock);
1254 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1256 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 mPrimaryDispSync.endResync();
1258 mPrimaryHWVsyncEnabled = false;
1259 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001260 if (makeUnavailable) {
1261 mHWVsyncAvailable = false;
1262 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263}
1264
Tim Murray4a4e4a22016-04-19 16:29:23 +00001265void SurfaceFlinger::resyncWithRateLimit() {
1266 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001267
1268 // No explicit locking is needed here since EventThread holds a lock while calling this method
1269 static nsecs_t sLastResyncAttempted = 0;
1270 const nsecs_t now = systemTime();
1271 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001272 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273 }
Dan Stoza57164302017-05-08 14:03:54 -07001274 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001275}
1276
Steven Thomasb02664d2017-07-26 18:48:28 -07001277void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1278 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001279 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001281 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001282 return;
1283 }
1284
1285 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001286 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001287 return;
1288 }
1289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 { // Scope for the lock
1293 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001297 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001298
1299 if (needsHwVsync) {
1300 enableHardwareVsync();
1301 } else {
1302 disableHardwareVsync(false);
1303 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001304}
1305
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001306void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001307 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1308 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001309}
1310
Lloyd Pique715a2c12017-12-14 17:18:08 -08001311void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1312 HWC2::Connection connection) {
1313 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1314 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001315
Lloyd Piqueba04e622017-12-14 17:11:26 -08001316 // Ignore events that do not have the right sequenceId.
1317 if (sequenceId != getBE().mComposerSequenceId) {
1318 return;
1319 }
1320
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 // Only lock if we're not on the main thread. This function is normally
1322 // called on a hwbinder thread, but for the primary display it's called on
1323 // the main thread with the state lock already held, so don't attempt to
1324 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001325 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001326
Lloyd Pique715a2c12017-12-14 17:18:08 -08001327 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001328
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001329 if (std::this_thread::get_id() == mMainThreadId) {
1330 // Process all pending hot plug events immediately if we are on the main thread.
1331 processDisplayHotplugEventsLocked();
1332 }
1333
Lloyd Piqueba04e622017-12-14 17:11:26 -08001334 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001335}
1336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337void SurfaceFlinger::onRefreshReceived(int sequenceId,
1338 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001339 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001342 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001343 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001344}
1345
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 getHwComposer().setVsyncEnabled(disp,
1350 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001351}
1352
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001354void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356 // Clear the drawing state so that the logic inside of
1357 // handleTransactionLocked will fire. It will determine the delta between
1358 // mCurrentState and mDrawingState and re-apply all changes when we make the
1359 // transition.
1360 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001361 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362 mDisplays.clear();
1363}
1364
Steven Thomas050b2c82017-03-06 11:45:16 -08001365void SurfaceFlinger::updateVrFlinger() {
1366 if (!mVrFlinger)
1367 return;
1368 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001369 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001370 return;
1371 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372
David Sodman105b7dc2017-11-04 20:28:14 -07001373 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 ALOGE("Vr flinger is only supported for remote hardware composer"
1375 " service connections. Ignoring request to transition to vr"
1376 " flinger.");
1377 mVrFlingerRequestsDisplay = false;
1378 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001379 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 int currentDisplayPowerMode = getDisplayDeviceLocked(
1384 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001391 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001392 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1393 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001394 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001395
David Sodman105b7dc2017-11-04 20:28:14 -07001396 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1397 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001398
1399 if (vrFlingerRequestsDisplay) {
1400 mVrFlinger->GrantDisplayOwnership();
1401 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404
1405 mVisibleRegionsDirty = true;
1406 invalidateHwcGeometry();
1407
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001408 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1410 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1411 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001414 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 const nsecs_t period = activeConfig->getVsyncPeriod();
1416 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 // Use phase of 0 since phase is not known.
1419 // Use latency of 0, which will snap to the ideal latency.
1420 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001421
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 android_atomic_or(1, &mRepaintEverything);
1423 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424}
1425
Mathias Agopian4fec8732012-06-29 14:12:52 -07001426void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001427 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001430 bool frameMissed = !mHadClientComposition &&
1431 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001432 (mPreviousPresentFence->getSignalTime() ==
1433 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001434 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001435 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001436 signalLayerUpdate();
1437 break;
1438 }
1439
Steven Thomas050b2c82017-03-06 11:45:16 -08001440 // Now that we're going to make it to the handleMessageTransaction()
1441 // call below it's safe to call updateVrFlinger(), which will
1442 // potentially trigger a display handoff.
1443 updateVrFlinger();
1444
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 bool refreshNeeded = handleMessageTransaction();
1446 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001447 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001448 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001449 // Signal a refresh if a transaction modified the window state,
1450 // a new buffer was latched, or if HWC has requested a full
1451 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 signalRefresh();
1453 }
1454 break;
1455 }
1456 case MessageQueue::REFRESH: {
1457 handleMessageRefresh();
1458 break;
1459 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 }
1461}
1462
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001464 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001466 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001470}
1471
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475}
1476
1477void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001478 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001479
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001480 mRefreshPending = false;
1481
Pablo Ceballos40845df2016-01-25 17:41:15 -08001482 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001483
Brian Andersond6927fb2016-07-23 23:37:30 -07001484 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001485 rebuildLayerStacks();
1486 setUpHWComposer();
1487 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001488 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001489 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001491 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001492
David Sodman105b7dc2017-11-04 20:28:14 -07001493 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001494
1495 mHadClientComposition = false;
1496 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1497 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1498 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001499 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001500 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001501
Dan Stoza9e56aa02015-11-02 13:00:03 -08001502 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505void SurfaceFlinger::doDebugFlashRegions()
1506{
1507 // is debugging enabled
1508 if (CC_LIKELY(!mDebugRegion))
1509 return;
1510
1511 const bool repaintEverything = mRepaintEverything;
1512 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1513 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001514 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 // transform the dirty region into this screen's coordinate space
1516 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1517 if (!dirtyRegion.isEmpty()) {
1518 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001519 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520
1521 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001523 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001524 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1525
Mathias Agopianda27af92012-09-13 18:17:13 -07001526 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 }
1528 }
1529 }
1530
1531 postFramebuffer();
1532
1533 if (mDebugRegion > 1) {
1534 usleep(mDebugRegion * 1000);
1535 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001536
Dan Stoza9e56aa02015-11-02 13:00:03 -08001537 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001538 auto& displayDevice = mDisplays[displayId];
1539 if (!displayDevice->isDisplayOn()) {
1540 continue;
1541 }
1542
David Sodman105b7dc2017-11-04 20:28:14 -07001543 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1544 ALOGE_IF(result != NO_ERROR,
1545 "prepareFrame for display %zd failed:"
1546 " %d (%s)",
1547 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001548 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549}
1550
Adrian Roos1e1a1282017-11-01 19:05:31 +01001551void SurfaceFlinger::doTracing(const char* where) {
1552 ATRACE_CALL();
1553 ATRACE_NAME(where);
1554 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001555 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001556 }
1557}
1558
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001559void SurfaceFlinger::logLayerStats() {
1560 ATRACE_CALL();
1561 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1562 int32_t hwcId = -1;
1563 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1564 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1565 if (displayDevice->isPrimary()) {
1566 hwcId = displayDevice->getHwcDisplayId();
1567 break;
1568 }
1569 }
1570 if (hwcId < 0) {
1571 ALOGE("LayerStats: Hmmm, no primary display?");
1572 return;
1573 }
1574 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1575 }
1576}
1577
Brian Andersond6927fb2016-07-23 23:37:30 -07001578void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001580 ATRACE_CALL();
1581 ALOGV("preComposition");
1582
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586 needExtraInvalidate = true;
1587 }
Robert Carr2047fae2016-11-28 14:09:09 -08001588 });
1589
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 if (needExtraInvalidate) {
1591 signalLayerUpdate();
1592 }
1593}
1594
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001595void SurfaceFlinger::updateCompositorTiming(
1596 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1597 std::shared_ptr<FenceTime>& presentFenceTime) {
1598 // Update queue of past composite+present times and determine the
1599 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001600 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001602 while (!getBE().mCompositePresentTimes.empty()) {
1603 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604 // Cached values should have been updated before calling this method,
1605 // which helps avoid duplicate syscalls.
1606 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1607 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1608 break;
1609 }
1610 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001611 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612 }
1613
1614 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001615 while (getBE().mCompositePresentTimes.size() > 16) {
1616 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617 }
1618
Brian Andersond0010582017-03-07 13:20:31 -08001619 setCompositorTimingSnapped(
1620 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1621}
1622
1623void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1624 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625 // Integer division and modulo round toward 0 not -inf, so we need to
1626 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001627 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001628 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1629 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1630
Brian Andersond0010582017-03-07 13:20:31 -08001631 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1632 if (idealLatency <= 0) {
1633 idealLatency = vsyncInterval;
1634 }
1635
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 // Snap the latency to a value that removes scheduling jitter from the
1637 // composition and present times, which often have >1ms of jitter.
1638 // Reducing jitter is important if an app attempts to extrapolate
1639 // something (such as user input) to an accurate diasplay time.
1640 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1641 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001642 nsecs_t bias = vsyncInterval / 2;
1643 int64_t extraVsyncs =
1644 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1645 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1646 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647
David Sodman99974d22017-11-28 12:04:33 -08001648 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1649 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1650 getBE().mCompositorTiming.interval = vsyncInterval;
1651 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652}
1653
1654void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001655{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001656 ATRACE_CALL();
1657 ALOGV("postComposition");
1658
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001660 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001662 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001663 }
1664
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001665 // |mStateLock| not needed as we are on the main thread
1666 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001667
David Sodman73beded2017-11-15 11:56:06 -08001668 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001670 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671 glCompositionDoneFenceTime =
1672 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001673 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001674 } else {
1675 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1676 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001677
David Sodman73beded2017-11-15 11:56:06 -08001678 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001679 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001680 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001681 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001682
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1684 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1685
1686 // We use the refreshStartTime which might be sampled a little later than
1687 // when we started doing work for this frame, but that should be okay
1688 // since updateCompositorTiming has snapping logic.
1689 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001690 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001691 CompositorTiming compositorTiming;
1692 {
David Sodman99974d22017-11-28 12:04:33 -08001693 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1694 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001695 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696
Robert Carr2047fae2016-11-28 14:09:09 -08001697 mDrawingState.traverseInZOrder([&](Layer* layer) {
1698 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001699 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001700 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001701 recordBufferingStats(layer->getName().string(),
1702 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001703 }
Robert Carr2047fae2016-11-28 14:09:09 -08001704 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001705
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001706 if (presentFenceTime->isValid()) {
1707 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001708 enableHardwareVsync();
1709 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001710 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001711 }
1712 }
1713
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001714 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001715 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001716 enableHardwareVsync();
1717 }
1718 }
1719
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001720 if (mAnimCompositionPending) {
1721 mAnimCompositionPending = false;
1722
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001725 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001726 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001727 // The HWC doesn't support present fences, so use the refresh
1728 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001730 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001731 mAnimFrameTracker.setActualPresentTime(presentTime);
1732 }
1733 mAnimFrameTracker.advanceFrame();
1734 }
Dan Stozab90cf072015-03-05 11:05:59 -08001735
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001736 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1737 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001738 return;
1739 }
1740
1741 nsecs_t currentTime = systemTime();
1742 if (mHasPoweredOff) {
1743 mHasPoweredOff = false;
1744 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001745 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001747 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1748 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001749 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001750 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001751 }
David Sodman4a36e932017-11-07 14:29:47 -08001752 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001753 }
David Sodman4a36e932017-11-07 14:29:47 -08001754 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755}
1756
1757void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 ATRACE_CALL();
1759 ALOGV("rebuildLayerStacks");
1760
Mathias Agopiancd60f992012-08-16 16:28:27 -07001761 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001763 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 mVisibleRegionsDirty = false;
1765 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001766
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1768 Region opaqueRegion;
1769 Region dirtyRegion;
1770 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001771 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1773 const Transform& tr(displayDevice->getTransform());
1774 const Rect bounds(displayDevice->getBounds());
1775 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001776 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001777
Jeff Sharkey76488112017-02-27 14:15:18 -07001778 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001779 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001780 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1781 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001782 Region drawRegion(tr.transform(
1783 layer->visibleNonTransparentRegion));
1784 drawRegion.andSelf(bounds);
1785 if (!drawRegion.isEmpty()) {
1786 layersSortedByZ.add(layer);
1787 } else {
1788 // Clear out the HWC layer if this layer was
1789 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001790 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001791 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001793 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001794 // WM changes displayDevice->layerStack upon sleep/awake.
1795 // Here we make sure we delete the HWC layers even if
1796 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001797 hwcLayerDestroyed = layer->destroyHwcLayer(
1798 displayDevice->getHwcDisplayId());
1799 }
1800
1801 // If a layer is not going to get a release fence because
1802 // it is invisible, but it is also going to release its
1803 // old buffer, add it to the list of layers needing
1804 // fences.
1805 if (hwcLayerDestroyed) {
1806 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1807 mLayersWithQueuedFrames.cend(), layer);
1808 if (found != mLayersWithQueuedFrames.cend()) {
1809 layersNeedingFences.add(layer);
1810 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 });
1813 }
1814 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001815 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 displayDevice->undefinedRegion.set(bounds);
1817 displayDevice->undefinedRegion.subtractSelf(
1818 tr.transform(opaqueRegion));
1819 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001823
Romain Guy0147a172017-06-01 13:53:56 -07001824mat4 SurfaceFlinger::computeSaturationMatrix() const {
1825 if (mSaturation == 1.0f) {
1826 return mat4();
1827 }
1828
1829 // Rec.709 luma coefficients
1830 float3 luminance{0.213f, 0.715f, 0.072f};
1831 luminance *= 1.0f - mSaturation;
1832 return mat4(
1833 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1834 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1835 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1836 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1837 );
1838}
1839
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001840// pickColorMode translates a given dataspace into the best available color mode.
1841// Currently only support sRGB and Display-P3.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001842ColorMode SurfaceFlinger::pickColorMode(Dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001843 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001844 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001845 }
1846
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001847 switch (dataSpace) {
1848 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1849 // system expects.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001850 case Dataspace::UNKNOWN:
1851 case Dataspace::SRGB:
1852 case Dataspace::V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001853 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001854 break;
1855
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001856 case Dataspace::DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001857 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001858 break;
1859
1860 default:
1861 // TODO (courtneygo): Do we want to assert an error here?
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001862 ALOGE("No color mode mapping for %s (%#x)",
1863 dataspaceDetails(static_cast<android_dataspace>(dataSpace)).c_str(),
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001864 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001865 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001866 break;
1867 }
1868}
1869
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001870Dataspace SurfaceFlinger::bestTargetDataSpace(
1871 Dataspace a, Dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001872 // Only support sRGB and Display-P3 right now.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001873 if (a == Dataspace::DISPLAY_P3 || b == Dataspace::DISPLAY_P3) {
1874 return Dataspace::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001875 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001876 if (a == Dataspace::V0_SCRGB_LINEAR || b == Dataspace::V0_SCRGB_LINEAR) {
1877 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001878 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001879 if (a == Dataspace::V0_SCRGB || b == Dataspace::V0_SCRGB) {
1880 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001881 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001882 if (!hasHdr) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001883 if (a == Dataspace::BT2020_PQ || b == Dataspace::BT2020_PQ) {
1884 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001885 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001886 if (a == Dataspace::BT2020_ITU_PQ || b == Dataspace::BT2020_ITU_PQ) {
1887 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001888 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001889 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001890
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001891 return Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001892}
1893
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 ATRACE_CALL();
1896 ALOGV("setUpHWComposer");
1897
Jesse Hall028dc8f2013-08-20 16:35:32 -07001898 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001899 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1900 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1901 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1902
1903 // If nothing has changed (!dirty), don't recompose.
1904 // If something changed, but we don't currently have any visible layers,
1905 // and didn't when we last did a composition, then skip it this time.
1906 // The second rule does two things:
1907 // - When all layers are removed from a display, we'll emit one black
1908 // frame, then nothing more until we get new layers.
1909 // - When a display is created with a private layer stack, we won't
1910 // emit any black frames until a layer is added to the layer stack.
1911 bool mustRecompose = dirty && !(empty && wasEmpty);
1912
1913 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1914 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1915 mustRecompose ? "doing" : "skipping",
1916 dirty ? "+" : "-",
1917 empty ? "+" : "-",
1918 wasEmpty ? "+" : "-");
1919
Dan Stoza71433162014-02-04 16:22:36 -08001920 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001921
1922 if (mustRecompose) {
1923 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1924 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001925 }
1926
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 // build the h/w work list
1928 if (CC_UNLIKELY(mGeometryInvalid)) {
1929 mGeometryInvalid = false;
1930 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1931 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1932 const auto hwcId = displayDevice->getHwcDisplayId();
1933 if (hwcId >= 0) {
1934 const Vector<sp<Layer>>& currentLayers(
1935 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001936 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001937 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001939 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001942 }
1943 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001944
Robert Carrae060832016-11-28 10:51:00 -08001945 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001946 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001948 }
1949 }
1950 }
1951 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 }
Riley Andrews03414a12014-07-01 14:22:59 -07001953
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001954
Romain Guy0147a172017-06-01 13:53:56 -07001955 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001956
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 // Set the per-frame data
1958 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1959 auto& displayDevice = mDisplays[displayId];
1960 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001961
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 if (hwcId < 0) {
1963 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001964 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001965 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08001966 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07001967 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001968 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1969 "display %zd: %d", displayId, result);
1970 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001972 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1973 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001974 !displayDevice->getHdrSupport()) {
1975 layer->forceClientComposition(hwcId);
1976 }
1977
chaviwc9232ed2017-11-14 15:31:15 -08001978 if (layer->getForceClientComposition(hwcId)) {
1979 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1980 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1981 continue;
1982 }
1983
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 layer->setPerFrameData(displayDevice);
1985 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001986
1987 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001988 ColorMode newColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001989 Dataspace newDataSpace = Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001990
1991 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001992 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1993 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001994 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001995 layer->getName().string(), dataspaceDetails(static_cast<android_dataspace>(layer->getDataSpace())).c_str(),
1996 layer->getDataSpace(), dataspaceDetails(static_cast<android_dataspace>(newDataSpace)).c_str(), newDataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001997 }
1998 newColorMode = pickColorMode(newDataSpace);
1999
Thierry Strudel2924d012017-08-14 15:19:37 -07002000 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002001 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 }
2003
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002004 mPreviousColorMatrix = colorMatrix;
2005
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002007 auto& displayDevice = mDisplays[displayId];
2008 if (!displayDevice->isDisplayOn()) {
2009 continue;
2010 }
2011
David Sodman105b7dc2017-11-04 20:28:14 -07002012 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2014 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002015 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002017
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018void SurfaceFlinger::doComposition() {
2019 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 ALOGV("doComposition");
2021
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002022 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002024 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002025 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026 // transform the dirty region into this screen's coordinate space
2027 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002028
2029 // repaint the framebuffer (if needed)
2030 doDisplayComposition(hw, dirtyRegion);
2031
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002033 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002034 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002035 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002036 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002037}
2038
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039void SurfaceFlinger::postFramebuffer()
2040{
Mathias Agopian841cde52012-03-01 15:44:37 -08002041 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002043
Mathias Agopiana44b0412011-10-16 18:46:35 -07002044 const nsecs_t now = systemTime();
2045 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002046
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2048 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002049 if (!displayDevice->isDisplayOn()) {
2050 continue;
2051 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 const auto hwcId = displayDevice->getHwcDisplayId();
2053 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002054 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002055 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002056 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002057 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002059 // The layer buffer from the previous frame (if any) is released
2060 // by HWC only when the release fence from this frame (if any) is
2061 // signaled. Always get the release fence from HWC first.
2062 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002063 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002064
2065 // If the layer was client composited in the previous frame, we
2066 // need to merge with the previous client target acquire fence.
2067 // Since we do not track that, always merge with the current
2068 // client target acquire fence when it is available, even though
2069 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002071 releaseFence = Fence::merge("LayerRelease", releaseFence,
2072 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002073 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002074
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 layer->onLayerDisplayed(releaseFence);
2076 }
Chia-I Wu83806892017-11-16 10:50:20 -08002077
2078 // We've got a list of layers needing fences, that are disjoint with
2079 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2080 // supply them with the present fence.
2081 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002082 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002083 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2084 layer->onLayerDisplayed(presentFence);
2085 }
2086 }
2087
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002089 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002090 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002091 }
2092
Mathias Agopiana44b0412011-10-16 18:46:35 -07002093 mLastSwapBufferTime = systemTime() - now;
2094 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002095
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002096 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002097 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2098 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2099 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2100 logFrameStats();
2101 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103}
2104
Mathias Agopian87baae12012-07-31 12:38:26 -07002105void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106{
Mathias Agopian841cde52012-03-01 15:44:37 -08002107 ATRACE_CALL();
2108
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002109 // here we keep a copy of the drawing state (that is the state that's
2110 // going to be overwritten by handleTransactionLocked()) outside of
2111 // mStateLock so that the side-effects of the State assignment
2112 // don't happen with mStateLock held (which can cause deadlocks).
2113 State drawingState(mDrawingState);
2114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 Mutex::Autolock _l(mStateLock);
2116 const nsecs_t now = systemTime();
2117 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118
Mathias Agopianca4d3602011-05-19 15:38:14 -07002119 // Here we're guaranteed that some transaction flags are set
2120 // so we can call handleTransactionLocked() unconditionally.
2121 // We call getTransactionFlags(), which will also clear the flags,
2122 // with mStateLock held to guarantee that mCurrentState won't change
2123 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002124
Mathias Agopiane57f2922012-08-09 16:29:12 -07002125 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002126 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002127
Mathias Agopianca4d3602011-05-19 15:38:14 -07002128 mLastTransactionTime = systemTime() - now;
2129 mDebugInTransaction = 0;
2130 invalidateHwcGeometry();
2131 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002132}
2133
Lloyd Pique715a2c12017-12-14 17:18:08 -08002134DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002135 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002136 // Figure out whether the event is for the primary display or an
2137 // external display by matching the Hwc display id against one for a
2138 // connected display. If we did not find a match, we then check what
2139 // displays are not already connected to determine the type. If we don't
2140 // have a connected primary display, we assume the new display is meant to
2141 // be the primary display, and then if we don't have an external display,
2142 // we assume it is that.
2143 const auto primaryDisplayId =
2144 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2145 const auto externalDisplayId =
2146 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2147 if (primaryDisplayId && primaryDisplayId == display) {
2148 return DisplayDevice::DISPLAY_PRIMARY;
2149 } else if (externalDisplayId && externalDisplayId == display) {
2150 return DisplayDevice::DISPLAY_EXTERNAL;
2151 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2152 return DisplayDevice::DISPLAY_PRIMARY;
2153 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2154 return DisplayDevice::DISPLAY_EXTERNAL;
2155 }
2156
2157 return DisplayDevice::DISPLAY_ID_INVALID;
2158}
2159
Lloyd Piqueba04e622017-12-14 17:11:26 -08002160void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2161 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002162 auto displayType = determineDisplayType(event.display, event.connection);
2163 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2164 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2165 continue;
2166 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002167
2168 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2169 ALOGE("External displays are not supported by the vr hardware composer.");
2170 continue;
2171 }
2172
Lloyd Pique715a2c12017-12-14 17:18:08 -08002173 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002174
2175 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002176 if (!mBuiltinDisplays[displayType].get()) {
2177 ALOGV("Creating built in display %d", displayType);
2178 mBuiltinDisplays[displayType] = new BBinder();
2179 // All non-virtual displays are currently considered secure.
2180 DisplayDeviceState info(displayType, true);
2181 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2182 "Built-in Screen" : "External Screen";
2183 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002184 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002185 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002186 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002187 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002188
Lloyd Piquefcd86612017-12-14 17:15:36 -08002189 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2190 if (idx >= 0) {
2191 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002192 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002193 mCurrentState.displays.removeItemsAt(idx);
2194 }
2195 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196 }
2197
2198 processDisplayChangesLocked();
2199 }
2200
2201 mPendingHotplugEvents.clear();
2202}
2203
Lloyd Pique09594832018-01-22 17:48:03 -08002204sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2205 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2206 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2207 bool hasWideColorSupport = false;
2208 if (hasWideColorDisplay) {
2209 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2210 for (ColorMode colorMode : modes) {
2211 switch (colorMode) {
2212 case ColorMode::DISPLAY_P3:
2213 case ColorMode::ADOBE_RGB:
2214 case ColorMode::DCI_P3:
2215 hasWideColorSupport = true;
2216 break;
2217 default:
2218 break;
2219 }
2220 }
2221 }
2222
2223 bool hasHdrSupport = false;
2224 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2225 getHwComposer().getHdrCapabilities(state.type);
2226 if (hdrCapabilities) {
2227 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2228 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2229 hasHdrSupport = iter != types.cend();
2230 }
2231
2232 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2233 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2234
2235 /*
2236 * Create our display's surface
2237 */
2238 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2239 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2240 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2241 renderSurface->setNativeWindow(nativeWindow.get());
2242 const int displayWidth = renderSurface->queryWidth();
2243 const int displayHeight = renderSurface->queryHeight();
2244
2245 // Make sure that composition can never be stalled by a virtual display
2246 // consumer that isn't processing buffers fast enough. We have to do this
2247 // in two places:
2248 // * Here, in case the display is composed entirely by HWC.
2249 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2250 // window's swap interval in eglMakeCurrent, so they'll override the
2251 // interval we set here.
2252 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2253 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2254 }
2255
2256 // virtual displays are always considered enabled
2257 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2258 : HWC_POWER_MODE_OFF;
2259
2260 sp<DisplayDevice> hw =
2261 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2262 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2263 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2264
2265 if (maxFrameBufferAcquiredBuffers >= 3) {
2266 nativeWindowSurface->preallocateBuffers();
2267 }
2268
2269 ColorMode defaultColorMode = ColorMode::NATIVE;
2270 if (hasWideColorSupport) {
2271 defaultColorMode = ColorMode::SRGB;
2272 }
2273 setActiveColorModeInternal(hw, defaultColorMode);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002274 hw->setCompositionDataSpace(Dataspace::UNKNOWN);
Lloyd Pique09594832018-01-22 17:48:03 -08002275 hw->setLayerStack(state.layerStack);
2276 hw->setProjection(state.orientation, state.viewport, state.frame);
2277 hw->setDisplayName(state.displayName);
2278
2279 return hw;
2280}
2281
Lloyd Pique347200f2017-12-14 17:00:15 -08002282void SurfaceFlinger::processDisplayChangesLocked() {
2283 // here we take advantage of Vector's copy-on-write semantics to
2284 // improve performance by skipping the transaction entirely when
2285 // know that the lists are identical
2286 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2287 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2288 if (!curr.isIdenticalTo(draw)) {
2289 mVisibleRegionsDirty = true;
2290 const size_t cc = curr.size();
2291 size_t dc = draw.size();
2292
2293 // find the displays that were removed
2294 // (ie: in drawing state but not in current state)
2295 // also handle displays that changed
2296 // (ie: displays that are in both lists)
2297 for (size_t i = 0; i < dc;) {
2298 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2299 if (j < 0) {
2300 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002301 // Call makeCurrent() on the primary display so we can
2302 // be sure that nothing associated with this display
2303 // is current.
2304 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2305 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2306 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2307 if (hw != nullptr) hw->disconnect(getHwComposer());
2308 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2309 mEventThread->onHotplugReceived(draw[i].type, false);
2310 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002311 } else {
2312 // this display is in both lists. see if something changed.
2313 const DisplayDeviceState& state(curr[j]);
2314 const wp<IBinder>& display(curr.keyAt(j));
2315 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2316 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2317 if (state_binder != draw_binder) {
2318 // changing the surface is like destroying and
2319 // recreating the DisplayDevice, so we just remove it
2320 // from the drawing state, so that it get re-added
2321 // below.
2322 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2323 if (hw != nullptr) hw->disconnect(getHwComposer());
2324 mDisplays.removeItem(display);
2325 mDrawingState.displays.removeItemsAt(i);
2326 dc--;
2327 // at this point we must loop to the next item
2328 continue;
2329 }
2330
2331 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2332 if (disp != nullptr) {
2333 if (state.layerStack != draw[i].layerStack) {
2334 disp->setLayerStack(state.layerStack);
2335 }
2336 if ((state.orientation != draw[i].orientation) ||
2337 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2338 disp->setProjection(state.orientation, state.viewport, state.frame);
2339 }
2340 if (state.width != draw[i].width || state.height != draw[i].height) {
2341 disp->setDisplaySize(state.width, state.height);
2342 }
2343 }
2344 }
2345 ++i;
2346 }
2347
2348 // find displays that were added
2349 // (ie: in current state but not in drawing state)
2350 for (size_t i = 0; i < cc; i++) {
2351 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2352 const DisplayDeviceState& state(curr[i]);
2353
2354 sp<DisplaySurface> dispSurface;
2355 sp<IGraphicBufferProducer> producer;
2356 sp<IGraphicBufferProducer> bqProducer;
2357 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002358 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002359
2360 int32_t hwcId = -1;
2361 if (state.isVirtualDisplay()) {
2362 // Virtual displays without a surface are dormant:
2363 // they have external state (layer stack, projection,
2364 // etc.) but no internal state (i.e. a DisplayDevice).
2365 if (state.surface != nullptr) {
2366 // Allow VR composer to use virtual displays.
2367 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2368 int width = 0;
2369 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2370 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2371 int height = 0;
2372 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2373 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2374 int intFormat = 0;
2375 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2376 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002377 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378
2379 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2380 }
2381
2382 // TODO: Plumb requested format back up to consumer
2383
2384 sp<VirtualDisplaySurface> vds =
2385 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2386 bqProducer, bqConsumer,
2387 state.displayName);
2388
2389 dispSurface = vds;
2390 producer = vds;
2391 }
2392 } else {
2393 ALOGE_IF(state.surface != nullptr,
2394 "adding a supported display, but rendering "
2395 "surface is provided (%p), ignoring it",
2396 state.surface.get());
2397
2398 hwcId = state.type;
2399 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2400 producer = bqProducer;
2401 }
2402
2403 const wp<IBinder>& display(curr.keyAt(i));
2404 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002405 mDisplays.add(display,
2406 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2407 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 if (!state.isVirtualDisplay()) {
2409 mEventThread->onHotplugReceived(state.type, true);
2410 }
2411 }
2412 }
2413 }
2414 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002415
2416 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002417}
2418
Mathias Agopian87baae12012-07-31 12:38:26 -07002419void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002420{
Dan Stoza7dde5992015-05-22 09:51:44 -07002421 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002422 mCurrentState.traverseInZOrder([](Layer* layer) {
2423 layer->notifyAvailableFrames();
2424 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426 /*
2427 * Traversal of the children
2428 * (perform the transaction for each of them if needed)
2429 */
2430
Mathias Agopian3559b072012-08-15 13:46:03 -07002431 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002432 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002434 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435
2436 const uint32_t flags = layer->doTransaction(0);
2437 if (flags & Layer::eVisibleRegion)
2438 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002439 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440 }
2441
2442 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002443 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444 */
2445
Mathias Agopiane57f2922012-08-09 16:29:12 -07002446 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002451 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002452 // The transform hint might have changed for some layers
2453 // (either because a display has changed, or because a layer
2454 // as changed).
2455 //
2456 // Walk through all the layers in currentLayers,
2457 // and update their transform hint.
2458 //
2459 // If a layer is visible only on a single display, then that
2460 // display is used to calculate the hint, otherwise we use the
2461 // default display.
2462 //
2463 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2464 // the hint is set before we acquire a buffer from the surface texture.
2465 //
2466 // NOTE: layer transactions have taken place already, so we use their
2467 // drawing state. However, SurfaceFlinger's own transaction has not
2468 // happened yet, so we must use the current state layer list
2469 // (soon to become the drawing state list).
2470 //
2471 sp<const DisplayDevice> disp;
2472 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002473 bool first = true;
2474 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002475 // NOTE: we rely on the fact that layers are sorted by
2476 // layerStack first (so we don't have to traverse the list
2477 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002478 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002479 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002480 currentlayerStack = layerStack;
2481 // figure out if this layerstack is mirrored
2482 // (more than one display) if so, pick the default display,
2483 // if not, pick the only display it's on.
2484 disp.clear();
2485 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2486 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002487 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002488 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002489 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002490 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002491 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002492 break;
2493 }
2494 }
2495 }
2496 }
Chet Haase91d25932013-04-11 15:24:55 -07002497
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002498 if (disp == nullptr) {
2499 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2500 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002501
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 // could be null when this layer is using a layerStack
2503 // that is not visible on any display. Also can occur at
2504 // screen off/on times.
2505 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002506 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002507
2508 // disp can be null if there is no display available at all to get
2509 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002510 if (disp != nullptr) {
2511 layer->updateTransformHint(disp);
2512 }
Robert Carr2047fae2016-11-28 14:09:09 -08002513
2514 first = false;
2515 });
Mathias Agopian84300952012-11-21 16:02:13 -08002516 }
2517
2518
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 /*
2520 * Perform our own transaction if needed
2521 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002522
2523 if (mLayersAdded) {
2524 mLayersAdded = false;
2525 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002526 mVisibleRegionsDirty = true;
2527 }
2528
2529 // some layers might have been removed, so
2530 // we need to update the regions they're exposing.
2531 if (mLayersRemoved) {
2532 mLayersRemoved = false;
2533 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002534 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002536 // this layer is not visible anymore
2537 // TODO: we could traverse the tree from front to back and
2538 // compute the actual visible region
2539 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 Region visibleReg;
2541 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002542 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002543 }
Robert Carr2047fae2016-11-28 14:09:09 -08002544 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 }
2546
2547 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002548
2549 updateCursorAsync();
2550}
2551
2552void SurfaceFlinger::updateCursorAsync()
2553{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2555 auto& displayDevice = mDisplays[displayId];
2556 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002557 continue;
2558 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002559
2560 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2561 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002562 }
2563 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002564}
2565
2566void SurfaceFlinger::commitTransaction()
2567{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002568 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570 for (const auto& l : mLayersPendingRemoval) {
2571 recordBufferingStats(l->getName().string(),
2572 l->getOccupancyHistory(true));
2573 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002574 }
2575 mLayersPendingRemoval.clear();
2576 }
2577
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002578 // If this transaction is part of a window animation then the next frame
2579 // we composite should be considered an animation as well.
2580 mAnimCompositionPending = mAnimTransactionPending;
2581
Mathias Agopian4fec8732012-06-29 14:12:52 -07002582 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002583 mDrawingState.traverseInZOrder([](Layer* layer) {
2584 layer->commitChildList();
2585 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002586 mTransactionPending = false;
2587 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589}
2590
Chia-I Wuab0c3192017-08-01 11:29:00 -07002591void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002592 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593{
Mathias Agopian841cde52012-03-01 15:44:37 -08002594 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002596
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 Region aboveOpaqueLayers;
2598 Region aboveCoveredLayers;
2599 Region dirty;
2600
Mathias Agopian87baae12012-07-31 12:38:26 -07002601 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002605 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Jesse Hall01e29052013-02-19 16:13:35 -08002607 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002608 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002609 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002610
Mathias Agopianab028732010-03-16 16:41:46 -07002611 /*
2612 * opaqueRegion: area of a surface that is fully opaque.
2613 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002615
2616 /*
2617 * visibleRegion: area of a surface that is visible on screen
2618 * and not fully transparent. This is essentially the layer's
2619 * footprint minus the opaque regions above it.
2620 * Areas covered by a translucent surface are considered visible.
2621 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002623
2624 /*
2625 * coveredRegion: area of a surface that is covered by all
2626 * visible regions above it (which includes the translucent areas).
2627 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002629
Jesse Halla8026d22012-09-25 13:25:04 -07002630 /*
2631 * transparentRegion: area of a surface that is hinted to be completely
2632 * transparent. This is only used to tell when the layer has no visible
2633 * non-transparent regions and can be removed from the layer list. It
2634 * does not affect the visibleRegion of this layer or any layers
2635 * beneath it. The hint may not be correct if apps don't respect the
2636 * SurfaceView restrictions (which, sadly, some don't).
2637 */
2638 Region transparentRegion;
2639
Mathias Agopianab028732010-03-16 16:41:46 -07002640
2641 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002642 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002643 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002647 if (!visibleRegion.isEmpty()) {
2648 // Remove the transparent area from the visible region
2649 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002650 if (tr.preserveRects()) {
2651 // transform the transparent region
2652 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002653 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002654 // transformation too complex, can't do the
2655 // transparent region optimization.
2656 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002657 }
Mathias Agopianab028732010-03-16 16:41:46 -07002658 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659
Mathias Agopianab028732010-03-16 16:41:46 -07002660 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002662 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002663 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2664 // the opaque region is the layer's footprint
2665 opaqueRegion = visibleRegion;
2666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 }
2668 }
2669
Robert Carre5f4f692018-01-12 13:12:28 -08002670 if (visibleRegion.isEmpty()) {
2671 layer->clearVisibilityRegions();
2672 return;
2673 }
2674
Mathias Agopianab028732010-03-16 16:41:46 -07002675 // Clip the covered region to the visible region
2676 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2677
2678 // Update aboveCoveredLayers for next (lower) layer
2679 aboveCoveredLayers.orSelf(visibleRegion);
2680
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681 // subtract the opaque region covered by the layers above us
2682 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683
2684 // compute this layer's dirty region
2685 if (layer->contentDirty) {
2686 // we need to invalidate the whole region
2687 dirty = visibleRegion;
2688 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 layer->contentDirty = false;
2691 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002692 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002693 * the exposed region consists of two components:
2694 * 1) what's VISIBLE now and was COVERED before
2695 * 2) what's EXPOSED now less what was EXPOSED before
2696 *
2697 * note that (1) is conservative, we start with the whole
2698 * visible region but only keep what used to be covered by
2699 * something -- which mean it may have been exposed.
2700 *
2701 * (2) handles areas that were not covered by anything but got
2702 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002703 */
Mathias Agopianab028732010-03-16 16:41:46 -07002704 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 const Region oldVisibleRegion = layer->visibleRegion;
2706 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002707 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2708 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 }
2710 dirty.subtractSelf(aboveOpaqueLayers);
2711
2712 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002713 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714
Mathias Agopianab028732010-03-16 16:41:46 -07002715 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002717
Jesse Halla8026d22012-09-25 13:25:04 -07002718 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 layer->setVisibleRegion(visibleRegion);
2720 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002721 layer->setVisibleNonTransparentRegion(
2722 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002723 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724
Mathias Agopian87baae12012-07-31 12:38:26 -07002725 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726}
2727
Chia-I Wuab0c3192017-08-01 11:29:00 -07002728void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002729 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002730 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002731 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002732 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002733 }
2734 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002735}
2736
Dan Stoza6b9454d2014-11-07 16:00:59 -08002737bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 ALOGV("handlePageFlip");
2740
Brian Andersond6927fb2016-07-23 23:37:30 -07002741 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002744 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002745 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002746
2747 // Store the set of layers that need updates. This set must not change as
2748 // buffers are being latched, as this could result in a deadlock.
2749 // Example: Two producers share the same command stream and:
2750 // 1.) Layer 0 is latched
2751 // 2.) Layer 0 gets a new frame
2752 // 2.) Layer 1 gets a new frame
2753 // 3.) Layer 1 is latched.
2754 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2755 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002757 if (layer->hasQueuedFrame()) {
2758 frameQueued = true;
2759 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002761 } else {
2762 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002763 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002764 } else {
2765 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002766 }
Robert Carr2047fae2016-11-28 14:09:09 -08002767 });
2768
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002770 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002771 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002772 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002773 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002774 newDataLatched = true;
2775 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002776 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002777
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002778 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002779
2780 // If we will need to wake up at some time in the future to deal with a
2781 // queued frame that shouldn't be displayed during this vsync period, wake
2782 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002783 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002784 signalLayerUpdate();
2785 }
2786
2787 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002788 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789}
2790
Mathias Agopianad456f92011-01-13 17:53:01 -08002791void SurfaceFlinger::invalidateHwcGeometry()
2792{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002794}
2795
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002796
Fabien Sanglard830b8472016-11-30 16:35:58 -08002797void SurfaceFlinger::doDisplayComposition(
2798 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002799 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800{
Dan Stoza71433162014-02-04 16:22:36 -08002801 // We only need to actually compose the display if:
2802 // 1) It is being handled by hardware composer, which may need this to
2803 // keep its virtual display state machine in sync, or
2804 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002805 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002806 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002808 return;
2809 }
2810
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002812 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002813
2814 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002815 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816}
2817
Chia-I Wub02087d2017-11-09 10:19:54 -08002818bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002819{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002821
Chia-I Wub02087d2017-11-09 10:19:54 -08002822 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002823 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002825
2826 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002827 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2828 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002829 if (applyColorMatrix) {
2830 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2831 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2832 }
2833
David Sodman105b7dc2017-11-04 20:28:14 -07002834 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 if (hasClientComposition) {
2836 ALOGV("hasClientComposition");
2837
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002838 Dataspace outputDataspace = Dataspace::UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002839 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002840 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002841 outputDataspace = Dataspace::DISPLAY_P3;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002842 }
2843 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2844
Chia-I Wu7f402902017-11-09 12:51:10 -08002845 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002846 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002848 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002849
2850 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002851 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002852 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2853 }
2854 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002855 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002856
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002857 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002858 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002859 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002860 // when using overlays, we assume a fully transparent framebuffer
2861 // NOTE: we could reduce how much we need to clear, for instance
2862 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002863 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002864 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002865 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002866 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002867 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002868 // we're left with the letterbox region
2869 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002871
2872 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002873 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002874
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002876 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002877 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002879 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002880 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002881
Dan Stoza9e56aa02015-11-02 13:00:03 -08002882 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002883 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002884 // scissor on the main display. It should never be needed
2885 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 const Rect& bounds(displayDevice->getBounds());
2887 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002888 if (scissor != bounds) {
2889 // scissor doesn't match the screen's dimensions, so we
2890 // need to clear everything outside of it and enable
2891 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002892
Mathias Agopianf45c5102012-10-24 16:29:17 -07002893 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002894 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002895 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002896 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002897 }
2898 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002899 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002900
Mathias Agopian85d751c2012-08-29 16:59:24 -07002901 /*
2902 * and then, render the layers targeted at the framebuffer
2903 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002904
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 ALOGV("Rendering client layers");
2906 const Transform& displayTransform = displayDevice->getTransform();
2907 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002908 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 bool firstLayer = true;
2910 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002911 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 displayTransform.transform(layer->visibleRegion)));
2913 ALOGV("Layer: %s", layer->getName().string());
2914 ALOGV(" Composition type: %s",
2915 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002916 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 switch (layer->getCompositionType(hwcId)) {
2918 case HWC2::Composition::Cursor:
2919 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002920 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002922 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002924 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002925 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002926 // never clear the very first layer since we're
2927 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002928 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002929 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002930 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002933 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002934 break;
2935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002937 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 } else {
2940 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002941 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002943 }
2944 } else {
2945 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002947 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002949 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002950 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002951 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002952 }
2953 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002954
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002955 if (applyColorMatrix) {
2956 getRenderEngine().setupColorTransform(oldColorMatrix);
2957 }
2958
Mathias Agopianf45c5102012-10-24 16:29:17 -07002959 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002960 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002961 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962}
2963
Fabien Sanglard830b8472016-11-30 16:35:58 -08002964void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2965 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002966 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002967 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968}
2969
Dan Stoza7d89d062015-04-30 13:29:25 -07002970status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002971 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002972 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002973 const sp<Layer>& lbc,
2974 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002975{
Dan Stoza7d89d062015-04-30 13:29:25 -07002976 // add this layer to the current state list
2977 {
2978 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002980 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2981 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002982 return NO_MEMORY;
2983 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 if (parent == nullptr) {
2985 mCurrentState.layersSortedByZ.add(lbc);
2986 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002987 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002988 ALOGE("addClientLayer called with a removed parent");
2989 return NAME_NOT_FOUND;
2990 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002991 parent->addChild(lbc);
2992 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002993
Dan Stoza101d8dc2018-02-27 15:42:25 -08002994 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002995 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2996 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2997 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2998 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2999 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 mLayersAdded = true;
3001 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003002 }
3003
Mathias Agopian96f08192010-06-02 23:28:45 -07003004 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003005 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003006
Dan Stoza7d89d062015-04-30 13:29:25 -07003007 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003008}
3009
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003010status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003011 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003012 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3013}
Robert Carr7f9b8992017-03-10 11:08:39 -08003014
chaviwca27f252018-02-06 16:46:39 -08003015status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3016 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003017 if (layer->isPendingRemoval()) {
3018 return NO_ERROR;
3019 }
3020
Robert Carr1f0a16a2016-10-24 16:27:39 -07003021 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003022 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003023 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003024 if (topLevelOnly) {
3025 return NO_ERROR;
3026 }
3027
Chia-I Wu98f1c102017-05-30 14:54:08 -07003028 sp<Layer> ancestor = p;
3029 while (ancestor->getParent() != nullptr) {
3030 ancestor = ancestor->getParent();
3031 }
3032 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3033 ALOGE("removeLayer called with a layer whose parent has been removed");
3034 return NAME_NOT_FOUND;
3035 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003036
3037 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003038 } else {
3039 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003040 }
3041
Robert Carr136e2f62017-02-08 17:54:29 -08003042 // As a matter of normal operation, the LayerCleaner will produce a second
3043 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3044 // so we will succeed in promoting it, but it's already been removed
3045 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3046 // otherwise something has gone wrong and we are leaking the layer.
3047 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3049 layer->getName().string(),
3050 (p != nullptr) ? p->getName().string() : "no-parent");
3051 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003052 } else if (index < 0) {
3053 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003054 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055
Chia-I Wuc6657022017-08-15 11:18:17 -07003056 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 mLayersPendingRemoval.add(layer);
3058 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003059 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 setTransactionFlags(eTransactionNeeded);
3061 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062}
3063
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003064uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003065 return android_atomic_release_load(&mTransactionFlags);
3066}
3067
Mathias Agopian3f844832013-08-07 21:24:32 -07003068uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3070}
3071
Mathias Agopian3f844832013-08-07 21:24:32 -07003072uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3074 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003075 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 }
3077 return old;
3078}
3079
chaviwca27f252018-02-06 16:46:39 -08003080bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3081 for (const ComposerState& state : states) {
3082 // Here we need to check that the interface we're given is indeed
3083 // one of our own. A malicious client could give us a nullptr
3084 // IInterface, or one of its own or even one of our own but a
3085 // different type. All these situations would cause us to crash.
3086 if (state.client == nullptr) {
3087 return true;
3088 }
3089
3090 sp<IBinder> binder = IInterface::asBinder(state.client);
3091 if (binder == nullptr) {
3092 return true;
3093 }
3094
3095 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3096 return true;
3097 }
3098 }
3099 return false;
3100}
3101
Mathias Agopian8b33f032012-07-24 20:43:54 -07003102void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003103 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003104 const Vector<DisplayState>& displays,
3105 uint32_t flags)
3106{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003107 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003108 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003109 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003110
chaviwca27f252018-02-06 16:46:39 -08003111 if (containsAnyInvalidClientState(states)) {
3112 return;
3113 }
3114
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003115 if (flags & eAnimation) {
3116 // For window updates that are part of an animation we must wait for
3117 // previous animation "frames" to be handled.
3118 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003119 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003120 if (CC_UNLIKELY(err != NO_ERROR)) {
3121 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003122 // caller after a few seconds.
3123 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3124 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003125 mAnimTransactionPending = false;
3126 break;
3127 }
3128 }
3129 }
3130
chaviwca27f252018-02-06 16:46:39 -08003131 for (const DisplayState& display : displays) {
3132 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003133 }
3134
chaviwca27f252018-02-06 16:46:39 -08003135 for (const ComposerState& state : states) {
3136 transactionFlags |= setClientStateLocked(state);
3137 }
3138
3139 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3140 // as destroyed should only occur after setting all other states. This is to allow for a
3141 // child re-parent to happen before marking its original parent as destroyed (which would
3142 // then mark the child as destroyed).
3143 for (const ComposerState& state : states) {
3144 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003145 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003146
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003147 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3148 // anyway. This can be used as a flush mechanism for previous async transactions.
3149 // Empty animation transaction can be used to simulate back-pressure, so also force a
3150 // transaction for empty animation transactions.
3151 if (transactionFlags == 0 &&
3152 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003153 transactionFlags = eTransactionNeeded;
3154 }
3155
Mathias Agopian386aa982011-11-07 21:58:03 -08003156 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003157 if (mInterceptor->isEnabled()) {
3158 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003159 }
Irvel468051e2016-06-13 16:44:44 -07003160
Mathias Agopian386aa982011-11-07 21:58:03 -08003161 // this triggers the transaction
3162 setTransactionFlags(transactionFlags);
3163
3164 // if this is a synchronous transaction, wait for it to take effect
3165 // before returning.
3166 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003167 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003168 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003169 if (flags & eAnimation) {
3170 mAnimTransactionPending = true;
3171 }
3172 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003173 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3174 if (CC_UNLIKELY(err != NO_ERROR)) {
3175 // just in case something goes wrong in SF, return to the
3176 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003177 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3178 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003179 break;
3180 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 }
3183}
3184
Mathias Agopiane57f2922012-08-09 16:29:12 -07003185uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3186{
Jesse Hall9a143922012-10-04 16:29:19 -07003187 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3188 if (dpyIdx < 0)
3189 return 0;
3190
Mathias Agopiane57f2922012-08-09 16:29:12 -07003191 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003192 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003193 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003194 const uint32_t what = s.what;
3195 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003196 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003197 disp.surface = s.surface;
3198 flags |= eDisplayTransactionNeeded;
3199 }
3200 }
3201 if (what & DisplayState::eLayerStackChanged) {
3202 if (disp.layerStack != s.layerStack) {
3203 disp.layerStack = s.layerStack;
3204 flags |= eDisplayTransactionNeeded;
3205 }
3206 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003207 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003208 if (disp.orientation != s.orientation) {
3209 disp.orientation = s.orientation;
3210 flags |= eDisplayTransactionNeeded;
3211 }
3212 if (disp.frame != s.frame) {
3213 disp.frame = s.frame;
3214 flags |= eDisplayTransactionNeeded;
3215 }
3216 if (disp.viewport != s.viewport) {
3217 disp.viewport = s.viewport;
3218 flags |= eDisplayTransactionNeeded;
3219 }
3220 }
Michael Lentine47e45402014-07-18 15:34:25 -07003221 if (what & DisplayState::eDisplaySizeChanged) {
3222 if (disp.width != s.width) {
3223 disp.width = s.width;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 if (disp.height != s.height) {
3227 disp.height = s.height;
3228 flags |= eDisplayTransactionNeeded;
3229 }
3230 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003231 }
3232 return flags;
3233}
3234
chaviwca27f252018-02-06 16:46:39 -08003235uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3236 const layer_state_t& s = composerState.state;
3237 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3238
Mathias Agopian13127d82013-03-05 17:47:11 -08003239 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003240 if (layer == nullptr) {
3241 return 0;
3242 }
3243
3244 if (layer->isPendingRemoval()) {
3245 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3246 return 0;
3247 }
3248
3249 uint32_t flags = 0;
3250
3251 const uint32_t what = s.what;
3252 bool geometryAppliesWithResize =
3253 what & layer_state_t::eGeometryAppliesWithResize;
3254 if (what & layer_state_t::ePositionChanged) {
3255 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3256 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003257 }
chaviw8b3871a2017-11-01 17:41:01 -07003258 }
3259 if (what & layer_state_t::eLayerChanged) {
3260 // NOTE: index needs to be calculated before we update the state
3261 const auto& p = layer->getParent();
3262 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003263 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003264 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003265 mCurrentState.layersSortedByZ.removeAt(idx);
3266 mCurrentState.layersSortedByZ.add(layer);
3267 // we need traversal (state changed)
3268 // AND transaction (list changed)
3269 flags |= eTransactionNeeded|eTraversalNeeded;
3270 }
chaviw8b3871a2017-11-01 17:41:01 -07003271 } else {
3272 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003273 flags |= eTransactionNeeded|eTraversalNeeded;
3274 }
3275 }
chaviw8b3871a2017-11-01 17:41:01 -07003276 }
3277 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003278 // NOTE: index needs to be calculated before we update the state
3279 const auto& p = layer->getParent();
3280 if (p == nullptr) {
3281 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3282 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3283 mCurrentState.layersSortedByZ.removeAt(idx);
3284 mCurrentState.layersSortedByZ.add(layer);
3285 // we need traversal (state changed)
3286 // AND transaction (list changed)
3287 flags |= eTransactionNeeded|eTraversalNeeded;
3288 }
3289 } else {
3290 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3291 flags |= eTransactionNeeded|eTraversalNeeded;
3292 }
chaviw8b3871a2017-11-01 17:41:01 -07003293 }
3294 }
3295 if (what & layer_state_t::eSizeChanged) {
3296 if (layer->setSize(s.w, s.h)) {
3297 flags |= eTraversalNeeded;
3298 }
3299 }
3300 if (what & layer_state_t::eAlphaChanged) {
3301 if (layer->setAlpha(s.alpha))
3302 flags |= eTraversalNeeded;
3303 }
3304 if (what & layer_state_t::eColorChanged) {
3305 if (layer->setColor(s.color))
3306 flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eMatrixChanged) {
3309 if (layer->setMatrix(s.matrix))
3310 flags |= eTraversalNeeded;
3311 }
3312 if (what & layer_state_t::eTransparentRegionChanged) {
3313 if (layer->setTransparentRegionHint(s.transparentRegion))
3314 flags |= eTraversalNeeded;
3315 }
3316 if (what & layer_state_t::eFlagsChanged) {
3317 if (layer->setFlags(s.flags, s.mask))
3318 flags |= eTraversalNeeded;
3319 }
3320 if (what & layer_state_t::eCropChanged) {
3321 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3322 flags |= eTraversalNeeded;
3323 }
3324 if (what & layer_state_t::eFinalCropChanged) {
3325 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3326 flags |= eTraversalNeeded;
3327 }
3328 if (what & layer_state_t::eLayerStackChanged) {
3329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3330 // We only allow setting layer stacks for top level layers,
3331 // everything else inherits layer stack from its parent.
3332 if (layer->hasParent()) {
3333 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3334 layer->getName().string());
3335 } else if (idx < 0) {
3336 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3337 "that also does not appear in the top level layer list. Something"
3338 " has gone wrong.", layer->getName().string());
3339 } else if (layer->setLayerStack(s.layerStack)) {
3340 mCurrentState.layersSortedByZ.removeAt(idx);
3341 mCurrentState.layersSortedByZ.add(layer);
3342 // we need traversal (state changed)
3343 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003344 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003345 }
3346 }
3347 if (what & layer_state_t::eDeferTransaction) {
3348 if (s.barrierHandle != nullptr) {
3349 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3350 } else if (s.barrierGbp != nullptr) {
3351 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3352 if (authenticateSurfaceTextureLocked(gbp)) {
3353 const auto& otherLayer =
3354 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3355 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3356 } else {
3357 ALOGE("Attempt to defer transaction to to an"
3358 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003359 }
3360 }
chaviw8b3871a2017-11-01 17:41:01 -07003361 // We don't trigger a traversal here because if no other state is
3362 // changed, we don't want this to cause any more work
3363 }
3364 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003365 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003366 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003367 if (!hadParent) {
3368 mCurrentState.layersSortedByZ.remove(layer);
3369 }
chaviw8b3871a2017-11-01 17:41:01 -07003370 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 }
3373 if (what & layer_state_t::eReparentChildren) {
3374 if (layer->reparentChildren(s.reparentHandle)) {
3375 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003376 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003377 }
chaviw8b3871a2017-11-01 17:41:01 -07003378 if (what & layer_state_t::eDetachChildren) {
3379 layer->detachChildren();
3380 }
3381 if (what & layer_state_t::eOverrideScalingModeChanged) {
3382 layer->setOverrideScalingMode(s.overrideScalingMode);
3383 // We don't trigger a traversal here because if no other state is
3384 // changed, we don't want this to cause any more work
3385 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003386 return flags;
3387}
3388
chaviwca27f252018-02-06 16:46:39 -08003389void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3390 const layer_state_t& state = composerState.state;
3391 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3392
3393 sp<Layer> layer(client->getLayerUser(state.surface));
3394 if (layer == nullptr) {
3395 return;
3396 }
3397
3398 if (layer->isPendingRemoval()) {
3399 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3400 return;
3401 }
3402
3403 if (state.what & layer_state_t::eDestroySurface) {
3404 removeLayerLocked(mStateLock, layer);
3405 }
3406}
3407
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003408status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003409 const String8& name,
3410 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003411 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003412 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003413 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003415 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003416 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003417 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003418 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003419 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003420
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003421 status_t result = NO_ERROR;
3422
3423 sp<Layer> layer;
3424
Cody Northropbc755282017-03-31 12:00:08 -06003425 String8 uniqueName = getUniqueLayerName(name);
3426
Mathias Agopian3165cc22012-08-08 19:42:09 -07003427 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3428 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003429 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003430 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003431 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003432
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433 break;
chaviw13fdc492017-06-27 12:40:18 -07003434 case ISurfaceComposerClient::eFXSurfaceColor:
3435 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003436 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003437 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003438 break;
3439 default:
3440 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441 break;
3442 }
3443
Dan Stoza7d89d062015-04-30 13:29:25 -07003444 if (result != NO_ERROR) {
3445 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003447
Chia-I Wuab0c3192017-08-01 11:29:00 -07003448 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3449 // TODO b/64227542
3450 if (windowType == 441731) {
3451 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3452 layer->setPrimaryDisplayOnly();
3453 }
3454
Albert Chaulk479c60c2017-01-27 14:21:34 -05003455 layer->setInfo(windowType, ownerUid);
3456
Robert Carr1f0a16a2016-10-24 16:27:39 -07003457 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003458 if (result != NO_ERROR) {
3459 return result;
3460 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003461 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003462
3463 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003464 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003465}
3466
Cody Northropbc755282017-03-31 12:00:08 -06003467String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3468{
3469 bool matchFound = true;
3470 uint32_t dupeCounter = 0;
3471
3472 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3473 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3474
3475 // Loop over layers until we're sure there is no matching name
3476 while (matchFound) {
3477 matchFound = false;
3478 mDrawingState.traverseInZOrder([&](Layer* layer) {
3479 if (layer->getName() == uniqueName) {
3480 matchFound = true;
3481 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3482 }
3483 });
3484 }
3485
3486 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3487
3488 return uniqueName;
3489}
3490
David Sodman0c69cad2017-08-21 12:12:51 -07003491status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003492 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3493 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494{
3495 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003496 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497 case PIXEL_FORMAT_TRANSPARENT:
3498 case PIXEL_FORMAT_TRANSLUCENT:
3499 format = PIXEL_FORMAT_RGBA_8888;
3500 break;
3501 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003502 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503 break;
3504 }
3505
David Sodman0c69cad2017-08-21 12:12:51 -07003506 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3507 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003509 *handle = layer->getHandle();
3510 *gbp = layer->getProducer();
3511 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513
David Sodman0c69cad2017-08-21 12:12:51 -07003514 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003515 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516}
3517
chaviw13fdc492017-06-27 12:40:18 -07003518status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003520 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521{
chaviw13fdc492017-06-27 12:40:18 -07003522 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003524 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003525}
3526
Mathias Agopianac9fa422013-02-11 16:40:36 -08003527status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528{
Robert Carr9524cb32017-02-13 11:32:32 -08003529 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003530 status_t err = NO_ERROR;
3531 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003532 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003533 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003534 err = removeLayer(l);
3535 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3536 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003537 }
3538 return err;
3539}
3540
Mathias Agopian13127d82013-03-05 17:47:11 -08003541status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003542{
Mathias Agopian67106042013-03-14 19:18:13 -07003543 // called by ~LayerCleaner() when all references to the IBinder (handle)
3544 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003545 sp<Layer> l = layer.promote();
3546 if (l == nullptr) {
3547 // The layer has already been removed, carry on
3548 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003549 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003550 // If we have a parent, then we can continue to live as long as it does.
3551 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552}
3553
Mathias Agopianb60314a2012-04-10 22:09:54 -07003554// ---------------------------------------------------------------------------
3555
Andy McFadden13a082e2012-08-24 10:16:42 -07003556void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003557 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003558 Vector<ComposerState> state;
3559 Vector<DisplayState> displays;
3560 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003561 d.what = DisplayState::eDisplayProjectionChanged |
3562 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003563 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003564 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003565 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003566 d.frame.makeInvalid();
3567 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003568 d.width = 0;
3569 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003570 displays.add(d);
3571 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003572 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3573 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003574
David Sodman105b7dc2017-11-04 20:28:14 -07003575 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003576 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003577 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003578
Brian Andersond0010582017-03-07 13:20:31 -08003579 // Use phase of 0 since phase is not known.
3580 // Use latency of 0, which will snap to the ideal latency.
3581 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003582}
3583
3584void SurfaceFlinger::initializeDisplays() {
3585 class MessageScreenInitialized : public MessageBase {
3586 SurfaceFlinger* flinger;
3587 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003588 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003589 virtual bool handler() {
3590 flinger->onInitializeDisplays();
3591 return true;
3592 }
3593 };
3594 sp<MessageBase> msg = new MessageScreenInitialized(this);
3595 postMessageAsync(msg); // we may be called from main thread, use async message
3596}
3597
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003598void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003599 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3601 this);
3602 int32_t type = hw->getDisplayType();
3603 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003604
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003605 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003606 return;
3607 }
3608
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003609 hw->setPowerMode(mode);
3610 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3611 ALOGW("Trying to set power mode for virtual display");
3612 return;
3613 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003614
Lloyd Pique4d234852018-01-22 17:21:36 -08003615 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003616 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003617 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3618 if (idx < 0) {
3619 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3620 return;
3621 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003622 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003623 }
3624
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003625 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003626 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003627 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003628 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3629 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003630 // FIXME: eventthread only knows about the main display right now
3631 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003632 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003633 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003635 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003636 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003637 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003638
3639 struct sched_param param = {0};
3640 param.sched_priority = 1;
3641 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3642 ALOGW("Couldn't set SCHED_FIFO on display on");
3643 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003644 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003645 // Turn off the display
3646 struct sched_param param = {0};
3647 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3648 ALOGW("Couldn't set SCHED_OTHER on display off");
3649 }
3650
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003651 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3652 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003653 disableHardwareVsync(true); // also cancels any in-progress resync
3654
Mathias Agopiancde87a32012-09-13 14:09:01 -07003655 // FIXME: eventthread only knows about the main display right now
3656 mEventThread->onScreenReleased();
3657 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003658
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003659 getHwComposer().setPowerMode(type, mode);
3660 mVisibleRegionsDirty = true;
3661 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003662 } else if (mode == HWC_POWER_MODE_DOZE ||
3663 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003664 // Update display while dozing
3665 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003666 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3667 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003668 // FIXME: eventthread only knows about the main display right now
3669 mEventThread->onScreenAcquired();
3670 resyncToHardwareVsync(true);
3671 }
3672 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3673 // Leave display going to doze
3674 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3675 disableHardwareVsync(true); // also cancels any in-progress resync
3676 // FIXME: eventthread only knows about the main display right now
3677 mEventThread->onScreenReleased();
3678 }
3679 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003681 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003683 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003684 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003685}
3686
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3688 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003689 SurfaceFlinger& mFlinger;
3690 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003692 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003693 MessageSetPowerMode(SurfaceFlinger& flinger,
3694 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3695 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003696 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003698 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003700 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003701 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 ALOGW("Attempt to set power mode = %d for virtual display",
3703 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003704 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003705 mFlinger.setPowerModeInternal(
3706 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003707 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003708 return true;
3709 }
3710 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003712 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003713}
3714
3715// ---------------------------------------------------------------------------
3716
Lloyd Pique755e3192018-01-31 16:46:15 -08003717status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3718 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003720
Mathias Agopianbd115332013-04-18 16:41:04 -07003721 IPCThreadState* ipc = IPCThreadState::self();
3722 const int pid = ipc->getCallingPid();
3723 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003724
Mathias Agopianbd115332013-04-18 16:41:04 -07003725 if ((uid != AID_SHELL) &&
3726 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003727 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003728 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003730 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003731 // (this would indicate SF is stuck, but we want to be able to
3732 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003733 status_t err = mStateLock.timedLock(s2ns(1));
3734 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003735 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003736 result.appendFormat(
3737 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3738 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003739 }
3740
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003741 bool dumpAll = true;
3742 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003743 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003744
3745 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003746 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003747 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3748 dumpAll = false;
3749 }
3750
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003751 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003752 if ((index < numArgs) &&
3753 (args[index] == String16("--list"))) {
3754 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003755 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003756 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757 }
3758
3759 if ((index < numArgs) &&
3760 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003761 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003762 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003763 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003765
3766 if ((index < numArgs) &&
3767 (args[index] == String16("--latency-clear"))) {
3768 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003769 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003770 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003771 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003772
3773 if ((index < numArgs) &&
3774 (args[index] == String16("--dispsync"))) {
3775 index++;
3776 mPrimaryDispSync.dump(result);
3777 dumpAll = false;
3778 }
Dan Stozab90cf072015-03-05 11:05:59 -08003779
3780 if ((index < numArgs) &&
3781 (args[index] == String16("--static-screen"))) {
3782 index++;
3783 dumpStaticScreenStats(result);
3784 dumpAll = false;
3785 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003786
3787 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003788 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003789 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003790 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003791 dumpAll = false;
3792 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003793
3794 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3795 index++;
3796 dumpWideColorInfo(result);
3797 dumpAll = false;
3798 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003799
3800 if ((index < numArgs) &&
3801 (args[index] == String16("--enable-layer-stats"))) {
3802 index++;
3803 mLayerStats.enable();
3804 dumpAll = false;
3805 }
3806
3807 if ((index < numArgs) &&
3808 (args[index] == String16("--disable-layer-stats"))) {
3809 index++;
3810 mLayerStats.disable();
3811 dumpAll = false;
3812 }
3813
3814 if ((index < numArgs) &&
3815 (args[index] == String16("--clear-layer-stats"))) {
3816 index++;
3817 mLayerStats.clear();
3818 dumpAll = false;
3819 }
3820
3821 if ((index < numArgs) &&
3822 (args[index] == String16("--dump-layer-stats"))) {
3823 index++;
3824 mLayerStats.dump(result);
3825 dumpAll = false;
3826 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003828
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003830 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003831 }
3832
Mathias Agopian9795c422009-08-26 16:36:26 -07003833 if (locked) {
3834 mStateLock.unlock();
3835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 }
3837 write(fd, result.string(), result.size());
3838 return NO_ERROR;
3839}
3840
Dan Stozac7014012014-02-14 15:03:43 -08003841void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3842 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843{
Robert Carr2047fae2016-11-28 14:09:09 -08003844 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003845 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003846 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847}
3848
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003850 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851{
3852 String8 name;
3853 if (index < args.size()) {
3854 name = String8(args[index]);
3855 index++;
3856 }
3857
David Sodman105b7dc2017-11-04 20:28:14 -07003858 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003859 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003860 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003861
3862 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003863 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003864 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003865 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003866 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003867 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003868 }
Robert Carr2047fae2016-11-28 14:09:09 -08003869 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 }
3871}
3872
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003873void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003874 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003875{
3876 String8 name;
3877 if (index < args.size()) {
3878 name = String8(args[index]);
3879 index++;
3880 }
3881
Robert Carr2047fae2016-11-28 14:09:09 -08003882 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003884 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003885 }
Robert Carr2047fae2016-11-28 14:09:09 -08003886 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003887
Svetoslavd85084b2014-03-20 10:28:31 -07003888 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003889}
3890
Jamie Gennis6547ff42013-07-16 20:12:42 -07003891// This should only be called from the main thread. Otherwise it would need
3892// the lock and should use mCurrentState rather than mDrawingState.
3893void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003894 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003895 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003896 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003897
3898 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3899}
3900
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003901void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003902{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003903 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003904
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003905 if (isLayerTripleBufferingDisabled())
3906 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003907
3908 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003909 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003910 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003911 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003912 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3913 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003914 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003915}
3916
Dan Stozab90cf072015-03-05 11:05:59 -08003917void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3918{
3919 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003920 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3921 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003922 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003923 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003924 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3925 b + 1, bucketTimeSec, percent);
3926 }
David Sodman4a36e932017-11-07 14:29:47 -08003927 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003928 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003929 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003930 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003931 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003932}
3933
Dan Stozae77c7662016-05-13 11:37:28 -07003934void SurfaceFlinger::recordBufferingStats(const char* layerName,
3935 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003936 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3937 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003938 for (const auto& segment : history) {
3939 if (!segment.usedThirdBuffer) {
3940 stats.twoBufferTime += segment.totalTime;
3941 }
3942 if (segment.occupancyAverage < 1.0f) {
3943 stats.doubleBufferedTime += segment.totalTime;
3944 } else if (segment.occupancyAverage < 2.0f) {
3945 stats.tripleBufferedTime += segment.totalTime;
3946 }
3947 ++stats.numSegments;
3948 stats.totalTime += segment.totalTime;
3949 }
3950}
3951
Brian Andersond6927fb2016-07-23 23:37:30 -07003952void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3953 result.appendFormat("Layer frame timestamps:\n");
3954
3955 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3956 const size_t count = currentLayers.size();
3957 for (size_t i=0 ; i<count ; i++) {
3958 currentLayers[i]->dumpFrameEvents(result);
3959 }
3960}
3961
Dan Stozae77c7662016-05-13 11:37:28 -07003962void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3963 result.append("Buffering stats:\n");
3964 result.append(" [Layer name] <Active time> <Two buffer> "
3965 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003966 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003967 typedef std::tuple<std::string, float, float, float> BufferTuple;
3968 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003969 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003970 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003971 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003972 if (stats.numSegments == 0) {
3973 continue;
3974 }
3975 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3976 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3977 stats.totalTime;
3978 float doubleBufferRatio = static_cast<float>(
3979 stats.doubleBufferedTime) / stats.totalTime;
3980 float tripleBufferRatio = static_cast<float>(
3981 stats.tripleBufferedTime) / stats.totalTime;
3982 sorted.insert({activeTime, {name, twoBufferRatio,
3983 doubleBufferRatio, tripleBufferRatio}});
3984 }
3985 for (const auto& sortedPair : sorted) {
3986 float activeTime = sortedPair.first;
3987 const BufferTuple& values = sortedPair.second;
3988 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3989 std::get<0>(values).c_str(), activeTime,
3990 std::get<1>(values), std::get<2>(values),
3991 std::get<3>(values));
3992 }
3993 result.append("\n");
3994}
3995
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003996void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3997 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003998 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003999
4000 // TODO: print out if wide-color mode is active or not
4001
4002 for (size_t d = 0; d < mDisplays.size(); d++) {
4003 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4004 int32_t hwcId = displayDevice->getHwcDisplayId();
4005 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4006 continue;
4007 }
4008
4009 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004010 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004011 for (auto&& mode : modes) {
4012 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4013 }
4014
Peiyong Lina52f0292018-03-14 17:26:31 -07004015 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004016 result.appendFormat(" Current color mode: %s (%d)\n",
4017 decodeColorMode(currentMode).c_str(), currentMode);
4018 }
4019 result.append("\n");
4020}
4021
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004022LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004023 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004024 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4025 const State& state = useDrawing ? mDrawingState : mCurrentState;
4026 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004027 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004028 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004029 });
4030
4031 return layersProto;
4032}
4033
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004034LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4035 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004036 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004037
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004038 SizeProto* resolution = layersProto.mutable_resolution();
4039 resolution->set_w(displayDevice->getWidth());
4040 resolution->set_h(displayDevice->getHeight());
4041
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004042 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4043 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4044 layersProto.set_global_transform(
4045 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4046
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004047 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004048 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004049 LayerProto* layerProto = layersProto.add_layers();
4050 layer->writeToProto(layerProto, hwcId);
4051 }
4052 });
4053
4054 return layersProto;
4055}
4056
Mathias Agopian74d211a2013-04-22 16:55:35 +02004057void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4058 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004059{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004060 bool colorize = false;
4061 if (index < args.size()
4062 && (args[index] == String16("--color"))) {
4063 colorize = true;
4064 index++;
4065 }
4066
4067 Colorizer colorizer(colorize);
4068
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004069 // figure out if we're stuck somewhere
4070 const nsecs_t now = systemTime();
4071 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4072 const nsecs_t inTransaction(mDebugInTransaction);
4073 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4074 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4075
4076 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004077 * Dump library configuration.
4078 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004079
4080 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004081 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004082 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004083 appendSfConfigString(result);
4084 appendUiConfigString(result);
4085 appendGuiConfigString(result);
4086 result.append("\n");
4087
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004088 result.append("\nWide-Color information:\n");
4089 dumpWideColorInfo(result);
4090
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004091 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004092 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004093 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004094 result.append(SyncFeatures::getInstance().toString());
4095 result.append("\n");
4096
David Sodman105b7dc2017-11-04 20:28:14 -07004097 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004098
Andy McFadden41d67d72014-04-25 16:58:34 -07004099 colorizer.bold(result);
4100 result.append("DispSync configuration: ");
4101 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004102 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004103 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004104 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004105 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004106 result.append("\n");
4107
Dan Stozab90cf072015-03-05 11:05:59 -08004108 // Dump static screen stats
4109 result.append("\n");
4110 dumpStaticScreenStats(result);
4111 result.append("\n");
4112
Dan Stozae77c7662016-05-13 11:37:28 -07004113 dumpBufferingStats(result);
4114
Andy McFadden4803b742012-09-24 19:07:20 -07004115 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004116 * Dump the visible layer list
4117 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004118 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004119 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004120 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4121 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004122 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004123
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004124 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004125 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004126 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004127 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004128
4129 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004130 * Dump Display state
4131 */
4132
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004133 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004134 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004135 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004136 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4137 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004138 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004139 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004140 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004141
4142 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143 * Dump SurfaceFlinger global state
4144 */
4145
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004146 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004147 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004148 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149
Mathias Agopian888c8222012-08-04 21:10:38 -07004150 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004151 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004152
David Sodmanbc815282017-11-05 18:57:52 -08004153 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004154
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004155 if (hw) {
4156 hw->undefinedRegion.dump(result, "undefinedRegion");
4157 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4158 hw->getOrientation(), hw->isDisplayOn());
4159 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004160 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004161 " last eglSwapBuffers() time: %f us\n"
4162 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004163 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004164 " refresh-rate : %f fps\n"
4165 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004166 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004167 " gpu_to_cpu_unsupported : %d\n"
4168 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004169 mLastSwapBufferTime/1000.0,
4170 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004171 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004172 1e9 / activeConfig->getVsyncPeriod(),
4173 activeConfig->getDpiX(),
4174 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004175 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176
Mathias Agopian74d211a2013-04-22 16:55:35 +02004177 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004178 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004179
Mathias Agopian74d211a2013-04-22 16:55:35 +02004180 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004181 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004182
4183 /*
4184 * VSYNC state
4185 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004186 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004187 result.append("\n");
4188
4189 /*
4190 * HWC layer minidump
4191 */
4192 for (size_t d = 0; d < mDisplays.size(); d++) {
4193 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4194 int32_t hwcId = displayDevice->getHwcDisplayId();
4195 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4196 continue;
4197 }
4198
4199 result.appendFormat("Display %d HWC layers:\n", hwcId);
4200 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004202 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004203 });
Dan Stozae22aec72016-08-01 13:20:59 -07004204 result.append("\n");
4205 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004206
4207 /*
4208 * Dump HWComposer state
4209 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004210 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004213 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004214 result.appendFormat(" h/w composer %s\n",
4215 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004216 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004217
4218 /*
4219 * Dump gralloc state
4220 */
4221 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4222 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004223
4224 /*
4225 * Dump VrFlinger state if in use.
4226 */
4227 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4228 result.append("VrFlinger state:\n");
4229 result.append(mVrFlinger->Dump().c_str());
4230 result.append("\n");
4231 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232}
4233
Mathias Agopian13127d82013-03-05 17:47:11 -08004234const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004235SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004236 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004237 wp<IBinder> dpy;
4238 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4239 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4240 dpy = mDisplays.keyAt(i);
4241 break;
4242 }
4243 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004244 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004245 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4246 // Just use the primary display so we have something to return
4247 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4248 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004249 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004250}
4251
Keun young Park63f165f2012-08-31 10:53:36 -07004252bool SurfaceFlinger::startDdmConnection()
4253{
4254 void* libddmconnection_dso =
4255 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4256 if (!libddmconnection_dso) {
4257 return false;
4258 }
4259 void (*DdmConnection_start)(const char* name);
4260 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004261 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004262 if (!DdmConnection_start) {
4263 dlclose(libddmconnection_dso);
4264 return false;
4265 }
4266 (*DdmConnection_start)(getServiceName());
4267 return true;
4268}
4269
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004270status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004271 switch (code) {
4272 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004273 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004275 case CLEAR_ANIMATION_FRAME_STATS:
4276 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004278 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004279 case ENABLE_VSYNC_INJECTIONS:
4280 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281 {
4282 // codes that require permission check
4283 IPCThreadState* ipc = IPCThreadState::self();
4284 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004285 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004286 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004287 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004288 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004289 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004290 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004291 break;
4292 }
Robert Carr1db73f62016-12-21 12:58:51 -08004293 /*
4294 * Calling setTransactionState is safe, because you need to have been
4295 * granted a reference to Client* and Handle* to do anything with it.
4296 *
4297 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4298 */
4299 case SET_TRANSACTION_STATE:
4300 case CREATE_SCOPED_CONNECTION:
4301 {
4302 return OK;
4303 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004304 case CAPTURE_SCREEN:
4305 {
4306 // codes that require permission check
4307 IPCThreadState* ipc = IPCThreadState::self();
4308 const int pid = ipc->getCallingPid();
4309 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004310 if ((uid != AID_GRAPHICS) &&
4311 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004312 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004313 return PERMISSION_DENIED;
4314 }
4315 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 }
chaviwa76b2712017-09-20 12:02:26 -07004317 case CAPTURE_LAYERS: {
4318 IPCThreadState* ipc = IPCThreadState::self();
4319 const int pid = ipc->getCallingPid();
4320 const int uid = ipc->getCallingUid();
4321 if ((uid != AID_GRAPHICS) &&
4322 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4323 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4324 return PERMISSION_DENIED;
4325 }
4326 break;
4327 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004328 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004329 return OK;
4330}
4331
4332status_t SurfaceFlinger::onTransact(
4333 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4334{
4335 status_t credentialCheck = CheckTransactCodeCredentials(code);
4336 if (credentialCheck != OK) {
4337 return credentialCheck;
4338 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004340 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4341 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004342 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004343 IPCThreadState* ipc = IPCThreadState::self();
4344 const int uid = ipc->getCallingUid();
4345 if (CC_UNLIKELY(uid != AID_SYSTEM
4346 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004347 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004348 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004349 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 return PERMISSION_DENIED;
4351 }
4352 int n;
4353 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004354 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004355 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 return NO_ERROR;
4357 case 1002: // SHOW_UPDATES
4358 n = data.readInt32();
4359 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004360 invalidateHwcGeometry();
4361 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004364 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004365 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004367 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004368 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004369 setTransactionFlags(
4370 eTransactionNeeded|
4371 eDisplayTransactionNeeded|
4372 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004373 return NO_ERROR;
4374 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004375 case 1006:{ // send empty update
4376 signalRefresh();
4377 return NO_ERROR;
4378 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004379 case 1008: // toggle use of hw composer
4380 n = data.readInt32();
4381 mDebugDisableHWC = n ? 1 : 0;
4382 invalidateHwcGeometry();
4383 repaintEverything();
4384 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004385 case 1009: // toggle use of transform hint
4386 n = data.readInt32();
4387 mDebugDisableTransformHint = n ? 1 : 0;
4388 invalidateHwcGeometry();
4389 repaintEverything();
4390 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004391 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004392 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004393 reply->writeInt32(0);
4394 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004395 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004396 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004397 return NO_ERROR;
4398 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004399 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004400 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004401 return NO_ERROR;
4402 }
4403 case 1014: {
4404 // daltonize
4405 n = data.readInt32();
4406 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004407 case 1:
4408 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4409 break;
4410 case 2:
4411 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4412 break;
4413 case 3:
4414 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4415 break;
4416 default:
4417 mDaltonizer.setType(ColorBlindnessType::None);
4418 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004419 }
4420 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004421 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004422 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004423 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004424 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004425 invalidateHwcGeometry();
4426 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004427 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004428 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004429 case 1015: {
4430 // apply a color matrix
4431 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004432 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004433 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004434 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004435 for (size_t j = 0; j < 4; j++) {
4436 mColorMatrix[i][j] = data.readFloat();
4437 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004438 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004439 } else {
4440 mColorMatrix = mat4();
4441 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004442
4443 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4444 // the division by w in the fragment shader
4445 float4 lastRow(transpose(mColorMatrix)[3]);
4446 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4447 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4448 }
4449
Alan Viverette9c5a3332013-09-12 20:04:35 -07004450 invalidateHwcGeometry();
4451 repaintEverything();
4452 return NO_ERROR;
4453 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004454 // This is an experimental interface
4455 // Needs to be shifted to proper binder interface when we productize
4456 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004457 n = data.readInt32();
4458 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004459 return NO_ERROR;
4460 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004461 case 1017: {
4462 n = data.readInt32();
4463 mForceFullDamage = static_cast<bool>(n);
4464 return NO_ERROR;
4465 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004466 case 1018: { // Modify Choreographer's phase offset
4467 n = data.readInt32();
4468 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4469 return NO_ERROR;
4470 }
4471 case 1019: { // Modify SurfaceFlinger's phase offset
4472 n = data.readInt32();
4473 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4474 return NO_ERROR;
4475 }
Irvel468051e2016-06-13 16:44:44 -07004476 case 1020: { // Layer updates interceptor
4477 n = data.readInt32();
4478 if (n) {
4479 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004480 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004481 }
4482 else{
4483 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004484 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004485 }
4486 return NO_ERROR;
4487 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004488 case 1021: { // Disable HWC virtual displays
4489 n = data.readInt32();
4490 mUseHwcVirtualDisplays = !n;
4491 return NO_ERROR;
4492 }
Romain Guy0147a172017-06-01 13:53:56 -07004493 case 1022: { // Set saturation boost
4494 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4495
4496 invalidateHwcGeometry();
4497 repaintEverything();
4498 return NO_ERROR;
4499 }
Romain Guy54f154a2017-10-24 21:40:32 +01004500 case 1023: { // Set native mode
4501 mForceNativeColorMode = data.readInt32() == 1;
4502
4503 invalidateHwcGeometry();
4504 repaintEverything();
4505 return NO_ERROR;
4506 }
4507 case 1024: { // Is wide color gamut rendering/color management supported?
4508 reply->writeBool(hasWideColorDisplay);
4509 return NO_ERROR;
4510 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004511 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004512 n = data.readInt32();
4513 if (n) {
4514 ALOGV("LayerTracing enabled");
4515 mTracing.enable();
4516 doTracing("tracing.enable");
4517 reply->writeInt32(NO_ERROR);
4518 } else {
4519 ALOGV("LayerTracing disabled");
4520 status_t err = mTracing.disable();
4521 reply->writeInt32(err);
4522 }
4523 return NO_ERROR;
4524 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004525 case 1026: { // Get layer tracing status
4526 reply->writeBool(mTracing.isEnabled());
4527 return NO_ERROR;
4528 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 }
4530 }
4531 return err;
4532}
4533
Steven Thomas6d8110b2017-08-31 18:24:21 -07004534void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004535 android_atomic_or(1, &mRepaintEverything);
Jeffrey Kardatzkea9dcf112018-04-03 10:45:55 -07004536 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
4537 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
4538 const Rect bounds(displayDevice->getBounds());
4539 displayDevice->dirtyRegion.orSelf(Region(bounds));
4540 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004541 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004542}
4543
Steven Thomas6d8110b2017-08-31 18:24:21 -07004544void SurfaceFlinger::repaintEverything() {
4545 ConditionalLock _l(mStateLock,
4546 std::this_thread::get_id() != mMainThreadId);
4547 repaintEverythingLocked();
4548}
4549
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004550// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4551class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004552public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004553 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4554 ~WindowDisconnector() {
4555 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004556 }
4557
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004558private:
4559 ANativeWindow* mWindow;
4560 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004561};
4562
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004563status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4564 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4565 int32_t minLayerZ, int32_t maxLayerZ,
4566 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004567 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004568 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004569
chaviwa76b2712017-09-20 12:02:26 -07004570 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4571
4572 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004573 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4574
chaviwa76b2712017-09-20 12:02:26 -07004575 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4576
4577 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4578 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004579 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004580}
4581
4582status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004583 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004584 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004585 ATRACE_CALL();
4586
4587 class LayerRenderArea : public RenderArea {
4588 public:
Robert Carr578038f2018-03-09 12:25:24 -08004589 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4590 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4591 : RenderArea(reqHeight, reqWidth),
4592 mLayer(layer),
4593 mCrop(crop),
4594 mFlinger(flinger),
4595 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004596 Rect getBounds() const override {
4597 const Layer::State& layerState(mLayer->getDrawingState());
4598 return Rect(layerState.active.w, layerState.active.h);
4599 }
4600 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4601 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4602 bool isSecure() const override { return false; }
4603 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004604 const Transform& getTransform() const { return mTransform; }
4605
4606 class ReparentForDrawing {
4607 public:
4608 const sp<Layer>& oldParent;
4609 const sp<Layer>& newParent;
4610
4611 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4612 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004613 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004614 }
Robert Carr15eae092018-03-23 13:43:53 -07004615 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004616 };
4617
4618 void render(std::function<void()> drawLayers) override {
4619 if (!mChildrenOnly) {
4620 mTransform = mLayer->getTransform().inverse();
4621 drawLayers();
4622 } else {
4623 Rect bounds = getBounds();
4624 screenshotParentLayer =
4625 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4626 bounds.getWidth(), bounds.getHeight(), 0);
4627
4628 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4629 drawLayers();
4630 }
4631 }
chaviwa76b2712017-09-20 12:02:26 -07004632
chaviw7206d492017-11-10 16:16:12 -08004633 Rect getSourceCrop() const override {
4634 if (mCrop.isEmpty()) {
4635 return getBounds();
4636 } else {
4637 return mCrop;
4638 }
4639 }
chaviwa76b2712017-09-20 12:02:26 -07004640 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004641 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004642
4643 private:
chaviw7206d492017-11-10 16:16:12 -08004644 const sp<Layer> mLayer;
4645 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004646
4647 // In the "childrenOnly" case we reparent the children to a screenshot
4648 // layer which has no properties set and which does not draw.
4649 sp<ContainerLayer> screenshotParentLayer;
4650 Transform mTransform;
4651
4652 SurfaceFlinger* mFlinger;
4653 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004654 };
4655
4656 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4657 auto parent = layerHandle->owner.promote();
4658
chaviw7206d492017-11-10 16:16:12 -08004659 if (parent == nullptr || parent->isPendingRemoval()) {
4660 ALOGE("captureLayers called with a removed parent");
4661 return NAME_NOT_FOUND;
4662 }
4663
Robert Carr578038f2018-03-09 12:25:24 -08004664 const int uid = IPCThreadState::self()->getCallingUid();
4665 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4666 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4667 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4668 return PERMISSION_DENIED;
4669 }
4670
chaviw7206d492017-11-10 16:16:12 -08004671 Rect crop(sourceCrop);
4672 if (sourceCrop.width() <= 0) {
4673 crop.left = 0;
4674 crop.right = parent->getCurrentState().active.w;
4675 }
4676
4677 if (sourceCrop.height() <= 0) {
4678 crop.top = 0;
4679 crop.bottom = parent->getCurrentState().active.h;
4680 }
4681
4682 int32_t reqWidth = crop.width() * frameScale;
4683 int32_t reqHeight = crop.height() * frameScale;
4684
Robert Carr578038f2018-03-09 12:25:24 -08004685 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004686
Robert Carr578038f2018-03-09 12:25:24 -08004687 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004688 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4689 if (!layer->isVisible()) {
4690 return;
Robert Carr578038f2018-03-09 12:25:24 -08004691 } else if (childrenOnly && layer == parent.get()) {
4692 return;
chaviwa76b2712017-09-20 12:02:26 -07004693 }
4694 visitor(layer);
4695 });
4696 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004697 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004698}
4699
4700status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4701 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004702 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004703 bool useIdentityTransform) {
4704 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004705
chaviwa76b2712017-09-20 12:02:26 -07004706 renderArea.updateDimensions();
4707
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004708 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4709 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4710 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4711 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004712
4713 // This mutex protects syncFd and captureResult for communication of the return values from the
4714 // main thread back to this Binder thread
4715 std::mutex captureMutex;
4716 std::condition_variable captureCondition;
4717 std::unique_lock<std::mutex> captureLock(captureMutex);
4718 int syncFd = -1;
4719 std::optional<status_t> captureResult;
4720
Robert Carr03480e22018-01-04 16:02:06 -08004721 const int uid = IPCThreadState::self()->getCallingUid();
4722 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4723
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004724 sp<LambdaMessage> message = new LambdaMessage([&]() {
4725 // If there is a refresh pending, bug out early and tell the binder thread to try again
4726 // after the refresh.
4727 if (mRefreshPending) {
4728 ATRACE_NAME("Skipping screenshot for now");
4729 std::unique_lock<std::mutex> captureLock(captureMutex);
4730 captureResult = std::make_optional<status_t>(EAGAIN);
4731 captureCondition.notify_one();
4732 return;
4733 }
4734
4735 status_t result = NO_ERROR;
4736 int fd = -1;
4737 {
4738 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004739 renderArea.render([&]() {
4740 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4741 useIdentityTransform, forSystem, &fd);
4742 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004743 }
4744
4745 {
4746 std::unique_lock<std::mutex> captureLock(captureMutex);
4747 syncFd = fd;
4748 captureResult = std::make_optional<status_t>(result);
4749 captureCondition.notify_one();
4750 }
4751 });
4752
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004753 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004754 if (result == NO_ERROR) {
4755 captureCondition.wait(captureLock, [&]() { return captureResult; });
4756 while (*captureResult == EAGAIN) {
4757 captureResult.reset();
4758 result = postMessageAsync(message);
4759 if (result != NO_ERROR) {
4760 return result;
4761 }
4762 captureCondition.wait(captureLock, [&]() { return captureResult; });
4763 }
4764 result = *captureResult;
4765 }
4766
4767 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004768 sync_wait(syncFd, -1);
4769 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004770 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004771
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004772 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004773}
4774
chaviwa76b2712017-09-20 12:02:26 -07004775void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4776 TraverseLayersFunction traverseLayers, bool yswap,
4777 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004778 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004779
Lloyd Pique144e1162017-12-20 16:44:52 -08004780 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004781
4782 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004783 const auto raWidth = renderArea.getWidth();
4784 const auto raHeight = renderArea.getHeight();
4785
4786 const auto reqWidth = renderArea.getReqWidth();
4787 const auto reqHeight = renderArea.getReqHeight();
4788 Rect sourceCrop = renderArea.getSourceCrop();
4789
4790 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4791 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004792
Dan Stozac1879002014-05-22 15:59:05 -07004793 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004794 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004795 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004796 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004797 }
4798
4799 // ensure that sourceCrop is inside screen
4800 if (sourceCrop.left < 0) {
4801 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4802 }
chaviwa76b2712017-09-20 12:02:26 -07004803 if (sourceCrop.right > raWidth) {
4804 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004805 }
4806 if (sourceCrop.top < 0) {
4807 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4808 }
chaviwa76b2712017-09-20 12:02:26 -07004809 if (sourceCrop.bottom > raHeight) {
4810 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004811 }
4812
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004813 Dataspace outputDataspace = Dataspace::UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004814 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004815 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004816 outputDataspace = Dataspace::DISPLAY_P3;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004817 }
4818 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004819
Mathias Agopian180f10d2013-04-10 22:55:41 -07004820 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004821 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004822
4823 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004824 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4825 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004826 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004827
4828 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004829 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004830
chaviwa76b2712017-09-20 12:02:26 -07004831 traverseLayers([&](Layer* layer) {
4832 if (filtering) layer->setFiltering(true);
4833 layer->draw(renderArea, useIdentityTransform);
4834 if (filtering) layer->setFiltering(false);
4835 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004836}
4837
chaviwa76b2712017-09-20 12:02:26 -07004838status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4839 TraverseLayersFunction traverseLayers,
4840 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004841 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004842 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004843 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004844 ATRACE_CALL();
4845
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004846 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004847
4848 traverseLayers([&](Layer* layer) {
4849 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4850 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004851
Robert Carr03480e22018-01-04 16:02:06 -08004852 // We allow the system server to take screenshots of secure layers for
4853 // use in situations like the Screen-rotation animation and place
4854 // the impetus on WindowManager to not persist them.
4855 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004856 ALOGW("FB is protected: PERMISSION_DENIED");
4857 return PERMISSION_DENIED;
4858 }
4859
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004860 // this binds the given EGLImage as a framebuffer for the
4861 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004862 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004863 if (bufferBond.getStatus() != NO_ERROR) {
4864 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004865 return INVALID_OPERATION;
4866 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004867
Dan Stozaabcda352017-06-01 14:37:39 -07004868 // this will in fact render into our dequeued buffer
4869 // via an FBO, which means we didn't have to create
4870 // an EGLSurface and therefore we're not
4871 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004872 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004873
Dan Stozaabcda352017-06-01 14:37:39 -07004874 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004875 getRenderEngine().finish();
4876 *outSyncFd = -1;
4877
chaviwa76b2712017-09-20 12:02:26 -07004878 const auto reqWidth = renderArea.getReqWidth();
4879 const auto reqHeight = renderArea.getReqHeight();
4880
Dan Stozaabcda352017-06-01 14:37:39 -07004881 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4882 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004883 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004884 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004885 } else {
4886 base::unique_fd syncFd = getRenderEngine().flush();
4887 if (syncFd < 0) {
4888 getRenderEngine().finish();
4889 }
4890 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004891 }
4892
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004893 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004894}
4895
Mathias Agopiand5556842013-09-19 17:08:37 -07004896void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004897 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004898 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004899 for (size_t y = 0; y < h; y++) {
4900 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4901 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004902 if (p[x] != 0xFF000000) return;
4903 }
4904 }
chaviwa76b2712017-09-20 12:02:26 -07004905 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004906
Robert Carr2047fae2016-11-28 14:09:09 -08004907 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004908 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004909 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004910 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4911 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4912 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4913 static_cast<float>(state.color.a));
4914 i++;
4915 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004916 }
4917}
4918
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004919// ---------------------------------------------------------------------------
4920
Dan Stoza412903f2017-04-27 13:42:17 -07004921void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4922 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004923}
4924
Dan Stoza412903f2017-04-27 13:42:17 -07004925void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4926 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004927}
4928
chaviwa76b2712017-09-20 12:02:26 -07004929void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4930 int32_t maxLayerZ,
4931 const LayerVector::Visitor& visitor) {
4932 // We loop through the first level of layers without traversing,
4933 // as we need to interpret min/max layer Z in the top level Z space.
4934 for (const auto& layer : mDrawingState.layersSortedByZ) {
4935 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4936 continue;
4937 }
4938 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004939 // relative layers are traversed in Layer::traverseInZOrder
4940 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004941 continue;
4942 }
4943 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004944 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4945 return;
4946 }
chaviwa76b2712017-09-20 12:02:26 -07004947 if (!layer->isVisible()) {
4948 return;
4949 }
4950 visitor(layer);
4951 });
4952 }
4953}
4954
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004956
4957
4958#if defined(__gl_h_)
4959#error "don't include gl/gl.h in this file"
4960#endif
4961
4962#if defined(__gl2_h_)
4963#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004964#endif