blob: 982107b4d87107890d265a677cc4aa71cc80a4a9 [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
Dan Stoza2713c302018-03-28 17:07:36 -0700299 property_get("debug.sf.early_phase_offset_ns", value, "0");
300 const int earlyWakeupOffsetOffsetNs = atoi(value);
301 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
302 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
303 sfVsyncPhaseOffsetNs);
304
Romain Guy11d63f42017-07-20 12:47:14 -0700305 // We should be reading 'persist.sys.sf.color_saturation' here
306 // but since /data may be encrypted, we need to wait until after vold
307 // comes online to attempt to read the property. The property is
308 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800309
310 if (useTrebleTestingOverride()) {
311 // Without the override SurfaceFlinger cannot connect to HIDL
312 // services that are not listed in the manifests. Considered
313 // deriving the setting from the set service name, but it
314 // would be brittle if the name that's not 'default' is used
315 // for production purposes later on.
316 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
317 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318}
319
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800320void SurfaceFlinger::onFirstRef()
321{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800322 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800323}
324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325SurfaceFlinger::~SurfaceFlinger()
326{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327}
328
Dan Stozac7014012014-02-14 15:03:43 -0800329void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800330{
331 // the window manager died on us. prepare its eulogy.
332
Andy McFadden13a082e2012-08-24 10:16:42 -0700333 // restore initial conditions (default device unblank, etc)
334 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800335
336 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700337 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800338}
339
Robert Carr1db73f62016-12-21 12:58:51 -0800340static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700341 status_t err = client->initCheck();
342 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800343 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 }
Robert Carr1db73f62016-12-21 12:58:51 -0800345 return nullptr;
346}
347
348sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
349 return initClient(new Client(this));
350}
351
352sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
353 const sp<IGraphicBufferProducer>& gbp) {
354 if (authenticateSurfaceTexture(gbp) == false) {
355 return nullptr;
356 }
357 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
358 if (layer == nullptr) {
359 return nullptr;
360 }
361
362 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700365sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
366 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700367{
368 class DisplayToken : public BBinder {
369 sp<SurfaceFlinger> flinger;
370 virtual ~DisplayToken() {
371 // no more references, this display must be terminated
372 Mutex::Autolock _l(flinger->mStateLock);
373 flinger->mCurrentState.displays.removeItem(this);
374 flinger->setTransactionFlags(eDisplayTransactionNeeded);
375 }
376 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700377 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378 : flinger(flinger) {
379 }
380 };
381
382 sp<BBinder> token = new DisplayToken(this);
383
384 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700385 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700386 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700387 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800388 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389 return token;
390}
391
Jesse Hall6c913be2013-08-08 12:15:49 -0700392void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
393 Mutex::Autolock _l(mStateLock);
394
395 ssize_t idx = mCurrentState.displays.indexOfKey(display);
396 if (idx < 0) {
397 ALOGW("destroyDisplay: invalid display token");
398 return;
399 }
400
401 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
402 if (!info.isVirtualDisplay()) {
403 ALOGE("destroyDisplay called for non-virtual display");
404 return;
405 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800406 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700407 mCurrentState.displays.removeItemsAt(idx);
408 setTransactionFlags(eDisplayTransactionNeeded);
409}
410
Mathias Agopiane57f2922012-08-09 16:29:12 -0700411sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700412 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800414 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 }
Jesse Hall692c7232012-11-08 15:41:56 -0800416 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417}
418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419void SurfaceFlinger::bootFinished()
420{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700421 if (mStartPropertySetThread->join() != NO_ERROR) {
422 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 const nsecs_t now = systemTime();
425 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000426 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700427
428 // wait patiently for the window manager death
429 const String16 name("window");
430 sp<IBinder> window(defaultServiceManager()->getService(name));
431 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700433 }
434
Steven Thomas050b2c82017-03-06 11:45:16 -0800435 if (mVrFlinger) {
436 mVrFlinger->OnBootFinished();
437 }
438
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700439 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 // formerly we would just kill the process, but we now ask it to exit so it
441 // can choose where to stop the animation.
442 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700443
444 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
445 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
446 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700447
Thierry Strudel2924d012017-08-14 15:19:37 -0700448 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700449 readPersistentProperties();
450 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700451 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452}
453
Mathias Agopian3f844832013-08-07 21:24:32 -0700454void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700455 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800456 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700457 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700458 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800459 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
460 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700461 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700462 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700463 return true;
464 }
465 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700466 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700467}
468
Lloyd Piquee83f9312018-02-01 12:53:17 -0800469class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700471 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000472 const char* name) :
473 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700474 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700475 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000476 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
477 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 mDispSync(dispSync),
479 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 mVsyncMutex(),
481 mPhaseOffset(phaseOffset),
482 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700483
Lloyd Piquee83f9312018-02-01 12:53:17 -0800484 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485
Lloyd Piquee83f9312018-02-01 12:53:17 -0800486 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000489 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 static_cast<DispSync::Callback*>(this));
491 if (err != NO_ERROR) {
492 ALOGE("error registering vsync callback: %s (%d)",
493 strerror(-err), err);
494 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 } else {
497 status_t err = mDispSync->removeEventListener(
498 static_cast<DispSync::Callback*>(this));
499 if (err != NO_ERROR) {
500 ALOGE("error unregistering vsync callback: %s (%d)",
501 strerror(-err), err);
502 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700503 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700504 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506 }
507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 mCallback = callback;
511 }
512
Lloyd Piquee83f9312018-02-01 12:53:17 -0800513 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700514 Mutex::Autolock lock(mVsyncMutex);
515
516 // Normalize phaseOffset to [0, period)
517 auto period = mDispSync->getPeriod();
518 phaseOffset %= period;
519 if (phaseOffset < 0) {
520 // If we're here, then phaseOffset is in (-period, 0). After this
521 // operation, it will be in (0, period)
522 phaseOffset += period;
523 }
524 mPhaseOffset = phaseOffset;
525
526 // If we're not enabled, we don't need to mess with the listeners
527 if (!mEnabled) {
528 return;
529 }
530
Dan Stoza2713c302018-03-28 17:07:36 -0700531 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
532 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700534 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535 strerror(-err), err);
536 }
537 }
538
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539private:
540 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 callback = mCallback;
545
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546 if (mTraceVsync) {
547 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700548 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 }
551
Peiyong Lin566a3b42018-01-09 18:22:43 -0800552 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 callback->onVSyncEvent(when);
554 }
555 }
556
Tim Murray4a4e4a22016-04-19 16:29:23 +0000557 const char* const mName;
558
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559 int mValue;
560
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700561 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700562 const String8 mVsyncOnLabel;
563 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700564
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700566
567 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569
570 Mutex mVsyncMutex; // Protects the following
571 nsecs_t mPhaseOffset;
572 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573};
574
Lloyd Piquee83f9312018-02-01 12:53:17 -0800575class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700576public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 InjectVSyncSource() = default;
578 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700579
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700581 std::lock_guard<std::mutex> lock(mCallbackMutex);
582 mCallback = callback;
583 }
584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700586 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700587 if (mCallback) {
588 mCallback->onVSyncEvent(when);
589 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700590 }
591
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 void setVSyncEnabled(bool) override {}
593 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700594
595private:
596 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800597 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700598};
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Thierry Strudel2924d012017-08-14 15:19:37 -0700606 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800611 mEventThreadSource =
612 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
613 true, "app");
614 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
615 "appEventThread");
616 mSfEventThreadSource =
617 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
618 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800619
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800620 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
621 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800622 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700623 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800626 getBE().mRenderEngine =
627 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay
629 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
630 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800631 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632
633 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
634 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800635 getBE().mHwc.reset(
636 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700637 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800638 // Process any initial hotplug and resulting display changes.
639 processDisplayHotplugEventsLocked();
640 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
641 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800642
Lloyd Piquefcd86612017-12-14 17:15:36 -0800643 // make the default display GLContext current so that we can create textures
644 // when creating Layers (which may happens before we render something)
645 getDefaultDisplayDeviceLocked()->makeCurrent();
646
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (useVrFlinger) {
648 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 // This callback is called from the vr flinger dispatch thread. We
650 // need to call signalTransaction(), which requires holding
651 // mStateLock when we're not on the main thread. Acquiring
652 // mStateLock from the vr flinger dispatch thread might trigger a
653 // deadlock in surface flinger (see b/66916578), so post a message
654 // to be handled on the main thread instead.
655 sp<LambdaMessage> message = new LambdaMessage([=]() {
656 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
657 mVrFlingerRequestsDisplay = requestDisplay;
658 signalTransaction();
659 });
660 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 };
David Sodman105b7dc2017-11-04 20:28:14 -0700662 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
663 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800664 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (!mVrFlinger) {
666 ALOGE("Failed to start vrflinger");
667 }
668 }
669
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800670 mEventControlThread = std::make_unique<impl::EventControlThread>(
671 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700672
Mathias Agopian92a979a2012-08-02 18:32:23 -0700673 // initialize our drawing state
674 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700675
Andy McFadden13a082e2012-08-24 10:16:42 -0700676 // set initial conditions (e.g. unblank default device)
677 initializeDisplays();
678
David Sodmanbc815282017-11-05 18:57:52 -0800679 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700680
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 // Inform native graphics APIs whether the present timestamp is supported:
682 if (getHwComposer().hasCapability(
683 HWC2::Capability::PresentFenceIsNotReliable)) {
684 mStartPropertySetThread = new StartPropertySetThread(false);
685 } else {
686 mStartPropertySetThread = new StartPropertySetThread(true);
687 }
688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
700 mSaturation = atof(value);
701 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
704 mForceNativeColorMode = atoi(value) == 1;
705 if (mForceNativeColorMode) {
706 ALOGV("Forcing native color mode");
707 }
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
764 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500769 if (!display.get())
770 return NAME_NOT_FOUND;
771
Jesse Hall692c7232012-11-08 15:41:56 -0800772 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800774 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700782 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 // TODO: Not sure if display density should handled by SF any longer
785 class Density {
786 static int getDensityFromProperty(char const* propName) {
787 char property[PROPERTY_VALUE_MAX];
788 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800789 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700790 density = atoi(property);
791 }
792 return density;
793 }
794 public:
795 static int getEmuDensity() {
796 return getDensityFromProperty("qemu.sf.lcd_density"); }
797 static int getBuildDensity() {
798 return getDensityFromProperty("ro.sf.lcd_density"); }
799 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 DisplayInfo info = DisplayInfo();
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 float xdpi = hwConfig->getDpiX();
809 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810
811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800829 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 } else {
831 // TODO: where should this value come from?
832 static const int TV_DENSITY = 213;
833 info.density = TV_DENSITY / 160.0f;
834 info.orientation = 0;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 info.xdpi = xdpi;
840 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900842 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843
Andy McFadden91b2ca82014-06-13 14:04:23 -0700844 // This is how far in advance a buffer must be queued for
845 // presentation at a given time. If you want a buffer to appear
846 // on the screen at time N, you must submit the buffer before
847 // (N - presentationDeadline).
848 //
849 // Normally it's one full refresh period (to give SF a chance to
850 // latch the buffer), but this can be reduced by configuring a
851 // DispSync offset. Any additional delays introduced by the hardware
852 // composer or panel must be accounted for here.
853 //
854 // We add an additional 1ms to allow for processing time and
855 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800857 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 // All non-virtual displays are currently considered secure.
860 info.secure = true;
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800870 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
876 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
878 return NO_ERROR;
879}
880
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800882 if (display == nullptr) {
883 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800888 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700889 return device->getActiveConfig();
890 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891
Dan Stoza24a42e92015-03-09 10:04:11 -0700892 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
896 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
897 this);
898 int32_t type = hw->getDisplayType();
899 int currentMode = hw->getActiveConfig();
900
901 if (mode == currentMode) {
902 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
903 return;
904 }
905
906 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
907 ALOGW("Trying to set config for virtual display");
908 return;
909 }
910
911 hw->setActiveConfig(mode);
912 getHwComposer().setActiveConfig(type, mode);
913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
916 class MessageSetActiveConfig: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 int mMode;
920 public:
921 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 int mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700925 Vector<DisplayInfo> configs;
926 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700927 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700928 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700929 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700931 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700935 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
937 ALOGW("Attempt to set active config = %d for virtual display",
938 mMode);
939 } else {
940 mFlinger.setActiveConfigInternal(hw, mMode);
941 }
942 return true;
943 }
944 };
945 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
946 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700947 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700948}
Michael Wright28f24d02016-07-12 13:30:53 -0700949status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700950 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
952 return BAD_VALUE;
953 }
954
955 if (!display.get()) {
956 return NAME_NOT_FOUND;
957 }
958
959 int32_t type = NAME_NOT_FOUND;
960 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
961 if (display == mBuiltinDisplays[i]) {
962 type = i;
963 break;
964 }
965 }
966
967 if (type < 0) {
968 return type;
969 }
970
Peiyong Lina52f0292018-03-14 17:26:31 -0700971 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700972 {
973 ConditionalLock _l(mStateLock,
974 std::this_thread::get_id() != mMainThreadId);
975 modes = getHwComposer().getColorModes(type);
976 }
Michael Wright28f24d02016-07-12 13:30:53 -0700977 outColorModes->clear();
978 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
979
980 return NO_ERROR;
981}
982
Peiyong Lina52f0292018-03-14 17:26:31 -0700983ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700984 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700985 if (device != nullptr) {
986 return device->getActiveColorMode();
987 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700989}
990
991void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700993 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995
996 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return;
998 }
999
1000 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1001 ALOGW("Trying to set config for virtual display");
1002 return;
1003 }
1004
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1006 hw->getDisplayType());
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 hw->setActiveColorMode(mode);
Peiyong Lin0e7a7912018-04-05 14:36:36 -07001009 getHwComposer().setActiveColorMode(type, mode, RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001010}
1011
1012
1013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 class MessageSetActiveColorMode: public MessageBase {
1016 SurfaceFlinger& mFlinger;
1017 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001019 public:
1020 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001022 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1023 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 mFlinger.getDisplayColorModes(mDisplay, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001028 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1029 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return true;
1031 }
1032 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1033 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001034 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1035 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001036 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001037 ALOGW("Attempt to set active color mode %s %d for virtual display",
1038 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001039 } else {
1040 mFlinger.setActiveColorModeInternal(hw, mMode);
1041 }
1042 return true;
1043 }
1044 };
1045 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1046 postMessageSync(msg);
1047 return NO_ERROR;
1048}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049
Svetoslavd85084b2014-03-20 10:28:31 -07001050status_t SurfaceFlinger::clearAnimationFrameStats() {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.clearStats();
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1057 Mutex::Autolock _l(mStateLock);
1058 mAnimFrameTracker.getStats(outStats);
1059 return NO_ERROR;
1060}
1061
Dan Stozac4f471e2016-03-24 09:31:08 -07001062status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1063 HdrCapabilities* outCapabilities) const {
1064 Mutex::Autolock _l(mStateLock);
1065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 if (displayDevice == nullptr) {
1068 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1069 return BAD_VALUE;
1070 }
1071
1072 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001073 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001075 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1076 // insert HDR10 as we will force client composition for HDR10
1077 // layers
1078 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1079 types.push_back(HAL_HDR_HDR10);
1080
1081 *outCapabilities = HdrCapabilities(types,
1082 capabilities->getDesiredMaxLuminance(),
1083 capabilities->getDesiredMaxAverageLuminance(),
1084 capabilities->getDesiredMinLuminance());
1085 } else {
1086 *outCapabilities = std::move(*capabilities);
1087 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 } else {
1089 return BAD_VALUE;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
1103 if (enable) {
1104 ALOGV("VSync Injections enabled");
1105 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001106 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001107 mInjectorEventThread =
1108 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 });
1119 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 IPCThreadState* ipc = IPCThreadState::self();
1140 const int pid = ipc->getCallingPid();
1141 const int uid = ipc->getCallingUid();
1142 if ((uid != AID_SHELL) &&
1143 !PermissionCache::checkPermission(sDump, pid, uid)) {
1144 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1145 return PERMISSION_DENIED;
1146 }
1147
1148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
1169 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1170 return mSFEventThread->createEventConnection();
1171 } else {
1172 return mEventThread->createEventConnection();
1173 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001174}
1175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177
1178void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001179 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180}
1181
1182void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001183 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001187 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001191 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001192 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001197 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001201 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001202 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203 if (res == NO_ERROR) {
1204 msg->wait();
1205 }
1206 return res;
1207}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210 do {
1211 waitForEvent();
1212 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213}
1214
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215void SurfaceFlinger::enableHardwareVsync() {
1216 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1220 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 Mutex::Autolock _l(mHWVsyncLock);
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228 if (makeAvailable) {
1229 mHWVsyncAvailable = true;
1230 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 // Hardware vsync is not currently available, so abort the resync
1232 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 return;
1234 }
1235
David Sodman105b7dc2017-11-04 20:28:14 -07001236 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
1239 mPrimaryDispSync.reset();
1240 mPrimaryDispSync.setPeriod(period);
1241
1242 if (!mPrimaryHWVsyncEnabled) {
1243 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
1247 }
1248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1254 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.endResync();
1256 mPrimaryHWVsyncEnabled = false;
1257 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeUnavailable) {
1259 mHWVsyncAvailable = false;
1260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Tim Murray4a4e4a22016-04-19 16:29:23 +00001263void SurfaceFlinger::resyncWithRateLimit() {
1264 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001265
1266 // No explicit locking is needed here since EventThread holds a lock while calling this method
1267 static nsecs_t sLastResyncAttempted = 0;
1268 const nsecs_t now = systemTime();
1269 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271 }
Dan Stoza57164302017-05-08 14:03:54 -07001272 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273}
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1276 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001277 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001279 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 return;
1281 }
1282
1283 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001284 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001285 return;
1286 }
1287
Jamie Gennisd1700752013-10-14 12:22:52 -07001288 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 { // Scope for the lock
1291 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001295 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001296
1297 if (needsHwVsync) {
1298 enableHardwareVsync();
1299 } else {
1300 disableHardwareVsync(false);
1301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302}
1303
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001305 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1306 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001307}
1308
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1310 HWC2::Connection connection) {
1311 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1312 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 // Ignore events that do not have the right sequenceId.
1315 if (sequenceId != getBE().mComposerSequenceId) {
1316 return;
1317 }
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Only lock if we're not on the main thread. This function is normally
1320 // called on a hwbinder thread, but for the primary display it's called on
1321 // the main thread with the state lock already held, so don't attempt to
1322 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001326
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001327 if (std::this_thread::get_id() == mMainThreadId) {
1328 // Process all pending hot plug events immediately if we are on the main thread.
1329 processDisplayHotplugEventsLocked();
1330 }
1331
Lloyd Piqueba04e622017-12-14 17:11:26 -08001332 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::onRefreshReceived(int sequenceId,
1336 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001341 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001342}
1343
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001347 getHwComposer().setVsyncEnabled(disp,
1348 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001349}
1350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001352void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 // Clear the drawing state so that the logic inside of
1355 // handleTransactionLocked will fire. It will determine the delta between
1356 // mCurrentState and mDrawingState and re-apply all changes when we make the
1357 // transition.
1358 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001359 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 mDisplays.clear();
1361}
1362
Steven Thomas050b2c82017-03-06 11:45:16 -08001363void SurfaceFlinger::updateVrFlinger() {
1364 if (!mVrFlinger)
1365 return;
1366 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001368 return;
1369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 ALOGE("Vr flinger is only supported for remote hardware composer"
1373 " service connections. Ignoring request to transition to vr"
1374 " flinger.");
1375 mVrFlingerRequestsDisplay = false;
1376 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 int currentDisplayPowerMode = getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001390 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1391 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001392 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1395 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001396
1397 if (vrFlingerRequestsDisplay) {
1398 mVrFlinger->GrantDisplayOwnership();
1399 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
1403 mVisibleRegionsDirty = true;
1404 invalidateHwcGeometry();
1405
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001406 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1408 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1409 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001412 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 const nsecs_t period = activeConfig->getVsyncPeriod();
1414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Use phase of 0 since phase is not known.
1417 // Use latency of 0, which will snap to the ideal latency.
1418 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 android_atomic_or(1, &mRepaintEverything);
1421 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422}
1423
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001425 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001428 bool frameMissed = !mHadClientComposition &&
1429 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 (mPreviousPresentFence->getSignalTime() ==
1431 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001432 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001433 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001434 signalLayerUpdate();
1435 break;
1436 }
1437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473}
1474
1475void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001478 mRefreshPending = false;
1479
Pablo Ceballos40845df2016-01-25 17:41:15 -08001480 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001481
Brian Andersond6927fb2016-07-23 23:37:30 -07001482 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001483 rebuildLayerStacks();
1484 setUpHWComposer();
1485 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001486 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001487 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001488 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492
1493 mHadClientComposition = false;
1494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1495 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1496 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001497 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 }
Dan Stoza2713c302018-03-28 17:07:36 -07001499 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504void SurfaceFlinger::doDebugFlashRegions()
1505{
1506 // is debugging enabled
1507 if (CC_LIKELY(!mDebugRegion))
1508 return;
1509
1510 const bool repaintEverything = mRepaintEverything;
1511 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1512 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001513 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 // transform the dirty region into this screen's coordinate space
1515 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1516 if (!dirtyRegion.isEmpty()) {
1517 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001518 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519
1520 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001522 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001523 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1524
Mathias Agopianda27af92012-09-13 18:17:13 -07001525 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 }
1527 }
1528 }
1529
1530 postFramebuffer();
1531
1532 if (mDebugRegion > 1) {
1533 usleep(mDebugRegion * 1000);
1534 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001535
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001537 auto& displayDevice = mDisplays[displayId];
1538 if (!displayDevice->isDisplayOn()) {
1539 continue;
1540 }
1541
David Sodman105b7dc2017-11-04 20:28:14 -07001542 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1543 ALOGE_IF(result != NO_ERROR,
1544 "prepareFrame for display %zd failed:"
1545 " %d (%s)",
1546 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001547 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548}
1549
Adrian Roos1e1a1282017-11-01 19:05:31 +01001550void SurfaceFlinger::doTracing(const char* where) {
1551 ATRACE_CALL();
1552 ATRACE_NAME(where);
1553 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001554 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001555 }
1556}
1557
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001558void SurfaceFlinger::logLayerStats() {
1559 ATRACE_CALL();
1560 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1561 int32_t hwcId = -1;
1562 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1563 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1564 if (displayDevice->isPrimary()) {
1565 hwcId = displayDevice->getHwcDisplayId();
1566 break;
1567 }
1568 }
1569 if (hwcId < 0) {
1570 ALOGE("LayerStats: Hmmm, no primary display?");
1571 return;
1572 }
1573 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1574 }
1575}
1576
Brian Andersond6927fb2016-07-23 23:37:30 -07001577void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001579 ATRACE_CALL();
1580 ALOGV("preComposition");
1581
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001583 mDrawingState.traverseInZOrder([&](Layer* layer) {
1584 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585 needExtraInvalidate = true;
1586 }
Robert Carr2047fae2016-11-28 14:09:09 -08001587 });
1588
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 if (needExtraInvalidate) {
1590 signalLayerUpdate();
1591 }
1592}
1593
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594void SurfaceFlinger::updateCompositorTiming(
1595 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1596 std::shared_ptr<FenceTime>& presentFenceTime) {
1597 // Update queue of past composite+present times and determine the
1598 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001599 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001601 while (!getBE().mCompositePresentTimes.empty()) {
1602 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 // Cached values should have been updated before calling this method,
1604 // which helps avoid duplicate syscalls.
1605 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1606 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1607 break;
1608 }
1609 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001610 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 }
1612
1613 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001614 while (getBE().mCompositePresentTimes.size() > 16) {
1615 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616 }
1617
Brian Andersond0010582017-03-07 13:20:31 -08001618 setCompositorTimingSnapped(
1619 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1620}
1621
1622void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1623 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 // Integer division and modulo round toward 0 not -inf, so we need to
1625 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001626 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1628 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1629
Brian Andersond0010582017-03-07 13:20:31 -08001630 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1631 if (idealLatency <= 0) {
1632 idealLatency = vsyncInterval;
1633 }
1634
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635 // Snap the latency to a value that removes scheduling jitter from the
1636 // composition and present times, which often have >1ms of jitter.
1637 // Reducing jitter is important if an app attempts to extrapolate
1638 // something (such as user input) to an accurate diasplay time.
1639 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1640 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001641 nsecs_t bias = vsyncInterval / 2;
1642 int64_t extraVsyncs =
1643 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1644 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1645 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646
David Sodman99974d22017-11-28 12:04:33 -08001647 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1648 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1649 getBE().mCompositorTiming.interval = vsyncInterval;
1650 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651}
1652
1653void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001654{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 ATRACE_CALL();
1656 ALOGV("postComposition");
1657
Brian Anderson3546a3f2016-07-14 11:51:14 -07001658 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001659 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001661 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001662 }
1663
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664 // |mStateLock| not needed as we are on the main thread
1665 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001666
David Sodman73beded2017-11-15 11:56:06 -08001667 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001669 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001670 glCompositionDoneFenceTime =
1671 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001672 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 } else {
1674 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1675 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676
David Sodman73beded2017-11-15 11:56:06 -08001677 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001678 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001679 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001680 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1683 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1684
1685 // We use the refreshStartTime which might be sampled a little later than
1686 // when we started doing work for this frame, but that should be okay
1687 // since updateCompositorTiming has snapping logic.
1688 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001689 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001690 CompositorTiming compositorTiming;
1691 {
David Sodman99974d22017-11-28 12:04:33 -08001692 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1693 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001694 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695
Robert Carr2047fae2016-11-28 14:09:09 -08001696 mDrawingState.traverseInZOrder([&](Layer* layer) {
1697 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001698 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001699 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001700 recordBufferingStats(layer->getName().string(),
1701 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001702 }
Robert Carr2047fae2016-11-28 14:09:09 -08001703 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001704
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001705 if (presentFenceTime->isValid()) {
1706 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001707 enableHardwareVsync();
1708 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001709 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001710 }
1711 }
1712
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001713 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001714 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001715 enableHardwareVsync();
1716 }
1717 }
1718
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001719 if (mAnimCompositionPending) {
1720 mAnimCompositionPending = false;
1721
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001725 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001726 // The HWC doesn't support present fences, so use the refresh
1727 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001729 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730 mAnimFrameTracker.setActualPresentTime(presentTime);
1731 }
1732 mAnimFrameTracker.advanceFrame();
1733 }
Dan Stozab90cf072015-03-05 11:05:59 -08001734
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001735 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1736 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001737 return;
1738 }
1739
1740 nsecs_t currentTime = systemTime();
1741 if (mHasPoweredOff) {
1742 mHasPoweredOff = false;
1743 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001744 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001746 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1747 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001748 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001749 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001750 }
David Sodman4a36e932017-11-07 14:29:47 -08001751 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001752 }
David Sodman4a36e932017-11-07 14:29:47 -08001753 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754}
1755
1756void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 ATRACE_CALL();
1758 ALOGV("rebuildLayerStacks");
1759
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001761 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001762 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001763 mVisibleRegionsDirty = false;
1764 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001765
Jeff Sharkey76488112017-02-27 14:15:18 -07001766 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1767 Region opaqueRegion;
1768 Region dirtyRegion;
1769 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001770 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001771 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1772 const Transform& tr(displayDevice->getTransform());
1773 const Rect bounds(displayDevice->getBounds());
1774 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001775 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001776
Jeff Sharkey76488112017-02-27 14:15:18 -07001777 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001778 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001779 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1780 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 Region drawRegion(tr.transform(
1782 layer->visibleNonTransparentRegion));
1783 drawRegion.andSelf(bounds);
1784 if (!drawRegion.isEmpty()) {
1785 layersSortedByZ.add(layer);
1786 } else {
1787 // Clear out the HWC layer if this layer was
1788 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001789 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001790 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001791 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001792 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001793 // WM changes displayDevice->layerStack upon sleep/awake.
1794 // Here we make sure we delete the HWC layers even if
1795 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001796 hwcLayerDestroyed = layer->destroyHwcLayer(
1797 displayDevice->getHwcDisplayId());
1798 }
1799
1800 // If a layer is not going to get a release fence because
1801 // it is invisible, but it is also going to release its
1802 // old buffer, add it to the list of layers needing
1803 // fences.
1804 if (hwcLayerDestroyed) {
1805 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1806 mLayersWithQueuedFrames.cend(), layer);
1807 if (found != mLayersWithQueuedFrames.cend()) {
1808 layersNeedingFences.add(layer);
1809 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001810 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 });
1812 }
1813 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001814 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 displayDevice->undefinedRegion.set(bounds);
1816 displayDevice->undefinedRegion.subtractSelf(
1817 tr.transform(opaqueRegion));
1818 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001822
Romain Guy0147a172017-06-01 13:53:56 -07001823mat4 SurfaceFlinger::computeSaturationMatrix() const {
1824 if (mSaturation == 1.0f) {
1825 return mat4();
1826 }
1827
1828 // Rec.709 luma coefficients
1829 float3 luminance{0.213f, 0.715f, 0.072f};
1830 luminance *= 1.0f - mSaturation;
1831 return mat4(
1832 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1833 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1834 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1835 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1836 );
1837}
1838
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001839// pickColorMode translates a given dataspace into the best available color mode.
1840// Currently only support sRGB and Display-P3.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001841ColorMode SurfaceFlinger::pickColorMode(Dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001842 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001843 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001844 }
1845
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001846 switch (dataSpace) {
1847 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1848 // system expects.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001849 case Dataspace::UNKNOWN:
1850 case Dataspace::SRGB:
1851 case Dataspace::V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001852 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853 break;
1854
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001855 case Dataspace::DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001856 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001857 break;
1858
1859 default:
1860 // TODO (courtneygo): Do we want to assert an error here?
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001861 ALOGE("No color mode mapping for %s (%#x)",
1862 dataspaceDetails(static_cast<android_dataspace>(dataSpace)).c_str(),
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001863 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001864 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001865 break;
1866 }
1867}
1868
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001869Dataspace SurfaceFlinger::bestTargetDataSpace(
1870 Dataspace a, Dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001871 // Only support sRGB and Display-P3 right now.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001872 if (a == Dataspace::DISPLAY_P3 || b == Dataspace::DISPLAY_P3) {
1873 return Dataspace::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001874 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001875 if (a == Dataspace::V0_SCRGB_LINEAR || b == Dataspace::V0_SCRGB_LINEAR) {
1876 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001877 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001878 if (a == Dataspace::V0_SCRGB || b == Dataspace::V0_SCRGB) {
1879 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001880 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001881 if (!hasHdr) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001882 if (a == Dataspace::BT2020_PQ || b == Dataspace::BT2020_PQ) {
1883 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001884 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001885 if (a == Dataspace::BT2020_ITU_PQ || b == Dataspace::BT2020_ITU_PQ) {
1886 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001887 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001888 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001889
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001890 return Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001891}
1892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ATRACE_CALL();
1895 ALOGV("setUpHWComposer");
1896
Jesse Hall028dc8f2013-08-20 16:35:32 -07001897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001898 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1899 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1900 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1901
1902 // If nothing has changed (!dirty), don't recompose.
1903 // If something changed, but we don't currently have any visible layers,
1904 // and didn't when we last did a composition, then skip it this time.
1905 // The second rule does two things:
1906 // - When all layers are removed from a display, we'll emit one black
1907 // frame, then nothing more until we get new layers.
1908 // - When a display is created with a private layer stack, we won't
1909 // emit any black frames until a layer is added to the layer stack.
1910 bool mustRecompose = dirty && !(empty && wasEmpty);
1911
1912 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1913 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1914 mustRecompose ? "doing" : "skipping",
1915 dirty ? "+" : "-",
1916 empty ? "+" : "-",
1917 wasEmpty ? "+" : "-");
1918
Dan Stoza71433162014-02-04 16:22:36 -08001919 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001920
1921 if (mustRecompose) {
1922 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1923 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001924 }
1925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 // build the h/w work list
1927 if (CC_UNLIKELY(mGeometryInvalid)) {
1928 mGeometryInvalid = false;
1929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1930 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1931 const auto hwcId = displayDevice->getHwcDisplayId();
1932 if (hwcId >= 0) {
1933 const Vector<sp<Layer>>& currentLayers(
1934 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001935 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001938 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001941 }
1942 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001943
Robert Carrae060832016-11-28 10:51:00 -08001944 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001945 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001947 }
1948 }
1949 }
1950 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 }
Riley Andrews03414a12014-07-01 14:22:59 -07001952
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001953
Romain Guy0147a172017-06-01 13:53:56 -07001954 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 // Set the per-frame data
1957 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1958 auto& displayDevice = mDisplays[displayId];
1959 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 if (hwcId < 0) {
1962 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001963 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001964 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08001965 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07001966 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001967 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1968 "display %zd: %d", displayId, result);
1969 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001971 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1972 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001973 !displayDevice->getHdrSupport()) {
1974 layer->forceClientComposition(hwcId);
1975 }
1976
chaviwc9232ed2017-11-14 15:31:15 -08001977 if (layer->getForceClientComposition(hwcId)) {
1978 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1979 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1980 continue;
1981 }
1982
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 layer->setPerFrameData(displayDevice);
1984 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001985
1986 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001987 ColorMode newColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001988 Dataspace newDataSpace = Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001989
1990 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001991 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1992 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001993 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001994 layer->getName().string(), dataspaceDetails(static_cast<android_dataspace>(layer->getDataSpace())).c_str(),
1995 layer->getDataSpace(), dataspaceDetails(static_cast<android_dataspace>(newDataSpace)).c_str(), newDataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001996 }
1997 newColorMode = pickColorMode(newDataSpace);
1998
Thierry Strudel2924d012017-08-14 15:19:37 -07001999 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002000 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 }
2002
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002003 mPreviousColorMatrix = colorMatrix;
2004
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002006 auto& displayDevice = mDisplays[displayId];
2007 if (!displayDevice->isDisplayOn()) {
2008 continue;
2009 }
2010
David Sodman105b7dc2017-11-04 20:28:14 -07002011 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2013 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017void SurfaceFlinger::doComposition() {
2018 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 ALOGV("doComposition");
2020
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002021 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002023 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002024 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 // transform the dirty region into this screen's coordinate space
2026 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002027
2028 // repaint the framebuffer (if needed)
2029 doDisplayComposition(hw, dirtyRegion);
2030
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002032 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002033 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002034 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002035 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036}
2037
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038void SurfaceFlinger::postFramebuffer()
2039{
Mathias Agopian841cde52012-03-01 15:44:37 -08002040 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002042
Mathias Agopiana44b0412011-10-16 18:46:35 -07002043 const nsecs_t now = systemTime();
2044 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002045
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2047 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002048 if (!displayDevice->isDisplayOn()) {
2049 continue;
2050 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 const auto hwcId = displayDevice->getHwcDisplayId();
2052 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002053 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002054 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002055 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002056 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002058 // The layer buffer from the previous frame (if any) is released
2059 // by HWC only when the release fence from this frame (if any) is
2060 // signaled. Always get the release fence from HWC first.
2061 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002062 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
2064 // If the layer was client composited in the previous frame, we
2065 // need to merge with the previous client target acquire fence.
2066 // Since we do not track that, always merge with the current
2067 // client target acquire fence when it is available, even though
2068 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002070 releaseFence = Fence::merge("LayerRelease", releaseFence,
2071 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002073
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 layer->onLayerDisplayed(releaseFence);
2075 }
Chia-I Wu83806892017-11-16 10:50:20 -08002076
2077 // We've got a list of layers needing fences, that are disjoint with
2078 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2079 // supply them with the present fence.
2080 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002081 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002082 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2083 layer->onLayerDisplayed(presentFence);
2084 }
2085 }
2086
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002088 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002089 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002090 }
2091
Mathias Agopiana44b0412011-10-16 18:46:35 -07002092 mLastSwapBufferTime = systemTime() - now;
2093 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002094
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002095 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002096 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2097 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2098 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2099 logFrameStats();
2100 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102}
2103
Mathias Agopian87baae12012-07-31 12:38:26 -07002104void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105{
Mathias Agopian841cde52012-03-01 15:44:37 -08002106 ATRACE_CALL();
2107
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002108 // here we keep a copy of the drawing state (that is the state that's
2109 // going to be overwritten by handleTransactionLocked()) outside of
2110 // mStateLock so that the side-effects of the State assignment
2111 // don't happen with mStateLock held (which can cause deadlocks).
2112 State drawingState(mDrawingState);
2113
Mathias Agopianca4d3602011-05-19 15:38:14 -07002114 Mutex::Autolock _l(mStateLock);
2115 const nsecs_t now = systemTime();
2116 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 // Here we're guaranteed that some transaction flags are set
2119 // so we can call handleTransactionLocked() unconditionally.
2120 // We call getTransactionFlags(), which will also clear the flags,
2121 // with mStateLock held to guarantee that mCurrentState won't change
2122 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002123
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002124 mVsyncModulator.onTransactionHandled();
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) {
Dan Stoza2713c302018-03-28 17:07:36 -07003073 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3074}
3075
3076uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3077 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003079 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003081 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 }
3083 return old;
3084}
3085
chaviwca27f252018-02-06 16:46:39 -08003086bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3087 for (const ComposerState& state : states) {
3088 // Here we need to check that the interface we're given is indeed
3089 // one of our own. A malicious client could give us a nullptr
3090 // IInterface, or one of its own or even one of our own but a
3091 // different type. All these situations would cause us to crash.
3092 if (state.client == nullptr) {
3093 return true;
3094 }
3095
3096 sp<IBinder> binder = IInterface::asBinder(state.client);
3097 if (binder == nullptr) {
3098 return true;
3099 }
3100
3101 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3102 return true;
3103 }
3104 }
3105 return false;
3106}
3107
Mathias Agopian8b33f032012-07-24 20:43:54 -07003108void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003109 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003110 const Vector<DisplayState>& displays,
3111 uint32_t flags)
3112{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003113 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003114 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003115 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003116
chaviwca27f252018-02-06 16:46:39 -08003117 if (containsAnyInvalidClientState(states)) {
3118 return;
3119 }
3120
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003121 if (flags & eAnimation) {
3122 // For window updates that are part of an animation we must wait for
3123 // previous animation "frames" to be handled.
3124 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003125 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003126 if (CC_UNLIKELY(err != NO_ERROR)) {
3127 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003128 // caller after a few seconds.
3129 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3130 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003131 mAnimTransactionPending = false;
3132 break;
3133 }
3134 }
3135 }
3136
chaviwca27f252018-02-06 16:46:39 -08003137 for (const DisplayState& display : displays) {
3138 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003139 }
3140
chaviwca27f252018-02-06 16:46:39 -08003141 for (const ComposerState& state : states) {
3142 transactionFlags |= setClientStateLocked(state);
3143 }
3144
3145 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3146 // as destroyed should only occur after setting all other states. This is to allow for a
3147 // child re-parent to happen before marking its original parent as destroyed (which would
3148 // then mark the child as destroyed).
3149 for (const ComposerState& state : states) {
3150 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003151 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003152
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003153 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3154 // anyway. This can be used as a flush mechanism for previous async transactions.
3155 // Empty animation transaction can be used to simulate back-pressure, so also force a
3156 // transaction for empty animation transactions.
3157 if (transactionFlags == 0 &&
3158 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003159 transactionFlags = eTransactionNeeded;
3160 }
3161
Mathias Agopian386aa982011-11-07 21:58:03 -08003162 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003163 if (mInterceptor->isEnabled()) {
3164 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003165 }
Irvel468051e2016-06-13 16:44:44 -07003166
Mathias Agopian386aa982011-11-07 21:58:03 -08003167 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003168 const auto start = (flags & eEarlyWakeup)
3169 ? VSyncModulator::TransactionStart::EARLY
3170 : VSyncModulator::TransactionStart::NORMAL;
3171 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003172
3173 // if this is a synchronous transaction, wait for it to take effect
3174 // before returning.
3175 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003176 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003177 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003178 if (flags & eAnimation) {
3179 mAnimTransactionPending = true;
3180 }
3181 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003182 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3183 if (CC_UNLIKELY(err != NO_ERROR)) {
3184 // just in case something goes wrong in SF, return to the
3185 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003186 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3187 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003188 break;
3189 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 }
3192}
3193
Mathias Agopiane57f2922012-08-09 16:29:12 -07003194uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3195{
Jesse Hall9a143922012-10-04 16:29:19 -07003196 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3197 if (dpyIdx < 0)
3198 return 0;
3199
Mathias Agopiane57f2922012-08-09 16:29:12 -07003200 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003201 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003202 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203 const uint32_t what = s.what;
3204 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003205 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003206 disp.surface = s.surface;
3207 flags |= eDisplayTransactionNeeded;
3208 }
3209 }
3210 if (what & DisplayState::eLayerStackChanged) {
3211 if (disp.layerStack != s.layerStack) {
3212 disp.layerStack = s.layerStack;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003216 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217 if (disp.orientation != s.orientation) {
3218 disp.orientation = s.orientation;
3219 flags |= eDisplayTransactionNeeded;
3220 }
3221 if (disp.frame != s.frame) {
3222 disp.frame = s.frame;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (disp.viewport != s.viewport) {
3226 disp.viewport = s.viewport;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
Michael Lentine47e45402014-07-18 15:34:25 -07003230 if (what & DisplayState::eDisplaySizeChanged) {
3231 if (disp.width != s.width) {
3232 disp.width = s.width;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (disp.height != s.height) {
3236 disp.height = s.height;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003240 }
3241 return flags;
3242}
3243
chaviwca27f252018-02-06 16:46:39 -08003244uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3245 const layer_state_t& s = composerState.state;
3246 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3247
Mathias Agopian13127d82013-03-05 17:47:11 -08003248 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003249 if (layer == nullptr) {
3250 return 0;
3251 }
3252
3253 if (layer->isPendingRemoval()) {
3254 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3255 return 0;
3256 }
3257
3258 uint32_t flags = 0;
3259
3260 const uint32_t what = s.what;
3261 bool geometryAppliesWithResize =
3262 what & layer_state_t::eGeometryAppliesWithResize;
3263 if (what & layer_state_t::ePositionChanged) {
3264 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3265 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 }
3268 if (what & layer_state_t::eLayerChanged) {
3269 // NOTE: index needs to be calculated before we update the state
3270 const auto& p = layer->getParent();
3271 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003272 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003273 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003274 mCurrentState.layersSortedByZ.removeAt(idx);
3275 mCurrentState.layersSortedByZ.add(layer);
3276 // we need traversal (state changed)
3277 // AND transaction (list changed)
3278 flags |= eTransactionNeeded|eTraversalNeeded;
3279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 } else {
3281 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003282 flags |= eTransactionNeeded|eTraversalNeeded;
3283 }
3284 }
chaviw8b3871a2017-11-01 17:41:01 -07003285 }
3286 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003287 // NOTE: index needs to be calculated before we update the state
3288 const auto& p = layer->getParent();
3289 if (p == nullptr) {
3290 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3291 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3292 mCurrentState.layersSortedByZ.removeAt(idx);
3293 mCurrentState.layersSortedByZ.add(layer);
3294 // we need traversal (state changed)
3295 // AND transaction (list changed)
3296 flags |= eTransactionNeeded|eTraversalNeeded;
3297 }
3298 } else {
3299 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3300 flags |= eTransactionNeeded|eTraversalNeeded;
3301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 }
3303 }
3304 if (what & layer_state_t::eSizeChanged) {
3305 if (layer->setSize(s.w, s.h)) {
3306 flags |= eTraversalNeeded;
3307 }
3308 }
3309 if (what & layer_state_t::eAlphaChanged) {
3310 if (layer->setAlpha(s.alpha))
3311 flags |= eTraversalNeeded;
3312 }
3313 if (what & layer_state_t::eColorChanged) {
3314 if (layer->setColor(s.color))
3315 flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eMatrixChanged) {
3318 if (layer->setMatrix(s.matrix))
3319 flags |= eTraversalNeeded;
3320 }
3321 if (what & layer_state_t::eTransparentRegionChanged) {
3322 if (layer->setTransparentRegionHint(s.transparentRegion))
3323 flags |= eTraversalNeeded;
3324 }
3325 if (what & layer_state_t::eFlagsChanged) {
3326 if (layer->setFlags(s.flags, s.mask))
3327 flags |= eTraversalNeeded;
3328 }
3329 if (what & layer_state_t::eCropChanged) {
3330 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3331 flags |= eTraversalNeeded;
3332 }
3333 if (what & layer_state_t::eFinalCropChanged) {
3334 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3335 flags |= eTraversalNeeded;
3336 }
3337 if (what & layer_state_t::eLayerStackChanged) {
3338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3339 // We only allow setting layer stacks for top level layers,
3340 // everything else inherits layer stack from its parent.
3341 if (layer->hasParent()) {
3342 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3343 layer->getName().string());
3344 } else if (idx < 0) {
3345 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3346 "that also does not appear in the top level layer list. Something"
3347 " has gone wrong.", layer->getName().string());
3348 } else if (layer->setLayerStack(s.layerStack)) {
3349 mCurrentState.layersSortedByZ.removeAt(idx);
3350 mCurrentState.layersSortedByZ.add(layer);
3351 // we need traversal (state changed)
3352 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003353 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003354 }
3355 }
3356 if (what & layer_state_t::eDeferTransaction) {
3357 if (s.barrierHandle != nullptr) {
3358 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3359 } else if (s.barrierGbp != nullptr) {
3360 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3361 if (authenticateSurfaceTextureLocked(gbp)) {
3362 const auto& otherLayer =
3363 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3364 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3365 } else {
3366 ALOGE("Attempt to defer transaction to to an"
3367 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003368 }
3369 }
chaviw8b3871a2017-11-01 17:41:01 -07003370 // We don't trigger a traversal here because if no other state is
3371 // changed, we don't want this to cause any more work
3372 }
3373 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003374 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003375 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003376 if (!hadParent) {
3377 mCurrentState.layersSortedByZ.remove(layer);
3378 }
chaviw8b3871a2017-11-01 17:41:01 -07003379 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003380 }
chaviw8b3871a2017-11-01 17:41:01 -07003381 }
3382 if (what & layer_state_t::eReparentChildren) {
3383 if (layer->reparentChildren(s.reparentHandle)) {
3384 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003385 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003386 }
chaviw8b3871a2017-11-01 17:41:01 -07003387 if (what & layer_state_t::eDetachChildren) {
3388 layer->detachChildren();
3389 }
3390 if (what & layer_state_t::eOverrideScalingModeChanged) {
3391 layer->setOverrideScalingMode(s.overrideScalingMode);
3392 // We don't trigger a traversal here because if no other state is
3393 // changed, we don't want this to cause any more work
3394 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395 return flags;
3396}
3397
chaviwca27f252018-02-06 16:46:39 -08003398void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3399 const layer_state_t& state = composerState.state;
3400 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3401
3402 sp<Layer> layer(client->getLayerUser(state.surface));
3403 if (layer == nullptr) {
3404 return;
3405 }
3406
3407 if (layer->isPendingRemoval()) {
3408 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3409 return;
3410 }
3411
3412 if (state.what & layer_state_t::eDestroySurface) {
3413 removeLayerLocked(mStateLock, layer);
3414 }
3415}
3416
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003418 const String8& name,
3419 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003420 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003421 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003422 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003424 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003425 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003426 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003427 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003428 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003429
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003430 status_t result = NO_ERROR;
3431
3432 sp<Layer> layer;
3433
Cody Northropbc755282017-03-31 12:00:08 -06003434 String8 uniqueName = getUniqueLayerName(name);
3435
Mathias Agopian3165cc22012-08-08 19:42:09 -07003436 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3437 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003438 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003439 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003440 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003441
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442 break;
chaviw13fdc492017-06-27 12:40:18 -07003443 case ISurfaceComposerClient::eFXSurfaceColor:
3444 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003445 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003446 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003447 break;
3448 default:
3449 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450 break;
3451 }
3452
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 if (result != NO_ERROR) {
3454 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003456
Chia-I Wuab0c3192017-08-01 11:29:00 -07003457 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3458 // TODO b/64227542
3459 if (windowType == 441731) {
3460 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3461 layer->setPrimaryDisplayOnly();
3462 }
3463
Albert Chaulk479c60c2017-01-27 14:21:34 -05003464 layer->setInfo(windowType, ownerUid);
3465
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 if (result != NO_ERROR) {
3468 return result;
3469 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003470 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003471
3472 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003473 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003474}
3475
Cody Northropbc755282017-03-31 12:00:08 -06003476String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3477{
3478 bool matchFound = true;
3479 uint32_t dupeCounter = 0;
3480
3481 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3482 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3483
3484 // Loop over layers until we're sure there is no matching name
3485 while (matchFound) {
3486 matchFound = false;
3487 mDrawingState.traverseInZOrder([&](Layer* layer) {
3488 if (layer->getName() == uniqueName) {
3489 matchFound = true;
3490 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3491 }
3492 });
3493 }
3494
3495 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3496
3497 return uniqueName;
3498}
3499
David Sodman0c69cad2017-08-21 12:12:51 -07003500status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003501 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3502 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503{
3504 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003505 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 case PIXEL_FORMAT_TRANSPARENT:
3507 case PIXEL_FORMAT_TRANSLUCENT:
3508 format = PIXEL_FORMAT_RGBA_8888;
3509 break;
3510 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003511 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 break;
3513 }
3514
David Sodman0c69cad2017-08-21 12:12:51 -07003515 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3516 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003518 *handle = layer->getHandle();
3519 *gbp = layer->getProducer();
3520 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522
David Sodman0c69cad2017-08-21 12:12:51 -07003523 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003524 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525}
3526
chaviw13fdc492017-06-27 12:40:18 -07003527status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003528 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003529 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530{
chaviw13fdc492017-06-27 12:40:18 -07003531 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003533 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003534}
3535
Mathias Agopianac9fa422013-02-11 16:40:36 -08003536status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537{
Robert Carr9524cb32017-02-13 11:32:32 -08003538 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003539 status_t err = NO_ERROR;
3540 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003541 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003542 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003543 err = removeLayer(l);
3544 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3545 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003546 }
3547 return err;
3548}
3549
Mathias Agopian13127d82013-03-05 17:47:11 -08003550status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003551{
Mathias Agopian67106042013-03-14 19:18:13 -07003552 // called by ~LayerCleaner() when all references to the IBinder (handle)
3553 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003554 sp<Layer> l = layer.promote();
3555 if (l == nullptr) {
3556 // The layer has already been removed, carry on
3557 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003558 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003559 // If we have a parent, then we can continue to live as long as it does.
3560 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561}
3562
Mathias Agopianb60314a2012-04-10 22:09:54 -07003563// ---------------------------------------------------------------------------
3564
Andy McFadden13a082e2012-08-24 10:16:42 -07003565void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003566 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003567 Vector<ComposerState> state;
3568 Vector<DisplayState> displays;
3569 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003570 d.what = DisplayState::eDisplayProjectionChanged |
3571 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003572 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003573 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003574 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003575 d.frame.makeInvalid();
3576 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003577 d.width = 0;
3578 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003579 displays.add(d);
3580 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003581 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3582 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003583
David Sodman105b7dc2017-11-04 20:28:14 -07003584 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003585 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003586 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003587
Brian Andersond0010582017-03-07 13:20:31 -08003588 // Use phase of 0 since phase is not known.
3589 // Use latency of 0, which will snap to the ideal latency.
3590 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003591}
3592
3593void SurfaceFlinger::initializeDisplays() {
3594 class MessageScreenInitialized : public MessageBase {
3595 SurfaceFlinger* flinger;
3596 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003597 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003598 virtual bool handler() {
3599 flinger->onInitializeDisplays();
3600 return true;
3601 }
3602 };
3603 sp<MessageBase> msg = new MessageScreenInitialized(this);
3604 postMessageAsync(msg); // we may be called from main thread, use async message
3605}
3606
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003607void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003608 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003609 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3610 this);
3611 int32_t type = hw->getDisplayType();
3612 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003613
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003614 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003615 return;
3616 }
3617
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003618 hw->setPowerMode(mode);
3619 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3620 ALOGW("Trying to set power mode for virtual display");
3621 return;
3622 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003623
Lloyd Pique4d234852018-01-22 17:21:36 -08003624 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003625 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003626 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3627 if (idx < 0) {
3628 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3629 return;
3630 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003631 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003632 }
3633
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003634 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003635 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003636 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003637 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3638 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003639 // FIXME: eventthread only knows about the main display right now
3640 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003641 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003644 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003645 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003646 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003647
3648 struct sched_param param = {0};
3649 param.sched_priority = 1;
3650 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3651 ALOGW("Couldn't set SCHED_FIFO on display on");
3652 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003653 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003654 // Turn off the display
3655 struct sched_param param = {0};
3656 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3657 ALOGW("Couldn't set SCHED_OTHER on display off");
3658 }
3659
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003660 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3661 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003662 disableHardwareVsync(true); // also cancels any in-progress resync
3663
Mathias Agopiancde87a32012-09-13 14:09:01 -07003664 // FIXME: eventthread only knows about the main display right now
3665 mEventThread->onScreenReleased();
3666 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003667
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003668 getHwComposer().setPowerMode(type, mode);
3669 mVisibleRegionsDirty = true;
3670 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003671 } else if (mode == HWC_POWER_MODE_DOZE ||
3672 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003673 // Update display while dozing
3674 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003675 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3676 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003677 // FIXME: eventthread only knows about the main display right now
3678 mEventThread->onScreenAcquired();
3679 resyncToHardwareVsync(true);
3680 }
3681 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3682 // Leave display going to doze
3683 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3684 disableHardwareVsync(true); // also cancels any in-progress resync
3685 // FIXME: eventthread only knows about the main display right now
3686 mEventThread->onScreenReleased();
3687 }
3688 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003690 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003692 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003693 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003694}
3695
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3697 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003698 SurfaceFlinger& mFlinger;
3699 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003700 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003701 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 MessageSetPowerMode(SurfaceFlinger& flinger,
3703 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3704 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003707 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003708 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003709 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003710 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 ALOGW("Attempt to set power mode = %d for virtual display",
3712 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003713 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003714 mFlinger.setPowerModeInternal(
3715 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003716 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003717 return true;
3718 }
3719 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003721 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003722}
3723
3724// ---------------------------------------------------------------------------
3725
Lloyd Pique755e3192018-01-31 16:46:15 -08003726status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3727 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003729
Mathias Agopianbd115332013-04-18 16:41:04 -07003730 IPCThreadState* ipc = IPCThreadState::self();
3731 const int pid = ipc->getCallingPid();
3732 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003733
Mathias Agopianbd115332013-04-18 16:41:04 -07003734 if ((uid != AID_SHELL) &&
3735 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003736 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003737 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003739 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003740 // (this would indicate SF is stuck, but we want to be able to
3741 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003742 status_t err = mStateLock.timedLock(s2ns(1));
3743 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003744 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003745 result.appendFormat(
3746 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3747 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003748 }
3749
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003750 bool dumpAll = true;
3751 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003752 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003753
3754 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003755 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003756 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3757 dumpAll = false;
3758 }
3759
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003760 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003761 if ((index < numArgs) &&
3762 (args[index] == String16("--list"))) {
3763 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003764 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003765 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003766 }
3767
3768 if ((index < numArgs) &&
3769 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003771 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003772 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003773 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003774
3775 if ((index < numArgs) &&
3776 (args[index] == String16("--latency-clear"))) {
3777 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003778 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003779 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003780 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003781
3782 if ((index < numArgs) &&
3783 (args[index] == String16("--dispsync"))) {
3784 index++;
3785 mPrimaryDispSync.dump(result);
3786 dumpAll = false;
3787 }
Dan Stozab90cf072015-03-05 11:05:59 -08003788
3789 if ((index < numArgs) &&
3790 (args[index] == String16("--static-screen"))) {
3791 index++;
3792 dumpStaticScreenStats(result);
3793 dumpAll = false;
3794 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003795
3796 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003797 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003798 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003799 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003800 dumpAll = false;
3801 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003802
3803 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3804 index++;
3805 dumpWideColorInfo(result);
3806 dumpAll = false;
3807 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003808
3809 if ((index < numArgs) &&
3810 (args[index] == String16("--enable-layer-stats"))) {
3811 index++;
3812 mLayerStats.enable();
3813 dumpAll = false;
3814 }
3815
3816 if ((index < numArgs) &&
3817 (args[index] == String16("--disable-layer-stats"))) {
3818 index++;
3819 mLayerStats.disable();
3820 dumpAll = false;
3821 }
3822
3823 if ((index < numArgs) &&
3824 (args[index] == String16("--clear-layer-stats"))) {
3825 index++;
3826 mLayerStats.clear();
3827 dumpAll = false;
3828 }
3829
3830 if ((index < numArgs) &&
3831 (args[index] == String16("--dump-layer-stats"))) {
3832 index++;
3833 mLayerStats.dump(result);
3834 dumpAll = false;
3835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003837
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003838 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003839 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003840 }
3841
Mathias Agopian9795c422009-08-26 16:36:26 -07003842 if (locked) {
3843 mStateLock.unlock();
3844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 }
3846 write(fd, result.string(), result.size());
3847 return NO_ERROR;
3848}
3849
Dan Stozac7014012014-02-14 15:03:43 -08003850void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3851 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003852{
Robert Carr2047fae2016-11-28 14:09:09 -08003853 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003855 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856}
3857
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003858void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003859 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003860{
3861 String8 name;
3862 if (index < args.size()) {
3863 name = String8(args[index]);
3864 index++;
3865 }
3866
David Sodman105b7dc2017-11-04 20:28:14 -07003867 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003868 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003869 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003870
3871 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003872 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003873 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003874 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003875 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003876 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003877 }
Robert Carr2047fae2016-11-28 14:09:09 -08003878 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003879 }
3880}
3881
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003882void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003883 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003884{
3885 String8 name;
3886 if (index < args.size()) {
3887 name = String8(args[index]);
3888 index++;
3889 }
3890
Robert Carr2047fae2016-11-28 14:09:09 -08003891 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003892 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003893 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003894 }
Robert Carr2047fae2016-11-28 14:09:09 -08003895 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003896
Svetoslavd85084b2014-03-20 10:28:31 -07003897 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003898}
3899
Jamie Gennis6547ff42013-07-16 20:12:42 -07003900// This should only be called from the main thread. Otherwise it would need
3901// the lock and should use mCurrentState rather than mDrawingState.
3902void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003903 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003904 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003905 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003906
3907 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3908}
3909
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003910void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003911{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003912 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003913
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003914 if (isLayerTripleBufferingDisabled())
3915 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003916
3917 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003918 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003919 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003920 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003921 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3922 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003923 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003924}
3925
Dan Stozab90cf072015-03-05 11:05:59 -08003926void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3927{
3928 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003929 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3930 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003931 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003932 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003933 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3934 b + 1, bucketTimeSec, percent);
3935 }
David Sodman4a36e932017-11-07 14:29:47 -08003936 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003937 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003938 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003939 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003940 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003941}
3942
Dan Stozae77c7662016-05-13 11:37:28 -07003943void SurfaceFlinger::recordBufferingStats(const char* layerName,
3944 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003945 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3946 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003947 for (const auto& segment : history) {
3948 if (!segment.usedThirdBuffer) {
3949 stats.twoBufferTime += segment.totalTime;
3950 }
3951 if (segment.occupancyAverage < 1.0f) {
3952 stats.doubleBufferedTime += segment.totalTime;
3953 } else if (segment.occupancyAverage < 2.0f) {
3954 stats.tripleBufferedTime += segment.totalTime;
3955 }
3956 ++stats.numSegments;
3957 stats.totalTime += segment.totalTime;
3958 }
3959}
3960
Brian Andersond6927fb2016-07-23 23:37:30 -07003961void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3962 result.appendFormat("Layer frame timestamps:\n");
3963
3964 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3965 const size_t count = currentLayers.size();
3966 for (size_t i=0 ; i<count ; i++) {
3967 currentLayers[i]->dumpFrameEvents(result);
3968 }
3969}
3970
Dan Stozae77c7662016-05-13 11:37:28 -07003971void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3972 result.append("Buffering stats:\n");
3973 result.append(" [Layer name] <Active time> <Two buffer> "
3974 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003975 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003976 typedef std::tuple<std::string, float, float, float> BufferTuple;
3977 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003978 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003979 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003980 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003981 if (stats.numSegments == 0) {
3982 continue;
3983 }
3984 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3985 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3986 stats.totalTime;
3987 float doubleBufferRatio = static_cast<float>(
3988 stats.doubleBufferedTime) / stats.totalTime;
3989 float tripleBufferRatio = static_cast<float>(
3990 stats.tripleBufferedTime) / stats.totalTime;
3991 sorted.insert({activeTime, {name, twoBufferRatio,
3992 doubleBufferRatio, tripleBufferRatio}});
3993 }
3994 for (const auto& sortedPair : sorted) {
3995 float activeTime = sortedPair.first;
3996 const BufferTuple& values = sortedPair.second;
3997 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3998 std::get<0>(values).c_str(), activeTime,
3999 std::get<1>(values), std::get<2>(values),
4000 std::get<3>(values));
4001 }
4002 result.append("\n");
4003}
4004
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004005void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4006 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01004007 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004008
4009 // TODO: print out if wide-color mode is active or not
4010
4011 for (size_t d = 0; d < mDisplays.size(); d++) {
4012 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4013 int32_t hwcId = displayDevice->getHwcDisplayId();
4014 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4015 continue;
4016 }
4017
4018 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004019 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004020 for (auto&& mode : modes) {
4021 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4022 }
4023
Peiyong Lina52f0292018-03-14 17:26:31 -07004024 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004025 result.appendFormat(" Current color mode: %s (%d)\n",
4026 decodeColorMode(currentMode).c_str(), currentMode);
4027 }
4028 result.append("\n");
4029}
4030
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004031LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004032 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004033 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4034 const State& state = useDrawing ? mDrawingState : mCurrentState;
4035 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004036 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004037 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004038 });
4039
4040 return layersProto;
4041}
4042
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004043LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4044 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004045 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004046
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004047 SizeProto* resolution = layersProto.mutable_resolution();
4048 resolution->set_w(displayDevice->getWidth());
4049 resolution->set_h(displayDevice->getHeight());
4050
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004051 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4052 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4053 layersProto.set_global_transform(
4054 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4055
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004056 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004057 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004058 LayerProto* layerProto = layersProto.add_layers();
4059 layer->writeToProto(layerProto, hwcId);
4060 }
4061 });
4062
4063 return layersProto;
4064}
4065
Mathias Agopian74d211a2013-04-22 16:55:35 +02004066void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4067 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004068{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004069 bool colorize = false;
4070 if (index < args.size()
4071 && (args[index] == String16("--color"))) {
4072 colorize = true;
4073 index++;
4074 }
4075
4076 Colorizer colorizer(colorize);
4077
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004078 // figure out if we're stuck somewhere
4079 const nsecs_t now = systemTime();
4080 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4081 const nsecs_t inTransaction(mDebugInTransaction);
4082 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4083 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4084
4085 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004086 * Dump library configuration.
4087 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004088
4089 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004090 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004091 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004092 appendSfConfigString(result);
4093 appendUiConfigString(result);
4094 appendGuiConfigString(result);
4095 result.append("\n");
4096
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004097 result.append("\nWide-Color information:\n");
4098 dumpWideColorInfo(result);
4099
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004100 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004101 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004102 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004103 result.append(SyncFeatures::getInstance().toString());
4104 result.append("\n");
4105
David Sodman105b7dc2017-11-04 20:28:14 -07004106 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004107
Andy McFadden41d67d72014-04-25 16:58:34 -07004108 colorizer.bold(result);
4109 result.append("DispSync configuration: ");
4110 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004111 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4112 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4113 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004114 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004115 result.append("\n");
4116
Dan Stozab90cf072015-03-05 11:05:59 -08004117 // Dump static screen stats
4118 result.append("\n");
4119 dumpStaticScreenStats(result);
4120 result.append("\n");
4121
Dan Stozae77c7662016-05-13 11:37:28 -07004122 dumpBufferingStats(result);
4123
Andy McFadden4803b742012-09-24 19:07:20 -07004124 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004125 * Dump the visible layer list
4126 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004127 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004128 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004129 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4130 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004131 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004132
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004133 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004134 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004135 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004136 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004137
4138 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004139 * Dump Display state
4140 */
4141
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004142 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004143 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004144 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004145 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4146 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004147 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004148 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004149 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004150
4151 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004152 * Dump SurfaceFlinger global state
4153 */
4154
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004155 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004156 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004157 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004158
Mathias Agopian888c8222012-08-04 21:10:38 -07004159 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004160 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004161
David Sodmanbc815282017-11-05 18:57:52 -08004162 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004164 if (hw) {
4165 hw->undefinedRegion.dump(result, "undefinedRegion");
4166 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4167 hw->getOrientation(), hw->isDisplayOn());
4168 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004169 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004170 " last eglSwapBuffers() time: %f us\n"
4171 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004172 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004173 " refresh-rate : %f fps\n"
4174 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004175 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004176 " gpu_to_cpu_unsupported : %d\n"
4177 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004178 mLastSwapBufferTime/1000.0,
4179 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004180 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004181 1e9 / activeConfig->getVsyncPeriod(),
4182 activeConfig->getDpiX(),
4183 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004184 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185
Mathias Agopian74d211a2013-04-22 16:55:35 +02004186 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004187 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004188
Mathias Agopian74d211a2013-04-22 16:55:35 +02004189 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004190 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191
4192 /*
4193 * VSYNC state
4194 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004195 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004196 result.append("\n");
4197
4198 /*
4199 * HWC layer minidump
4200 */
4201 for (size_t d = 0; d < mDisplays.size(); d++) {
4202 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4203 int32_t hwcId = displayDevice->getHwcDisplayId();
4204 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4205 continue;
4206 }
4207
4208 result.appendFormat("Display %d HWC layers:\n", hwcId);
4209 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004210 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004211 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004212 });
Dan Stozae22aec72016-08-01 13:20:59 -07004213 result.append("\n");
4214 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215
4216 /*
4217 * Dump HWComposer state
4218 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004221 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004222 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004223 result.appendFormat(" h/w composer %s\n",
4224 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004225 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004226
4227 /*
4228 * Dump gralloc state
4229 */
4230 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4231 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004232
4233 /*
4234 * Dump VrFlinger state if in use.
4235 */
4236 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4237 result.append("VrFlinger state:\n");
4238 result.append(mVrFlinger->Dump().c_str());
4239 result.append("\n");
4240 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004241}
4242
Mathias Agopian13127d82013-03-05 17:47:11 -08004243const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004244SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004245 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004246 wp<IBinder> dpy;
4247 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4248 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4249 dpy = mDisplays.keyAt(i);
4250 break;
4251 }
4252 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004253 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004254 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4255 // Just use the primary display so we have something to return
4256 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4257 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004258 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004259}
4260
Keun young Park63f165f2012-08-31 10:53:36 -07004261bool SurfaceFlinger::startDdmConnection()
4262{
4263 void* libddmconnection_dso =
4264 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4265 if (!libddmconnection_dso) {
4266 return false;
4267 }
4268 void (*DdmConnection_start)(const char* name);
4269 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004270 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004271 if (!DdmConnection_start) {
4272 dlclose(libddmconnection_dso);
4273 return false;
4274 }
4275 (*DdmConnection_start)(getServiceName());
4276 return true;
4277}
4278
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004279status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 switch (code) {
4281 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004282 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004284 case CLEAR_ANIMATION_FRAME_STATS:
4285 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004286 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004287 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004288 case ENABLE_VSYNC_INJECTIONS:
4289 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004290 {
4291 // codes that require permission check
4292 IPCThreadState* ipc = IPCThreadState::self();
4293 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004294 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004295 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004296 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004297 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004298 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004300 break;
4301 }
Robert Carr1db73f62016-12-21 12:58:51 -08004302 /*
4303 * Calling setTransactionState is safe, because you need to have been
4304 * granted a reference to Client* and Handle* to do anything with it.
4305 *
4306 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4307 */
4308 case SET_TRANSACTION_STATE:
4309 case CREATE_SCOPED_CONNECTION:
4310 {
4311 return OK;
4312 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004313 case CAPTURE_SCREEN:
4314 {
4315 // codes that require permission check
4316 IPCThreadState* ipc = IPCThreadState::self();
4317 const int pid = ipc->getCallingPid();
4318 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004319 if ((uid != AID_GRAPHICS) &&
4320 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004321 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004322 return PERMISSION_DENIED;
4323 }
4324 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004325 }
chaviwa76b2712017-09-20 12:02:26 -07004326 case CAPTURE_LAYERS: {
4327 IPCThreadState* ipc = IPCThreadState::self();
4328 const int pid = ipc->getCallingPid();
4329 const int uid = ipc->getCallingUid();
4330 if ((uid != AID_GRAPHICS) &&
4331 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4332 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4333 return PERMISSION_DENIED;
4334 }
4335 break;
4336 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004337 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004338 return OK;
4339}
4340
4341status_t SurfaceFlinger::onTransact(
4342 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4343{
4344 status_t credentialCheck = CheckTransactCodeCredentials(code);
4345 if (credentialCheck != OK) {
4346 return credentialCheck;
4347 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4350 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004351 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004352 IPCThreadState* ipc = IPCThreadState::self();
4353 const int uid = ipc->getCallingUid();
4354 if (CC_UNLIKELY(uid != AID_SYSTEM
4355 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004356 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004357 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004358 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004359 return PERMISSION_DENIED;
4360 }
4361 int n;
4362 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004363 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004364 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 return NO_ERROR;
4366 case 1002: // SHOW_UPDATES
4367 n = data.readInt32();
4368 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004369 invalidateHwcGeometry();
4370 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004373 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004374 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004376 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004377 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004378 setTransactionFlags(
4379 eTransactionNeeded|
4380 eDisplayTransactionNeeded|
4381 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004382 return NO_ERROR;
4383 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004384 case 1006:{ // send empty update
4385 signalRefresh();
4386 return NO_ERROR;
4387 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004388 case 1008: // toggle use of hw composer
4389 n = data.readInt32();
4390 mDebugDisableHWC = n ? 1 : 0;
4391 invalidateHwcGeometry();
4392 repaintEverything();
4393 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004394 case 1009: // toggle use of transform hint
4395 n = data.readInt32();
4396 mDebugDisableTransformHint = n ? 1 : 0;
4397 invalidateHwcGeometry();
4398 repaintEverything();
4399 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004400 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004401 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 reply->writeInt32(0);
4403 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004404 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004405 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004406 return NO_ERROR;
4407 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004408 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004409 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004410 return NO_ERROR;
4411 }
4412 case 1014: {
4413 // daltonize
4414 n = data.readInt32();
4415 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004416 case 1:
4417 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4418 break;
4419 case 2:
4420 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4421 break;
4422 case 3:
4423 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4424 break;
4425 default:
4426 mDaltonizer.setType(ColorBlindnessType::None);
4427 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004428 }
4429 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004430 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004431 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004432 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004433 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004434 invalidateHwcGeometry();
4435 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004436 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004438 case 1015: {
4439 // apply a color matrix
4440 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004441 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004442 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004443 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004444 for (size_t j = 0; j < 4; j++) {
4445 mColorMatrix[i][j] = data.readFloat();
4446 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004447 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004448 } else {
4449 mColorMatrix = mat4();
4450 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004451
4452 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4453 // the division by w in the fragment shader
4454 float4 lastRow(transpose(mColorMatrix)[3]);
4455 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4456 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4457 }
4458
Alan Viverette9c5a3332013-09-12 20:04:35 -07004459 invalidateHwcGeometry();
4460 repaintEverything();
4461 return NO_ERROR;
4462 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004463 // This is an experimental interface
4464 // Needs to be shifted to proper binder interface when we productize
4465 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004466 n = data.readInt32();
4467 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004468 return NO_ERROR;
4469 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004470 case 1017: {
4471 n = data.readInt32();
4472 mForceFullDamage = static_cast<bool>(n);
4473 return NO_ERROR;
4474 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004475 case 1018: { // Modify Choreographer's phase offset
4476 n = data.readInt32();
4477 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4478 return NO_ERROR;
4479 }
4480 case 1019: { // Modify SurfaceFlinger's phase offset
4481 n = data.readInt32();
4482 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4483 return NO_ERROR;
4484 }
Irvel468051e2016-06-13 16:44:44 -07004485 case 1020: { // Layer updates interceptor
4486 n = data.readInt32();
4487 if (n) {
4488 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004489 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004490 }
4491 else{
4492 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004493 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004494 }
4495 return NO_ERROR;
4496 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004497 case 1021: { // Disable HWC virtual displays
4498 n = data.readInt32();
4499 mUseHwcVirtualDisplays = !n;
4500 return NO_ERROR;
4501 }
Romain Guy0147a172017-06-01 13:53:56 -07004502 case 1022: { // Set saturation boost
4503 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4504
4505 invalidateHwcGeometry();
4506 repaintEverything();
4507 return NO_ERROR;
4508 }
Romain Guy54f154a2017-10-24 21:40:32 +01004509 case 1023: { // Set native mode
4510 mForceNativeColorMode = data.readInt32() == 1;
4511
4512 invalidateHwcGeometry();
4513 repaintEverything();
4514 return NO_ERROR;
4515 }
4516 case 1024: { // Is wide color gamut rendering/color management supported?
4517 reply->writeBool(hasWideColorDisplay);
4518 return NO_ERROR;
4519 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004520 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004521 n = data.readInt32();
4522 if (n) {
4523 ALOGV("LayerTracing enabled");
4524 mTracing.enable();
4525 doTracing("tracing.enable");
4526 reply->writeInt32(NO_ERROR);
4527 } else {
4528 ALOGV("LayerTracing disabled");
4529 status_t err = mTracing.disable();
4530 reply->writeInt32(err);
4531 }
4532 return NO_ERROR;
4533 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004534 case 1026: { // Get layer tracing status
4535 reply->writeBool(mTracing.isEnabled());
4536 return NO_ERROR;
4537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 }
4539 }
4540 return err;
4541}
4542
Steven Thomas6d8110b2017-08-31 18:24:21 -07004543void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004544 android_atomic_or(1, &mRepaintEverything);
Jeffrey Kardatzkea9dcf112018-04-03 10:45:55 -07004545 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
4546 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
4547 const Rect bounds(displayDevice->getBounds());
4548 displayDevice->dirtyRegion.orSelf(Region(bounds));
4549 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004550 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004551}
4552
Steven Thomas6d8110b2017-08-31 18:24:21 -07004553void SurfaceFlinger::repaintEverything() {
4554 ConditionalLock _l(mStateLock,
4555 std::this_thread::get_id() != mMainThreadId);
4556 repaintEverythingLocked();
4557}
4558
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004559// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4560class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004561public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004562 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4563 ~WindowDisconnector() {
4564 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004565 }
4566
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004567private:
4568 ANativeWindow* mWindow;
4569 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004570};
4571
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004572status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4573 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4574 int32_t minLayerZ, int32_t maxLayerZ,
4575 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004576 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004577 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004578
chaviwa76b2712017-09-20 12:02:26 -07004579 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4580
4581 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004582 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4583
chaviwa76b2712017-09-20 12:02:26 -07004584 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4585
4586 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4587 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004588 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004589}
4590
4591status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004592 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004593 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004594 ATRACE_CALL();
4595
4596 class LayerRenderArea : public RenderArea {
4597 public:
Robert Carr578038f2018-03-09 12:25:24 -08004598 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4599 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4600 : RenderArea(reqHeight, reqWidth),
4601 mLayer(layer),
4602 mCrop(crop),
4603 mFlinger(flinger),
4604 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004605 Rect getBounds() const override {
4606 const Layer::State& layerState(mLayer->getDrawingState());
4607 return Rect(layerState.active.w, layerState.active.h);
4608 }
4609 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4610 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4611 bool isSecure() const override { return false; }
4612 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004613 const Transform& getTransform() const { return mTransform; }
4614
4615 class ReparentForDrawing {
4616 public:
4617 const sp<Layer>& oldParent;
4618 const sp<Layer>& newParent;
4619
4620 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4621 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004622 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004623 }
Robert Carr15eae092018-03-23 13:43:53 -07004624 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004625 };
4626
4627 void render(std::function<void()> drawLayers) override {
4628 if (!mChildrenOnly) {
4629 mTransform = mLayer->getTransform().inverse();
4630 drawLayers();
4631 } else {
4632 Rect bounds = getBounds();
4633 screenshotParentLayer =
4634 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4635 bounds.getWidth(), bounds.getHeight(), 0);
4636
4637 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4638 drawLayers();
4639 }
4640 }
chaviwa76b2712017-09-20 12:02:26 -07004641
chaviw7206d492017-11-10 16:16:12 -08004642 Rect getSourceCrop() const override {
4643 if (mCrop.isEmpty()) {
4644 return getBounds();
4645 } else {
4646 return mCrop;
4647 }
4648 }
chaviwa76b2712017-09-20 12:02:26 -07004649 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004650 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004651
4652 private:
chaviw7206d492017-11-10 16:16:12 -08004653 const sp<Layer> mLayer;
4654 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004655
4656 // In the "childrenOnly" case we reparent the children to a screenshot
4657 // layer which has no properties set and which does not draw.
4658 sp<ContainerLayer> screenshotParentLayer;
4659 Transform mTransform;
4660
4661 SurfaceFlinger* mFlinger;
4662 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004663 };
4664
4665 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4666 auto parent = layerHandle->owner.promote();
4667
chaviw7206d492017-11-10 16:16:12 -08004668 if (parent == nullptr || parent->isPendingRemoval()) {
4669 ALOGE("captureLayers called with a removed parent");
4670 return NAME_NOT_FOUND;
4671 }
4672
Robert Carr578038f2018-03-09 12:25:24 -08004673 const int uid = IPCThreadState::self()->getCallingUid();
4674 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4675 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4676 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4677 return PERMISSION_DENIED;
4678 }
4679
chaviw7206d492017-11-10 16:16:12 -08004680 Rect crop(sourceCrop);
4681 if (sourceCrop.width() <= 0) {
4682 crop.left = 0;
4683 crop.right = parent->getCurrentState().active.w;
4684 }
4685
4686 if (sourceCrop.height() <= 0) {
4687 crop.top = 0;
4688 crop.bottom = parent->getCurrentState().active.h;
4689 }
4690
4691 int32_t reqWidth = crop.width() * frameScale;
4692 int32_t reqHeight = crop.height() * frameScale;
4693
Robert Carr578038f2018-03-09 12:25:24 -08004694 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004695
Robert Carr578038f2018-03-09 12:25:24 -08004696 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004697 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4698 if (!layer->isVisible()) {
4699 return;
Robert Carr578038f2018-03-09 12:25:24 -08004700 } else if (childrenOnly && layer == parent.get()) {
4701 return;
chaviwa76b2712017-09-20 12:02:26 -07004702 }
4703 visitor(layer);
4704 });
4705 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004706 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004707}
4708
4709status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4710 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004711 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004712 bool useIdentityTransform) {
4713 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004714
chaviwa76b2712017-09-20 12:02:26 -07004715 renderArea.updateDimensions();
4716
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004717 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4718 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4719 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4720 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004721
4722 // This mutex protects syncFd and captureResult for communication of the return values from the
4723 // main thread back to this Binder thread
4724 std::mutex captureMutex;
4725 std::condition_variable captureCondition;
4726 std::unique_lock<std::mutex> captureLock(captureMutex);
4727 int syncFd = -1;
4728 std::optional<status_t> captureResult;
4729
Robert Carr03480e22018-01-04 16:02:06 -08004730 const int uid = IPCThreadState::self()->getCallingUid();
4731 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4732
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004733 sp<LambdaMessage> message = new LambdaMessage([&]() {
4734 // If there is a refresh pending, bug out early and tell the binder thread to try again
4735 // after the refresh.
4736 if (mRefreshPending) {
4737 ATRACE_NAME("Skipping screenshot for now");
4738 std::unique_lock<std::mutex> captureLock(captureMutex);
4739 captureResult = std::make_optional<status_t>(EAGAIN);
4740 captureCondition.notify_one();
4741 return;
4742 }
4743
4744 status_t result = NO_ERROR;
4745 int fd = -1;
4746 {
4747 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004748 renderArea.render([&]() {
4749 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4750 useIdentityTransform, forSystem, &fd);
4751 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004752 }
4753
4754 {
4755 std::unique_lock<std::mutex> captureLock(captureMutex);
4756 syncFd = fd;
4757 captureResult = std::make_optional<status_t>(result);
4758 captureCondition.notify_one();
4759 }
4760 });
4761
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004762 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004763 if (result == NO_ERROR) {
4764 captureCondition.wait(captureLock, [&]() { return captureResult; });
4765 while (*captureResult == EAGAIN) {
4766 captureResult.reset();
4767 result = postMessageAsync(message);
4768 if (result != NO_ERROR) {
4769 return result;
4770 }
4771 captureCondition.wait(captureLock, [&]() { return captureResult; });
4772 }
4773 result = *captureResult;
4774 }
4775
4776 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004777 sync_wait(syncFd, -1);
4778 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004779 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004780
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004781 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004782}
4783
chaviwa76b2712017-09-20 12:02:26 -07004784void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4785 TraverseLayersFunction traverseLayers, bool yswap,
4786 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004787 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004788
Lloyd Pique144e1162017-12-20 16:44:52 -08004789 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004790
4791 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004792 const auto raWidth = renderArea.getWidth();
4793 const auto raHeight = renderArea.getHeight();
4794
4795 const auto reqWidth = renderArea.getReqWidth();
4796 const auto reqHeight = renderArea.getReqHeight();
4797 Rect sourceCrop = renderArea.getSourceCrop();
4798
4799 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4800 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004801
Dan Stozac1879002014-05-22 15:59:05 -07004802 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004803 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004804 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004805 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004806 }
4807
4808 // ensure that sourceCrop is inside screen
4809 if (sourceCrop.left < 0) {
4810 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4811 }
chaviwa76b2712017-09-20 12:02:26 -07004812 if (sourceCrop.right > raWidth) {
4813 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004814 }
4815 if (sourceCrop.top < 0) {
4816 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4817 }
chaviwa76b2712017-09-20 12:02:26 -07004818 if (sourceCrop.bottom > raHeight) {
4819 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004820 }
4821
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004822 Dataspace outputDataspace = Dataspace::UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004823 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004824 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004825 outputDataspace = Dataspace::DISPLAY_P3;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004826 }
4827 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004828
Mathias Agopian180f10d2013-04-10 22:55:41 -07004829 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004830 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004831
4832 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004833 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4834 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004835 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004836
4837 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004838 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004839
chaviwa76b2712017-09-20 12:02:26 -07004840 traverseLayers([&](Layer* layer) {
4841 if (filtering) layer->setFiltering(true);
4842 layer->draw(renderArea, useIdentityTransform);
4843 if (filtering) layer->setFiltering(false);
4844 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004845}
4846
chaviwa76b2712017-09-20 12:02:26 -07004847status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4848 TraverseLayersFunction traverseLayers,
4849 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004850 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004851 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004852 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004853 ATRACE_CALL();
4854
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004855 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004856
4857 traverseLayers([&](Layer* layer) {
4858 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4859 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004860
Robert Carr03480e22018-01-04 16:02:06 -08004861 // We allow the system server to take screenshots of secure layers for
4862 // use in situations like the Screen-rotation animation and place
4863 // the impetus on WindowManager to not persist them.
4864 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004865 ALOGW("FB is protected: PERMISSION_DENIED");
4866 return PERMISSION_DENIED;
4867 }
4868
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004869 // this binds the given EGLImage as a framebuffer for the
4870 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004871 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004872 if (bufferBond.getStatus() != NO_ERROR) {
4873 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004874 return INVALID_OPERATION;
4875 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004876
Dan Stozaabcda352017-06-01 14:37:39 -07004877 // this will in fact render into our dequeued buffer
4878 // via an FBO, which means we didn't have to create
4879 // an EGLSurface and therefore we're not
4880 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004881 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004882
Dan Stozaabcda352017-06-01 14:37:39 -07004883 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004884 getRenderEngine().finish();
4885 *outSyncFd = -1;
4886
chaviwa76b2712017-09-20 12:02:26 -07004887 const auto reqWidth = renderArea.getReqWidth();
4888 const auto reqHeight = renderArea.getReqHeight();
4889
Dan Stozaabcda352017-06-01 14:37:39 -07004890 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4891 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004892 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004893 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004894 } else {
4895 base::unique_fd syncFd = getRenderEngine().flush();
4896 if (syncFd < 0) {
4897 getRenderEngine().finish();
4898 }
4899 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004900 }
4901
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004902 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004903}
4904
Mathias Agopiand5556842013-09-19 17:08:37 -07004905void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004906 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004907 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004908 for (size_t y = 0; y < h; y++) {
4909 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4910 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004911 if (p[x] != 0xFF000000) return;
4912 }
4913 }
chaviwa76b2712017-09-20 12:02:26 -07004914 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004915
Robert Carr2047fae2016-11-28 14:09:09 -08004916 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004917 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004918 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004919 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4920 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4921 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4922 static_cast<float>(state.color.a));
4923 i++;
4924 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004925 }
4926}
4927
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004928// ---------------------------------------------------------------------------
4929
Dan Stoza412903f2017-04-27 13:42:17 -07004930void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4931 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004932}
4933
Dan Stoza412903f2017-04-27 13:42:17 -07004934void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4935 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004936}
4937
chaviwa76b2712017-09-20 12:02:26 -07004938void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4939 int32_t maxLayerZ,
4940 const LayerVector::Visitor& visitor) {
4941 // We loop through the first level of layers without traversing,
4942 // as we need to interpret min/max layer Z in the top level Z space.
4943 for (const auto& layer : mDrawingState.layersSortedByZ) {
4944 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4945 continue;
4946 }
4947 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004948 // relative layers are traversed in Layer::traverseInZOrder
4949 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004950 continue;
4951 }
4952 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004953 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4954 return;
4955 }
chaviwa76b2712017-09-20 12:02:26 -07004956 if (!layer->isVisible()) {
4957 return;
4958 }
4959 visitor(layer);
4960 });
4961 }
4962}
4963
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004965
4966
4967#if defined(__gl_h_)
4968#error "don't include gl/gl.h in this file"
4969#endif
4970
4971#if defined(__gl2_h_)
4972#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004973#endif