blob: 6f3f2520ceaaf55775b468266a4893e03f0813c9 [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>
Iris Chang7501ed62018-04-30 14:45:42 +080091#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
92#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090093#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094
chaviw1d044282017-09-27 12:19:28 -070095#include <layerproto/LayerProtoParser.h>
96
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097#define DISPLAY_COUNT 1
98
Mathias Agopianfee2b462013-07-03 12:34:01 -070099/*
100 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
101 * black pixels.
102 */
103#define DEBUG_SCREENSHOTS false
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700109using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700110using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700111using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700112using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
Steven Thomasb02664d2017-07-26 18:48:28 -0700114namespace {
115class ConditionalLock {
116public:
117 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
118 if (lock) {
119 mMutex.lock();
120 }
121 }
122 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
123private:
124 Mutex& mMutex;
125 bool mLocked;
126};
127} // namespace anonymous
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129// ---------------------------------------------------------------------------
130
Mathias Agopian99b49842011-06-27 16:05:52 -0700131const String16 sHardwareTest("android.permission.HARDWARE_TEST");
132const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
133const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
134const String16 sDump("android.permission.DUMP");
135
136// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800137int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
138int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700139int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700140bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800141uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800142bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800143bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800144int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800145// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600146bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700147
Kalle Raitaa099a242017-01-11 11:17:29 -0800148
149std::string getHwcServiceName() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.hwc_service_name", value, "default");
152 ALOGI("Using HWComposer service: '%s'", value);
153 return std::string(value);
154}
155
156bool useTrebleTestingOverride() {
157 char value[PROPERTY_VALUE_MAX] = {};
158 property_get("debug.sf.treble_testing_override", value, "false");
159 ALOGI("Treble testing override: '%s'", value);
160 return std::string(value) == "true";
161}
162
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800163DisplayColorSetting toDisplayColorSetting(int value) {
164 switch(value) {
165 case 0:
166 return DisplayColorSetting::MANAGED;
167 case 1:
168 return DisplayColorSetting::UNMANAGED;
169 case 2:
170 return DisplayColorSetting::ENHANCED;
171 default:
172 return DisplayColorSetting::MANAGED;
173 }
174}
175
176std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
177 switch(displayColorSetting) {
178 case DisplayColorSetting::MANAGED:
179 return std::string("Natural Mode");
180 case DisplayColorSetting::UNMANAGED:
181 return std::string("Saturated Mode");
182 case DisplayColorSetting::ENHANCED:
183 return std::string("Auto Color Mode");
184 }
185 return std::string("Unknown Display Color Setting");
186}
187
Lloyd Pique09594832018-01-22 17:48:03 -0800188NativeWindowSurface::~NativeWindowSurface() = default;
189
190namespace impl {
191
192class NativeWindowSurface final : public android::NativeWindowSurface {
193public:
194 static std::unique_ptr<android::NativeWindowSurface> create(
195 const sp<IGraphicBufferProducer>& producer) {
196 return std::make_unique<NativeWindowSurface>(producer);
197 }
198
199 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
200 : surface(new Surface(producer, false)) {}
201
202 ~NativeWindowSurface() override = default;
203
204private:
205 sp<ANativeWindow> getNativeWindow() const override { return surface; }
206
207 void preallocateBuffers() override { surface->allocateBuffers(); }
208
209 sp<Surface> surface;
210};
211
212} // namespace impl
213
David Sodmanbc815282017-11-05 18:57:52 -0800214SurfaceFlingerBE::SurfaceFlingerBE()
215 : mHwcServiceName(getHwcServiceName()),
216 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800217 mFrameBuckets(),
218 mTotalTime(0),
219 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800220 mComposerSequenceId(0) {
221}
222
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800223SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800224 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700226 mTransactionPending(false),
227 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700228 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700229 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700230 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800234 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800235 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700237 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700238 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700239 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700240 mDebugInSwapBuffers(0),
241 mLastSwapBufferTime(0),
242 mDebugInTransaction(0),
243 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700244 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700245 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000246 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700247 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700248 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800249 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800250 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700251 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800252 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800253 mCreateBufferQueue(&BufferQueue::createBufferQueue),
254 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800255
256SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800257 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800258
259 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
260 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
261
262 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
263 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
264
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
266 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700268 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
270
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700271 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
273
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
278 useVrFlinger = getBool< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::useVrFlinger>(false);
280
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
283
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600284 hasWideColorDisplay =
285 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
286
Iris Chang7501ed62018-04-30 14:45:42 +0800287 V1_1::DisplayOrientation primaryDisplayOrientation =
288 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
289 V1_1::DisplayOrientation::ORIENTATION_0);
290
291 switch (primaryDisplayOrientation) {
292 case V1_1::DisplayOrientation::ORIENTATION_90:
293 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
294 break;
295 case V1_1::DisplayOrientation::ORIENTATION_180:
296 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
297 break;
298 case V1_1::DisplayOrientation::ORIENTATION_270:
299 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
300 break;
301 default:
302 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
303 break;
304 }
305 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
306
David Sodman99974d22017-11-28 12:04:33 -0800307 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309 // debugging stuff...
310 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700311
Mathias Agopianb4b17302013-03-20 18:36:41 -0700312 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700313 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700314
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 property_get("debug.sf.showupdates", value, "0");
316 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700317
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700318 property_get("debug.sf.ddms", value, "0");
319 mDebugDDMS = atoi(value);
320 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700321 if (!startDdmConnection()) {
322 // start failed, and DDMS debugging not enabled
323 mDebugDDMS = 0;
324 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700325 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700326 ALOGI_IF(mDebugRegion, "showupdates enabled");
327 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700328
329 property_get("debug.sf.disable_backpressure", value, "0");
330 mPropagateBackpressure = !atoi(value);
331 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700332
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800333 property_get("debug.sf.enable_hwc_vds", value, "0");
334 mUseHwcVirtualDisplays = atoi(value);
335 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800336
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800337 property_get("ro.sf.disable_triple_buffer", value, "1");
338 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800339 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700340
Yiwei Zhang243b3782018-05-15 17:40:04 -0700341 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700342 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
343 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
344
Dan Stoza2713c302018-03-28 17:07:36 -0700345 property_get("debug.sf.early_phase_offset_ns", value, "0");
346 const int earlyWakeupOffsetOffsetNs = atoi(value);
347 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
348 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
349 sfVsyncPhaseOffsetNs);
350
Romain Guy11d63f42017-07-20 12:47:14 -0700351 // We should be reading 'persist.sys.sf.color_saturation' here
352 // but since /data may be encrypted, we need to wait until after vold
353 // comes online to attempt to read the property. The property is
354 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800355
356 if (useTrebleTestingOverride()) {
357 // Without the override SurfaceFlinger cannot connect to HIDL
358 // services that are not listed in the manifests. Considered
359 // deriving the setting from the set service name, but it
360 // would be brittle if the name that's not 'default' is used
361 // for production purposes later on.
362 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
363 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364}
365
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366void SurfaceFlinger::onFirstRef()
367{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800368 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800369}
370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371SurfaceFlinger::~SurfaceFlinger()
372{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800373}
374
Dan Stozac7014012014-02-14 15:03:43 -0800375void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800376{
377 // the window manager died on us. prepare its eulogy.
378
Andy McFadden13a082e2012-08-24 10:16:42 -0700379 // restore initial conditions (default device unblank, etc)
380 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381
382 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700383 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800384}
385
Robert Carr1db73f62016-12-21 12:58:51 -0800386static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700387 status_t err = client->initCheck();
388 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800389 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390 }
Robert Carr1db73f62016-12-21 12:58:51 -0800391 return nullptr;
392}
393
394sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
395 return initClient(new Client(this));
396}
397
398sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
399 const sp<IGraphicBufferProducer>& gbp) {
400 if (authenticateSurfaceTexture(gbp) == false) {
401 return nullptr;
402 }
403 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
404 if (layer == nullptr) {
405 return nullptr;
406 }
407
408 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700411sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
412 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413{
414 class DisplayToken : public BBinder {
415 sp<SurfaceFlinger> flinger;
416 virtual ~DisplayToken() {
417 // no more references, this display must be terminated
418 Mutex::Autolock _l(flinger->mStateLock);
419 flinger->mCurrentState.displays.removeItem(this);
420 flinger->setTransactionFlags(eDisplayTransactionNeeded);
421 }
422 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700423 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700424 : flinger(flinger) {
425 }
426 };
427
428 sp<BBinder> token = new DisplayToken(this);
429
430 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700431 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700432 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800434 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435 return token;
436}
437
Jesse Hall6c913be2013-08-08 12:15:49 -0700438void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
439 Mutex::Autolock _l(mStateLock);
440
441 ssize_t idx = mCurrentState.displays.indexOfKey(display);
442 if (idx < 0) {
443 ALOGW("destroyDisplay: invalid display token");
444 return;
445 }
446
447 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
448 if (!info.isVirtualDisplay()) {
449 ALOGE("destroyDisplay called for non-virtual display");
450 return;
451 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800452 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 mCurrentState.displays.removeItemsAt(idx);
454 setTransactionFlags(eDisplayTransactionNeeded);
455}
456
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700458 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800460 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461 }
Jesse Hall692c7232012-11-08 15:41:56 -0800462 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700463}
464
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465void SurfaceFlinger::bootFinished()
466{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700467 if (mStartPropertySetThread->join() != NO_ERROR) {
468 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800469 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470 const nsecs_t now = systemTime();
471 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000472 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700473
474 // wait patiently for the window manager death
475 const String16 name("window");
476 sp<IBinder> window(defaultServiceManager()->getService(name));
477 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700478 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700479 }
480
Steven Thomas050b2c82017-03-06 11:45:16 -0800481 if (mVrFlinger) {
482 mVrFlinger->OnBootFinished();
483 }
484
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700485 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700486 // formerly we would just kill the process, but we now ask it to exit so it
487 // can choose where to stop the animation.
488 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700489
490 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
491 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
492 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700493
Thierry Strudel2924d012017-08-14 15:19:37 -0700494 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700495 readPersistentProperties();
496 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700497 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498}
499
Mathias Agopian3f844832013-08-07 21:24:32 -0700500void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700501 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800502 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700503 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700504 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800505 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
506 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700507 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700508 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700509 return true;
510 }
511 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700512 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700513}
514
Lloyd Piquee83f9312018-02-01 12:53:17 -0800515class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700517 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000518 const char* name) :
519 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700520 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000522 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
523 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700524 mDispSync(dispSync),
525 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 mVsyncMutex(),
527 mPhaseOffset(phaseOffset),
528 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700529
Lloyd Piquee83f9312018-02-01 12:53:17 -0800530 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000535 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 static_cast<DispSync::Callback*>(this));
537 if (err != NO_ERROR) {
538 ALOGE("error registering vsync callback: %s (%d)",
539 strerror(-err), err);
540 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 } else {
543 status_t err = mDispSync->removeEventListener(
544 static_cast<DispSync::Callback*>(this));
545 if (err != NO_ERROR) {
546 ALOGE("error unregistering vsync callback: %s (%d)",
547 strerror(-err), err);
548 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700549 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 }
553
Lloyd Piquee83f9312018-02-01 12:53:17 -0800554 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700555 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 mCallback = callback;
557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mVsyncMutex);
561
562 // Normalize phaseOffset to [0, period)
563 auto period = mDispSync->getPeriod();
564 phaseOffset %= period;
565 if (phaseOffset < 0) {
566 // If we're here, then phaseOffset is in (-period, 0). After this
567 // operation, it will be in (0, period)
568 phaseOffset += period;
569 }
570 mPhaseOffset = phaseOffset;
571
572 // If we're not enabled, we don't need to mess with the listeners
573 if (!mEnabled) {
574 return;
575 }
576
Dan Stoza2713c302018-03-28 17:07:36 -0700577 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
578 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700580 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 strerror(-err), err);
582 }
583 }
584
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585private:
586 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800587 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700589 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 callback = mCallback;
591
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592 if (mTraceVsync) {
593 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700594 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700595 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 }
597
Peiyong Lin566a3b42018-01-09 18:22:43 -0800598 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599 callback->onVSyncEvent(when);
600 }
601 }
602
Tim Murray4a4e4a22016-04-19 16:29:23 +0000603 const char* const mName;
604
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 int mValue;
606
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700607 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700608 const String8 mVsyncOnLabel;
609 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700610
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700612
613 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700615
616 Mutex mVsyncMutex; // Protects the following
617 nsecs_t mPhaseOffset;
618 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619};
620
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 InjectVSyncSource() = default;
624 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625
Lloyd Piquee83f9312018-02-01 12:53:17 -0800626 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700627 std::lock_guard<std::mutex> lock(mCallbackMutex);
628 mCallback = callback;
629 }
630
Lloyd Piquee83f9312018-02-01 12:53:17 -0800631 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700632 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700633 if (mCallback) {
634 mCallback->onVSyncEvent(when);
635 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636 }
637
Lloyd Piquee83f9312018-02-01 12:53:17 -0800638 void setVSyncEnabled(bool) override {}
639 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700640
641private:
642 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800643 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700644};
645
Wei Wangf9b05ee2017-07-19 20:59:39 -0700646// Do not call property_set on main thread which will be blocked by init
647// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700649 ALOGI( "SurfaceFlinger's main thread ready to run. "
650 "Initializing graphics H/W...");
651
Thierry Strudel2924d012017-08-14 15:19:37 -0700652 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900653
Steven Thomasb02664d2017-07-26 18:48:28 -0700654 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800657 mEventThreadSource =
658 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
659 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800660 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
661 [this]() { resyncWithRateLimit(); },
662 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800663 "appEventThread");
664 mSfEventThreadSource =
665 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
666 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800667
Lloyd Pique24b0a482018-03-09 18:52:26 -0800668 mSFEventThread =
669 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
670 [this]() { resyncWithRateLimit(); },
671 [this](nsecs_t timestamp) {
672 mInterceptor->saveVSyncEvent(timestamp);
673 },
674 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800675 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700676 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677
Steven Thomasb02664d2017-07-26 18:48:28 -0700678 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800679 getBE().mRenderEngine =
680 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
681 hasWideColorDisplay
682 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
683 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800684 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700685
686 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
687 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800688 getBE().mHwc.reset(
689 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700690 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
693 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
694 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800695
Lloyd Piquefcd86612017-12-14 17:15:36 -0800696 // make the default display GLContext current so that we can create textures
697 // when creating Layers (which may happens before we render something)
698 getDefaultDisplayDeviceLocked()->makeCurrent();
699
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 if (useVrFlinger) {
701 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700702 // This callback is called from the vr flinger dispatch thread. We
703 // need to call signalTransaction(), which requires holding
704 // mStateLock when we're not on the main thread. Acquiring
705 // mStateLock from the vr flinger dispatch thread might trigger a
706 // deadlock in surface flinger (see b/66916578), so post a message
707 // to be handled on the main thread instead.
708 sp<LambdaMessage> message = new LambdaMessage([=]() {
709 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
710 mVrFlingerRequestsDisplay = requestDisplay;
711 signalTransaction();
712 });
713 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800714 };
David Sodman105b7dc2017-11-04 20:28:14 -0700715 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
716 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800717 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800718 if (!mVrFlinger) {
719 ALOGE("Failed to start vrflinger");
720 }
721 }
722
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800723 mEventControlThread = std::make_unique<impl::EventControlThread>(
724 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700725
Mathias Agopian92a979a2012-08-02 18:32:23 -0700726 // initialize our drawing state
727 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700728
Andy McFadden13a082e2012-08-24 10:16:42 -0700729 // set initial conditions (e.g. unblank default device)
730 initializeDisplays();
731
David Sodmanbc815282017-11-05 18:57:52 -0800732 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700733
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 // Inform native graphics APIs whether the present timestamp is supported:
735 if (getHwComposer().hasCapability(
736 HWC2::Capability::PresentFenceIsNotReliable)) {
737 mStartPropertySetThread = new StartPropertySetThread(false);
738 } else {
739 mStartPropertySetThread = new StartPropertySetThread(true);
740 }
741
742 if (mStartPropertySetThread->Start() != NO_ERROR) {
743 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800745
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
747 Dataspace::SRGB_LINEAR);
748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800763 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
764 ALOGV("Display Color Setting is set to %s.",
765 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700766}
767
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800769 // Start boot animation service by setting a property mailbox
770 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800772 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700773 if (mStartPropertySetThread->join() != NO_ERROR) {
774 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800775 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800779 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800783 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800786// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800787
Jamie Gennis582270d2011-08-17 18:19:00 -0700788bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800790 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800791 return authenticateSurfaceTextureLocked(bufferProducer);
792}
793
794bool SurfaceFlinger::authenticateSurfaceTextureLocked(
795 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800796 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800797 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800798}
799
Brian Anderson6b376712017-04-04 10:51:39 -0700800status_t SurfaceFlinger::getSupportedFrameTimestamps(
801 std::vector<FrameEvent>* outSupported) const {
802 *outSupported = {
803 FrameEvent::REQUESTED_PRESENT,
804 FrameEvent::ACQUIRE,
805 FrameEvent::LATCH,
806 FrameEvent::FIRST_REFRESH_START,
807 FrameEvent::LAST_REFRESH_START,
808 FrameEvent::GPU_COMPOSITION_DONE,
809 FrameEvent::DEQUEUE_READY,
810 FrameEvent::RELEASE,
811 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700812 ConditionalLock _l(mStateLock,
813 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700814 if (!getHwComposer().hasCapability(
815 HWC2::Capability::PresentFenceIsNotReliable)) {
816 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
817 }
818 return NO_ERROR;
819}
820
Dan Stoza7f7da322014-05-02 15:26:25 -0700821status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
822 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 return BAD_VALUE;
825 }
826
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500827 if (!display.get())
828 return NAME_NOT_FOUND;
829
Jesse Hall692c7232012-11-08 15:41:56 -0800830 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700831 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800832 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700833 type = i;
834 break;
835 }
836 }
837
838 if (type < 0) {
839 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700840 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 // TODO: Not sure if display density should handled by SF any longer
843 class Density {
844 static int getDensityFromProperty(char const* propName) {
845 char property[PROPERTY_VALUE_MAX];
846 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800847 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 density = atoi(property);
849 }
850 return density;
851 }
852 public:
853 static int getEmuDensity() {
854 return getDensityFromProperty("qemu.sf.lcd_density"); }
855 static int getBuildDensity() {
856 return getDensityFromProperty("ro.sf.lcd_density"); }
857 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700860
Steven Thomas6d8110b2017-08-31 18:24:21 -0700861 ConditionalLock _l(mStateLock,
862 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 DisplayInfo info = DisplayInfo();
865
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866 float xdpi = hwConfig->getDpiX();
867 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700868
869 if (type == DisplayDevice::DISPLAY_PRIMARY) {
870 // The density of the device is provided by a build property
871 float density = Density::getBuildDensity() / 160.0f;
872 if (density == 0) {
873 // the build doesn't provide a density -- this is wrong!
874 // use xdpi instead
875 ALOGE("ro.sf.lcd_density must be defined as a build property");
876 density = xdpi / 160.0f;
877 }
878 if (Density::getEmuDensity()) {
879 // if "qemu.sf.lcd_density" is specified, it overrides everything
880 xdpi = ydpi = density = Density::getEmuDensity();
881 density /= 160.0f;
882 }
883 info.density = density;
884
885 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700886 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800887 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 } else {
889 // TODO: where should this value come from?
890 static const int TV_DENSITY = 213;
891 info.density = TV_DENSITY / 160.0f;
892 info.orientation = 0;
893 }
894
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.w = hwConfig->getWidth();
896 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700897 info.xdpi = xdpi;
898 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800899 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900900 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901
Andy McFadden91b2ca82014-06-13 14:04:23 -0700902 // This is how far in advance a buffer must be queued for
903 // presentation at a given time. If you want a buffer to appear
904 // on the screen at time N, you must submit the buffer before
905 // (N - presentationDeadline).
906 //
907 // Normally it's one full refresh period (to give SF a chance to
908 // latch the buffer), but this can be reduced by configuring a
909 // DispSync offset. Any additional delays introduced by the hardware
910 // composer or panel must be accounted for here.
911 //
912 // We add an additional 1ms to allow for processing time and
913 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800914 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800915 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700916
917 // All non-virtual displays are currently considered secure.
918 info.secure = true;
919
Iris Chang7501ed62018-04-30 14:45:42 +0800920 if (type == DisplayDevice::DISPLAY_PRIMARY &&
921 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
922 std::swap(info.w, info.h);
923 }
924
Michael Wright28f24d02016-07-12 13:30:53 -0700925 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700926 }
927
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 return NO_ERROR;
929}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700930
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800931status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 return BAD_VALUE;
935 }
936
937 // FIXME for now we always return stats for the primary display
938 memset(stats, 0, sizeof(*stats));
939 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
940 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
941 return NO_ERROR;
942}
943
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800945 if (display == nullptr) {
946 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800947 return BAD_VALUE;
948 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700949
950 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800951 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700952 return device->getActiveConfig();
953 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700954
Dan Stoza24a42e92015-03-09 10:04:11 -0700955 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700956}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700957
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
959 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
960 this);
961 int32_t type = hw->getDisplayType();
962 int currentMode = hw->getActiveConfig();
963
964 if (mode == currentMode) {
965 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
966 return;
967 }
968
969 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
970 ALOGW("Trying to set config for virtual display");
971 return;
972 }
973
974 hw->setActiveConfig(mode);
975 getHwComposer().setActiveConfig(type, mode);
976}
977
978status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
979 class MessageSetActiveConfig: public MessageBase {
980 SurfaceFlinger& mFlinger;
981 sp<IBinder> mDisplay;
982 int mMode;
983 public:
984 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
985 int mode) :
986 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
987 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700988 Vector<DisplayInfo> configs;
989 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700990 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700991 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700992 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700993 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700994 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800996 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700998 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1000 ALOGW("Attempt to set active config = %d for virtual display",
1001 mMode);
1002 } else {
1003 mFlinger.setActiveConfigInternal(hw, mMode);
1004 }
1005 return true;
1006 }
1007 };
1008 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1009 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001010 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011}
Michael Wright28f24d02016-07-12 13:30:53 -07001012status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001014 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1015 return BAD_VALUE;
1016 }
1017
1018 if (!display.get()) {
1019 return NAME_NOT_FOUND;
1020 }
1021
1022 int32_t type = NAME_NOT_FOUND;
1023 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1024 if (display == mBuiltinDisplays[i]) {
1025 type = i;
1026 break;
1027 }
1028 }
1029
1030 if (type < 0) {
1031 return type;
1032 }
1033
Peiyong Lina52f0292018-03-14 17:26:31 -07001034 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001035 {
1036 ConditionalLock _l(mStateLock,
1037 std::this_thread::get_id() != mMainThreadId);
1038 modes = getHwComposer().getColorModes(type);
1039 }
Michael Wright28f24d02016-07-12 13:30:53 -07001040 outColorModes->clear();
1041 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1042
1043 return NO_ERROR;
1044}
1045
Peiyong Lina52f0292018-03-14 17:26:31 -07001046ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001047 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001048 if (device != nullptr) {
1049 return device->getActiveColorMode();
1050 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001051 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001052}
1053
1054void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001055 ColorMode mode, Dataspace dataSpace,
1056 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001057 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001059 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001060 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001061
Peiyong Lin38e9a562018-04-10 16:24:20 -07001062 if (mode == currentMode && dataSpace == currentDataSpace &&
1063 renderIntent == currentRenderIntent) {
1064 return;
1065 }
1066
1067 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1068 ALOGW("Trying to set config for virtual display");
1069 return;
1070 }
1071
1072 hw->setActiveColorMode(mode);
1073 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001074 hw->setActiveRenderIntent(renderIntent);
1075 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1076
1077 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1078 decodeColorMode(mode).c_str(), mode,
1079 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1080 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001081}
1082
1083
1084status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001086 class MessageSetActiveColorMode: public MessageBase {
1087 SurfaceFlinger& mFlinger;
1088 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001090 public:
1091 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001092 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001093 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1094 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001095 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001096 mFlinger.getDisplayColorModes(mDisplay, &modes);
1097 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001098 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001099 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1100 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001101 return true;
1102 }
1103 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1104 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001105 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1106 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001107 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001108 ALOGW("Attempt to set active color mode %s %d for virtual display",
1109 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001110 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001111 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1112 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001113 }
1114 return true;
1115 }
1116 };
1117 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1118 postMessageSync(msg);
1119 return NO_ERROR;
1120}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001121
Svetoslavd85084b2014-03-20 10:28:31 -07001122status_t SurfaceFlinger::clearAnimationFrameStats() {
1123 Mutex::Autolock _l(mStateLock);
1124 mAnimFrameTracker.clearStats();
1125 return NO_ERROR;
1126}
1127
1128status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1129 Mutex::Autolock _l(mStateLock);
1130 mAnimFrameTracker.getStats(outStats);
1131 return NO_ERROR;
1132}
1133
Dan Stozac4f471e2016-03-24 09:31:08 -07001134status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1135 HdrCapabilities* outCapabilities) const {
1136 Mutex::Autolock _l(mStateLock);
1137
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001138 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001139 if (displayDevice == nullptr) {
1140 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1141 return BAD_VALUE;
1142 }
1143
Peiyong Linfb069302018-04-25 14:34:31 -07001144 // At this point the DisplayDeivce should already be set up,
1145 // meaning the luminance information is already queried from
1146 // hardware composer and stored properly.
1147 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1148 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1149 capabilities.getDesiredMaxLuminance(),
1150 capabilities.getDesiredMaxAverageLuminance(),
1151 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001152
1153 return NO_ERROR;
1154}
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1158 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 if (mInjectVSyncs == enable) {
1161 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163
1164 if (enable) {
1165 ALOGV("VSync Injections enabled");
1166 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001167 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001168 mInjectorEventThread = std::make_unique<
1169 impl::EventThread>(mVSyncInjector.get(),
1170 [this]() { resyncWithRateLimit(); },
1171 impl::EventThread::InterceptVSyncsCallback(),
1172 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001174 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 } else {
1176 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001177 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 }
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 });
1182 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 return NO_ERROR;
1184}
1185
1186status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 Mutex::Autolock _l(mStateLock);
1188
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189 if (!mInjectVSyncs) {
1190 ALOGE("VSync Injections not enabled");
1191 return BAD_VALUE;
1192 }
1193 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1194 ALOGV("Injecting VSync inside SurfaceFlinger");
1195 mVSyncInjector->onInjectSyncEvent(when);
1196 }
1197 return NO_ERROR;
1198}
1199
Lloyd Pique755e3192018-01-31 16:46:15 -08001200status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1201 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001202 IPCThreadState* ipc = IPCThreadState::self();
1203 const int pid = ipc->getCallingPid();
1204 const int uid = ipc->getCallingUid();
1205 if ((uid != AID_SHELL) &&
1206 !PermissionCache::checkPermission(sDump, pid, uid)) {
1207 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1208 return PERMISSION_DENIED;
1209 }
1210
1211 // Try to acquire a lock for 1s, fail gracefully
1212 const status_t err = mStateLock.timedLock(s2ns(1));
1213 const bool locked = (err == NO_ERROR);
1214 if (!locked) {
1215 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1216 return TIMED_OUT;
1217 }
1218
1219 outLayers->clear();
1220 mCurrentState.traverseInZOrder([&](Layer* layer) {
1221 outLayers->push_back(layer->getLayerDebugInfo());
1222 });
1223
1224 mStateLock.unlock();
1225 return NO_ERROR;
1226}
1227
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001228// ----------------------------------------------------------------------------
1229
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001230sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1231 ISurfaceComposer::VsyncSource vsyncSource) {
1232 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1233 return mSFEventThread->createEventConnection();
1234 } else {
1235 return mEventThread->createEventConnection();
1236 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001237}
1238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240
1241void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001242 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001243}
1244
1245void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001246 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001250 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001251}
1252
1253void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001254 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001255 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256}
1257
1258status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001259 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001260 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001264 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001265 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266 if (res == NO_ERROR) {
1267 msg->wait();
1268 }
1269 return res;
1270}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001271
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001272void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001273 do {
1274 waitForEvent();
1275 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001276}
1277
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278void SurfaceFlinger::enableHardwareVsync() {
1279 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001282 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1283 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001285 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001286}
1287
Jesse Hall948fe0c2013-10-14 12:56:09 -07001288void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289 Mutex::Autolock _l(mHWVsyncLock);
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeAvailable) {
1292 mHWVsyncAvailable = true;
1293 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001294 // Hardware vsync is not currently available, so abort the resync
1295 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001296 return;
1297 }
1298
David Sodman105b7dc2017-11-04 20:28:14 -07001299 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301
1302 mPrimaryDispSync.reset();
1303 mPrimaryDispSync.setPeriod(period);
1304
1305 if (!mPrimaryHWVsyncEnabled) {
1306 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001307 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1308 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 mPrimaryHWVsyncEnabled = true;
1310 }
1311}
1312
Jesse Hall948fe0c2013-10-14 12:56:09 -07001313void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314 Mutex::Autolock _l(mHWVsyncLock);
1315 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001316 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1317 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318 mPrimaryDispSync.endResync();
1319 mPrimaryHWVsyncEnabled = false;
1320 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001321 if (makeUnavailable) {
1322 mHWVsyncAvailable = false;
1323 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324}
1325
Tim Murray4a4e4a22016-04-19 16:29:23 +00001326void SurfaceFlinger::resyncWithRateLimit() {
1327 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001328
1329 // No explicit locking is needed here since EventThread holds a lock while calling this method
1330 static nsecs_t sLastResyncAttempted = 0;
1331 const nsecs_t now = systemTime();
1332 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001333 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001334 }
Dan Stoza57164302017-05-08 14:03:54 -07001335 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001336}
1337
Steven Thomasb02664d2017-07-26 18:48:28 -07001338void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1339 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001342 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 return;
1344 }
1345
1346 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001347 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001348 return;
1349 }
1350
Jamie Gennisd1700752013-10-14 12:22:52 -07001351 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352
Jamie Gennisd1700752013-10-14 12:22:52 -07001353 { // Scope for the lock
1354 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001356 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001358 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001359
1360 if (needsHwVsync) {
1361 enableHardwareVsync();
1362 } else {
1363 disableHardwareVsync(false);
1364 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001365}
1366
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001367void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001368 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1369 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001370}
1371
Lloyd Pique715a2c12017-12-14 17:18:08 -08001372void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1373 HWC2::Connection connection) {
1374 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1375 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376
Lloyd Piqueba04e622017-12-14 17:11:26 -08001377 // Ignore events that do not have the right sequenceId.
1378 if (sequenceId != getBE().mComposerSequenceId) {
1379 return;
1380 }
1381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 // Only lock if we're not on the main thread. This function is normally
1383 // called on a hwbinder thread, but for the primary display it's called on
1384 // the main thread with the state lock already held, so don't attempt to
1385 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001386 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001387
Lloyd Pique715a2c12017-12-14 17:18:08 -08001388 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001389
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001390 if (std::this_thread::get_id() == mMainThreadId) {
1391 // Process all pending hot plug events immediately if we are on the main thread.
1392 processDisplayHotplugEventsLocked();
1393 }
1394
Lloyd Piqueba04e622017-12-14 17:11:26 -08001395 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001396}
1397
Steven Thomasb02664d2017-07-26 18:48:28 -07001398void SurfaceFlinger::onRefreshReceived(int sequenceId,
1399 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001400 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001401 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001403 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001404 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001405}
1406
Dan Stoza9e56aa02015-11-02 13:00:03 -08001407void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001408 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001410 getHwComposer().setVsyncEnabled(disp,
1411 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001412}
1413
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001415void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417 // Clear the drawing state so that the logic inside of
1418 // handleTransactionLocked will fire. It will determine the delta between
1419 // mCurrentState and mDrawingState and re-apply all changes when we make the
1420 // transition.
1421 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001422 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423 mDisplays.clear();
1424}
1425
Steven Thomas050b2c82017-03-06 11:45:16 -08001426void SurfaceFlinger::updateVrFlinger() {
1427 if (!mVrFlinger)
1428 return;
1429 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001430 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001431 return;
1432 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433
David Sodman105b7dc2017-11-04 20:28:14 -07001434 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 ALOGE("Vr flinger is only supported for remote hardware composer"
1436 " service connections. Ignoring request to transition to vr"
1437 " flinger.");
1438 mVrFlingerRequestsDisplay = false;
1439 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001440 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001442 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 int currentDisplayPowerMode = getDisplayDeviceLocked(
1445 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450
Steven Thomasb02664d2017-07-26 18:48:28 -07001451 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001452 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001453 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1454 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001455 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456
David Sodman105b7dc2017-11-04 20:28:14 -07001457 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1458 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001459
1460 if (vrFlingerRequestsDisplay) {
1461 mVrFlinger->GrantDisplayOwnership();
1462 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465
1466 mVisibleRegionsDirty = true;
1467 invalidateHwcGeometry();
1468
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001469 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1471 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1472 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001473
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001475 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 const nsecs_t period = activeConfig->getVsyncPeriod();
1477 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001478
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 // Use phase of 0 since phase is not known.
1480 // Use latency of 0, which will snap to the ideal latency.
1481 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001482
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483 android_atomic_or(1, &mRepaintEverything);
1484 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485}
1486
Mathias Agopian4fec8732012-06-29 14:12:52 -07001487void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001488 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001491 bool frameMissed = !mHadClientComposition &&
1492 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 (mPreviousPresentFence->getSignalTime() ==
1494 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001495 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001496 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001497 mTimeStats.incrementMissedFrames();
1498 if (mPropagateBackpressure) {
1499 signalLayerUpdate();
1500 break;
1501 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001502 }
Dan Stoza50182882016-07-08 12:02:20 -07001503
Steven Thomas050b2c82017-03-06 11:45:16 -08001504 // Now that we're going to make it to the handleMessageTransaction()
1505 // call below it's safe to call updateVrFlinger(), which will
1506 // potentially trigger a display handoff.
1507 updateVrFlinger();
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 bool refreshNeeded = handleMessageTransaction();
1510 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001511 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001513 // Signal a refresh if a transaction modified the window state,
1514 // a new buffer was latched, or if HWC has requested a full
1515 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516 signalRefresh();
1517 }
1518 break;
1519 }
1520 case MessageQueue::REFRESH: {
1521 handleMessageRefresh();
1522 break;
1523 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001524 }
1525}
1526
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001528 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001530 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001531 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001532 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001533 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534}
1535
Dan Stoza6b9454d2014-11-07 16:00:59 -08001536bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001537 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001538 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001539}
1540
1541void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001543
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001544 mRefreshPending = false;
1545
Pablo Ceballos40845df2016-01-25 17:41:15 -08001546 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001547
Brian Andersond6927fb2016-07-23 23:37:30 -07001548 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001549 rebuildLayerStacks();
1550 setUpHWComposer();
1551 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001552 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001553 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001554 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001555 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001556
David Sodman105b7dc2017-11-04 20:28:14 -07001557 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001558
1559 mHadClientComposition = false;
1560 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1561 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1562 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001563 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001564 }
Dan Stoza2713c302018-03-28 17:07:36 -07001565 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001566
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570void SurfaceFlinger::doDebugFlashRegions()
1571{
1572 // is debugging enabled
1573 if (CC_LIKELY(!mDebugRegion))
1574 return;
1575
1576 const bool repaintEverything = mRepaintEverything;
1577 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1578 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001579 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580 // transform the dirty region into this screen's coordinate space
1581 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1582 if (!dirtyRegion.isEmpty()) {
1583 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001584 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585
1586 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001588 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001589 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1590
Mathias Agopianda27af92012-09-13 18:17:13 -07001591 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 }
1593 }
1594 }
1595
1596 postFramebuffer();
1597
1598 if (mDebugRegion > 1) {
1599 usleep(mDebugRegion * 1000);
1600 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001601
Dan Stoza9e56aa02015-11-02 13:00:03 -08001602 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001603 auto& displayDevice = mDisplays[displayId];
1604 if (!displayDevice->isDisplayOn()) {
1605 continue;
1606 }
1607
David Sodman105b7dc2017-11-04 20:28:14 -07001608 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1609 ALOGE_IF(result != NO_ERROR,
1610 "prepareFrame for display %zd failed:"
1611 " %d (%s)",
1612 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001613 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614}
1615
Adrian Roos1e1a1282017-11-01 19:05:31 +01001616void SurfaceFlinger::doTracing(const char* where) {
1617 ATRACE_CALL();
1618 ATRACE_NAME(where);
1619 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001620 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001621 }
1622}
1623
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001624void SurfaceFlinger::logLayerStats() {
1625 ATRACE_CALL();
1626 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1627 int32_t hwcId = -1;
1628 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1629 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1630 if (displayDevice->isPrimary()) {
1631 hwcId = displayDevice->getHwcDisplayId();
1632 break;
1633 }
1634 }
1635 if (hwcId < 0) {
1636 ALOGE("LayerStats: Hmmm, no primary display?");
1637 return;
1638 }
1639 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1640 }
1641}
1642
Brian Andersond6927fb2016-07-23 23:37:30 -07001643void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001644{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001645 ATRACE_CALL();
1646 ALOGV("preComposition");
1647
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001649 mDrawingState.traverseInZOrder([&](Layer* layer) {
1650 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001651 needExtraInvalidate = true;
1652 }
Robert Carr2047fae2016-11-28 14:09:09 -08001653 });
1654
Mathias Agopiancd60f992012-08-16 16:28:27 -07001655 if (needExtraInvalidate) {
1656 signalLayerUpdate();
1657 }
1658}
1659
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660void SurfaceFlinger::updateCompositorTiming(
1661 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1662 std::shared_ptr<FenceTime>& presentFenceTime) {
1663 // Update queue of past composite+present times and determine the
1664 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001665 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001667 while (!getBE().mCompositePresentTimes.empty()) {
1668 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 // Cached values should have been updated before calling this method,
1670 // which helps avoid duplicate syscalls.
1671 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1672 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1673 break;
1674 }
1675 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001676 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 }
1678
1679 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001680 while (getBE().mCompositePresentTimes.size() > 16) {
1681 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 }
1683
Brian Andersond0010582017-03-07 13:20:31 -08001684 setCompositorTimingSnapped(
1685 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1686}
1687
1688void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1689 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 // Integer division and modulo round toward 0 not -inf, so we need to
1691 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001692 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001693 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1694 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1695
Brian Andersond0010582017-03-07 13:20:31 -08001696 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1697 if (idealLatency <= 0) {
1698 idealLatency = vsyncInterval;
1699 }
1700
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 // Snap the latency to a value that removes scheduling jitter from the
1702 // composition and present times, which often have >1ms of jitter.
1703 // Reducing jitter is important if an app attempts to extrapolate
1704 // something (such as user input) to an accurate diasplay time.
1705 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1706 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001707 nsecs_t bias = vsyncInterval / 2;
1708 int64_t extraVsyncs =
1709 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1710 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1711 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712
David Sodman99974d22017-11-28 12:04:33 -08001713 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1714 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1715 getBE().mCompositorTiming.interval = vsyncInterval;
1716 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717}
1718
1719void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001720{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721 ATRACE_CALL();
1722 ALOGV("postComposition");
1723
Brian Anderson3546a3f2016-07-14 11:51:14 -07001724 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001725 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001726 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001727 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001728 }
1729
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730 // |mStateLock| not needed as we are on the main thread
1731 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001734 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001735 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001736 glCompositionDoneFenceTime =
1737 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001738 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 } else {
1740 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1741 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001742
David Sodman73beded2017-11-15 11:56:06 -08001743 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001744 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001745 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001746 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1749 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1750
1751 // We use the refreshStartTime which might be sampled a little later than
1752 // when we started doing work for this frame, but that should be okay
1753 // since updateCompositorTiming has snapping logic.
1754 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001755 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001756 CompositorTiming compositorTiming;
1757 {
David Sodman99974d22017-11-28 12:04:33 -08001758 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1759 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001760 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761
Robert Carr2047fae2016-11-28 14:09:09 -08001762 mDrawingState.traverseInZOrder([&](Layer* layer) {
1763 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001764 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001765 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001766 recordBufferingStats(layer->getName().string(),
1767 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001768 }
Robert Carr2047fae2016-11-28 14:09:09 -08001769 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001770
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001771 if (presentFenceTime->isValid()) {
1772 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001773 enableHardwareVsync();
1774 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001775 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001776 }
1777 }
1778
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001779 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001780 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001781 enableHardwareVsync();
1782 }
1783 }
1784
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001785 if (mAnimCompositionPending) {
1786 mAnimCompositionPending = false;
1787
Brian Anderson4e606e32017-03-16 15:34:57 -07001788 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001789 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001790 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001791 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001792 // The HWC doesn't support present fences, so use the refresh
1793 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001794 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001795 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001796 mAnimFrameTracker.setActualPresentTime(presentTime);
1797 }
1798 mAnimFrameTracker.advanceFrame();
1799 }
Dan Stozab90cf072015-03-05 11:05:59 -08001800
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001801 mTimeStats.incrementTotalFrames();
1802 if (mHadClientComposition) {
1803 mTimeStats.incrementClientCompositionFrames();
1804 }
1805
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001806 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1807 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001808 return;
1809 }
1810
1811 nsecs_t currentTime = systemTime();
1812 if (mHasPoweredOff) {
1813 mHasPoweredOff = false;
1814 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001815 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001817 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1818 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001819 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001820 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001821 }
David Sodman4a36e932017-11-07 14:29:47 -08001822 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001823 }
David Sodman4a36e932017-11-07 14:29:47 -08001824 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825}
1826
1827void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001828 ATRACE_CALL();
1829 ALOGV("rebuildLayerStacks");
1830
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001833 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001834 mVisibleRegionsDirty = false;
1835 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001836
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1838 Region opaqueRegion;
1839 Region dirtyRegion;
1840 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001841 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001842 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1843 const Transform& tr(displayDevice->getTransform());
1844 const Rect bounds(displayDevice->getBounds());
1845 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001846 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001847
Jeff Sharkey76488112017-02-27 14:15:18 -07001848 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001849 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001850 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1851 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001852 Region drawRegion(tr.transform(
1853 layer->visibleNonTransparentRegion));
1854 drawRegion.andSelf(bounds);
1855 if (!drawRegion.isEmpty()) {
1856 layersSortedByZ.add(layer);
1857 } else {
1858 // Clear out the HWC layer if this layer was
1859 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001860 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001861 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001862 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001863 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001864 // WM changes displayDevice->layerStack upon sleep/awake.
1865 // Here we make sure we delete the HWC layers even if
1866 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001867 hwcLayerDestroyed = layer->destroyHwcLayer(
1868 displayDevice->getHwcDisplayId());
1869 }
1870
1871 // If a layer is not going to get a release fence because
1872 // it is invisible, but it is also going to release its
1873 // old buffer, add it to the list of layers needing
1874 // fences.
1875 if (hwcLayerDestroyed) {
1876 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1877 mLayersWithQueuedFrames.cend(), layer);
1878 if (found != mLayersWithQueuedFrames.cend()) {
1879 layersNeedingFences.add(layer);
1880 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001881 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001882 });
1883 }
1884 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001885 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001886 displayDevice->undefinedRegion.set(bounds);
1887 displayDevice->undefinedRegion.subtractSelf(
1888 tr.transform(opaqueRegion));
1889 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001890 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001891 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001893
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001894// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001896// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897// - Dataspace::DISPLAY_P3
1898// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001899// The returned HDR data space is one of
1900// - Dataspace::UNKNOWN
1901// - Dataspace::BT2020_HLG
1902// - Dataspace::BT2020_PQ
1903Dataspace SurfaceFlinger::getBestDataspace(
1904 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1905 Dataspace bestDataSpace = Dataspace::SRGB;
1906 *outHdrDataSpace = Dataspace::UNKNOWN;
1907
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07001909 switch (layer->getDrawingState().dataSpace) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001910 case Dataspace::V0_SCRGB:
1911 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001912 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001913 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001914 case Dataspace::DISPLAY_P3:
1915 if (bestDataSpace == Dataspace::SRGB) {
1916 bestDataSpace = Dataspace::DISPLAY_P3;
1917 }
1918 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 case Dataspace::BT2020_PQ:
1920 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001921 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001923 case Dataspace::BT2020_HLG:
1924 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001925 // When there's mixed PQ content and HLG content, we set the HDR
1926 // data space to be BT2020_PQ and convert HLG to PQ.
1927 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1928 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001929 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930 break;
1931 default:
1932 break;
1933 }
Romain Guy54f154a2017-10-24 21:40:32 +01001934 }
1935
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001936 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937}
1938
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001941 ColorMode* outMode, Dataspace* outDataSpace,
1942 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001943 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1944 *outMode = ColorMode::NATIVE;
1945 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001946 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001947 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001948 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001949
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001950 Dataspace hdrDataSpace;
1951 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1952
1953 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1954 // Hardware composer can handle BT2100 ColorMode only when
1955 // - colorimetrical tone mapping is supported, or
1956 // - Auto mode is turned on and enhanced tone mapping is supported.
1957 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1958 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1959 displayDevice->hasBT2100PQEnhanceSupport())) {
1960 *outMode = ColorMode::BT2100_PQ;
1961 *outDataSpace = Dataspace::BT2020_PQ;
1962 } else if (displayDevice->hasHDR10Support()) {
1963 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1964 hdrDataSpace = Dataspace::UNKNOWN;
1965 } else {
1966 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001967 *outMode = ColorMode::DISPLAY_P3;
1968 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001969 }
1970 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1971 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1972 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1973 displayDevice->hasBT2100HLGEnhanceSupport())) {
1974 *outMode = ColorMode::BT2100_HLG;
1975 *outDataSpace = Dataspace::BT2020_HLG;
1976 } else if (displayDevice->hasHLGSupport()) {
1977 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1978 hdrDataSpace = Dataspace::UNKNOWN;
1979 } else {
1980 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1981 *outMode = ColorMode::DISPLAY_P3;
1982 *outDataSpace = Dataspace::DISPLAY_P3;
1983 }
1984 }
1985
1986 // At this point, there's no HDR layer.
1987 if (hdrDataSpace == Dataspace::UNKNOWN) {
1988 switch (bestDataSpace) {
1989 case Dataspace::DISPLAY_P3:
1990 case Dataspace::V0_SCRGB_LINEAR:
1991 *outMode = ColorMode::DISPLAY_P3;
1992 *outDataSpace = Dataspace::DISPLAY_P3;
1993 break;
1994 default:
1995 *outMode = ColorMode::SRGB;
1996 *outDataSpace = Dataspace::SRGB;
1997 break;
1998 }
1999 }
2000 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
2001}
2002
2003RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
2004 ColorMode colorMode) const {
2005 // Native Mode means the display is not color managed, and whichever
2006 // render intent is picked doesn't matter, thus return
2007 // RenderIntent::COLORIMETRIC as default here.
2008 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2009 return RenderIntent::COLORIMETRIC;
2010 }
2011
2012 // In Auto Color Mode, we want to strech to panel color space, right now
2013 // only the built-in display supports it.
2014 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2015 mBuiltinDisplaySupportsEnhance &&
2016 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
2017 switch (colorMode) {
2018 case ColorMode::DISPLAY_P3:
2019 case ColorMode::SRGB:
2020 return RenderIntent::ENHANCE;
2021 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2022 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
2023 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
2024 case ColorMode::BT2100_PQ:
2025 return displayDevice->hasBT2100PQEnhanceSupport() ?
2026 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2027 case ColorMode::BT2100_HLG:
2028 return displayDevice->hasBT2100HLGEnhanceSupport() ?
2029 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2030 // This statement shouldn't be reached, switch cases will always
2031 // cover all possible ColorMode returned by pickColorMode.
2032 default:
2033 return RenderIntent::COLORIMETRIC;
2034 }
2035 }
2036
2037 // Either enhance is not supported or we are in natural mode.
2038
2039 // Natural Mode means it's color managed and the color must be right,
2040 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2041 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2042 switch (colorMode) {
2043 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2044 // when TONE_MAP_COLORIMETRIC is supported.
2045 case ColorMode::BT2100_PQ:
2046 case ColorMode::BT2100_HLG:
2047 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002048 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002049 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002050 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002051}
2052
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 ATRACE_CALL();
2055 ALOGV("setUpHWComposer");
2056
Jesse Hall028dc8f2013-08-20 16:35:32 -07002057 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002058 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002059 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2060 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2061
2062 // If nothing has changed (!dirty), don't recompose.
2063 // If something changed, but we don't currently have any visible layers,
2064 // and didn't when we last did a composition, then skip it this time.
2065 // The second rule does two things:
2066 // - When all layers are removed from a display, we'll emit one black
2067 // frame, then nothing more until we get new layers.
2068 // - When a display is created with a private layer stack, we won't
2069 // emit any black frames until a layer is added to the layer stack.
2070 bool mustRecompose = dirty && !(empty && wasEmpty);
2071
2072 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2073 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2074 mustRecompose ? "doing" : "skipping",
2075 dirty ? "+" : "-",
2076 empty ? "+" : "-",
2077 wasEmpty ? "+" : "-");
2078
Dan Stoza71433162014-02-04 16:22:36 -08002079 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002080
2081 if (mustRecompose) {
2082 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2083 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002084 }
2085
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 // build the h/w work list
2087 if (CC_UNLIKELY(mGeometryInvalid)) {
2088 mGeometryInvalid = false;
2089 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2090 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2091 const auto hwcId = displayDevice->getHwcDisplayId();
2092 if (hwcId >= 0) {
2093 const Vector<sp<Layer>>& currentLayers(
2094 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002095 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002096 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002098 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002101 }
2102 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002103
Robert Carrae060832016-11-28 10:51:00 -08002104 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002105 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002107 }
2108 }
2109 }
2110 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 }
Riley Andrews03414a12014-07-01 14:22:59 -07002112
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 // Set the per-frame data
2114 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2115 auto& displayDevice = mDisplays[displayId];
2116 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002117
Dan Stoza9e56aa02015-11-02 13:00:03 -08002118 if (hwcId < 0) {
2119 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002120 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002121 if (mDrawingState.colorMatrixChanged) {
2122 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2123 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002124 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2125 "display %zd: %d", displayId, result);
2126 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07002128 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_PQ ||
2129 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002130 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002131 layer->forceClientComposition(hwcId);
2132 }
Chia-I Wue1043322018-05-17 13:24:48 -07002133 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_HLG ||
2134 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002135 !displayDevice->hasHLGSupport()) {
2136 layer->forceClientComposition(hwcId);
2137 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002138
chaviwc9232ed2017-11-14 15:31:15 -08002139 if (layer->getForceClientComposition(hwcId)) {
2140 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2141 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2142 continue;
2143 }
2144
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 layer->setPerFrameData(displayDevice);
2146 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002147
2148 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002149 ColorMode colorMode;
2150 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002151 RenderIntent renderIntent;
2152 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2153 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002154 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 }
2156
Chia-I Wu28f320b2018-05-03 11:02:56 -07002157 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002158
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002160 auto& displayDevice = mDisplays[displayId];
2161 if (!displayDevice->isDisplayOn()) {
2162 continue;
2163 }
2164
David Sodman105b7dc2017-11-04 20:28:14 -07002165 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2167 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002168 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002169}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002170
Mathias Agopiancd60f992012-08-16 16:28:27 -07002171void SurfaceFlinger::doComposition() {
2172 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 ALOGV("doComposition");
2174
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002175 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002176 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002177 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002178 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002179 // transform the dirty region into this screen's coordinate space
2180 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002181
2182 // repaint the framebuffer (if needed)
2183 doDisplayComposition(hw, dirtyRegion);
2184
Mathias Agopiancd60f992012-08-16 16:28:27 -07002185 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002186 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002187 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002188 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002189 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190}
2191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192void SurfaceFlinger::postFramebuffer()
2193{
Mathias Agopian841cde52012-03-01 15:44:37 -08002194 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002196
Mathias Agopiana44b0412011-10-16 18:46:35 -07002197 const nsecs_t now = systemTime();
2198 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002199
Dan Stoza9e56aa02015-11-02 13:00:03 -08002200 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2201 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002202 if (!displayDevice->isDisplayOn()) {
2203 continue;
2204 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 const auto hwcId = displayDevice->getHwcDisplayId();
2206 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002207 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002208 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002209 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002210 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002212 // The layer buffer from the previous frame (if any) is released
2213 // by HWC only when the release fence from this frame (if any) is
2214 // signaled. Always get the release fence from HWC first.
2215 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002216 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002217
2218 // If the layer was client composited in the previous frame, we
2219 // need to merge with the previous client target acquire fence.
2220 // Since we do not track that, always merge with the current
2221 // client target acquire fence when it is available, even though
2222 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002223 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002224 releaseFence = Fence::merge("LayerRelease", releaseFence,
2225 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002226 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002227
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 layer->onLayerDisplayed(releaseFence);
2229 }
Chia-I Wu83806892017-11-16 10:50:20 -08002230
2231 // We've got a list of layers needing fences, that are disjoint with
2232 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2233 // supply them with the present fence.
2234 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002235 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002236 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2237 layer->onLayerDisplayed(presentFence);
2238 }
2239 }
2240
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002242 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002243 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002244 }
2245
Mathias Agopiana44b0412011-10-16 18:46:35 -07002246 mLastSwapBufferTime = systemTime() - now;
2247 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002248
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002249 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002250 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2251 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2252 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2253 logFrameStats();
2254 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256}
2257
Mathias Agopian87baae12012-07-31 12:38:26 -07002258void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259{
Mathias Agopian841cde52012-03-01 15:44:37 -08002260 ATRACE_CALL();
2261
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002262 // here we keep a copy of the drawing state (that is the state that's
2263 // going to be overwritten by handleTransactionLocked()) outside of
2264 // mStateLock so that the side-effects of the State assignment
2265 // don't happen with mStateLock held (which can cause deadlocks).
2266 State drawingState(mDrawingState);
2267
Mathias Agopianca4d3602011-05-19 15:38:14 -07002268 Mutex::Autolock _l(mStateLock);
2269 const nsecs_t now = systemTime();
2270 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002271
Mathias Agopianca4d3602011-05-19 15:38:14 -07002272 // Here we're guaranteed that some transaction flags are set
2273 // so we can call handleTransactionLocked() unconditionally.
2274 // We call getTransactionFlags(), which will also clear the flags,
2275 // with mStateLock held to guarantee that mCurrentState won't change
2276 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002277
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002278 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002279 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002280 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002281
Mathias Agopianca4d3602011-05-19 15:38:14 -07002282 mLastTransactionTime = systemTime() - now;
2283 mDebugInTransaction = 0;
2284 invalidateHwcGeometry();
2285 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002286}
2287
Lloyd Pique715a2c12017-12-14 17:18:08 -08002288DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002289 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002290 // Figure out whether the event is for the primary display or an
2291 // external display by matching the Hwc display id against one for a
2292 // connected display. If we did not find a match, we then check what
2293 // displays are not already connected to determine the type. If we don't
2294 // have a connected primary display, we assume the new display is meant to
2295 // be the primary display, and then if we don't have an external display,
2296 // we assume it is that.
2297 const auto primaryDisplayId =
2298 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2299 const auto externalDisplayId =
2300 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2301 if (primaryDisplayId && primaryDisplayId == display) {
2302 return DisplayDevice::DISPLAY_PRIMARY;
2303 } else if (externalDisplayId && externalDisplayId == display) {
2304 return DisplayDevice::DISPLAY_EXTERNAL;
2305 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2306 return DisplayDevice::DISPLAY_PRIMARY;
2307 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2308 return DisplayDevice::DISPLAY_EXTERNAL;
2309 }
2310
2311 return DisplayDevice::DISPLAY_ID_INVALID;
2312}
2313
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2315 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002316 auto displayType = determineDisplayType(event.display, event.connection);
2317 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2318 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2319 continue;
2320 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002321
2322 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2323 ALOGE("External displays are not supported by the vr hardware composer.");
2324 continue;
2325 }
2326
Lloyd Pique715a2c12017-12-14 17:18:08 -08002327 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002328
2329 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002330 if (!mBuiltinDisplays[displayType].get()) {
2331 ALOGV("Creating built in display %d", displayType);
2332 mBuiltinDisplays[displayType] = new BBinder();
2333 // All non-virtual displays are currently considered secure.
2334 DisplayDeviceState info(displayType, true);
2335 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2336 "Built-in Screen" : "External Screen";
2337 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002338 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002339 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002341 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342
Lloyd Piquefcd86612017-12-14 17:15:36 -08002343 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2344 if (idx >= 0) {
2345 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002346 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002347 mCurrentState.displays.removeItemsAt(idx);
2348 }
2349 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350 }
2351
2352 processDisplayChangesLocked();
2353 }
2354
2355 mPendingHotplugEvents.clear();
2356}
2357
Lloyd Pique09594832018-01-22 17:48:03 -08002358sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2359 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2360 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002362 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2363
Lloyd Pique09594832018-01-22 17:48:03 -08002364 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002365 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002366 for (ColorMode colorMode : modes) {
2367 switch (colorMode) {
2368 case ColorMode::DISPLAY_P3:
2369 case ColorMode::ADOBE_RGB:
2370 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002372 break;
2373 default:
2374 break;
2375 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376
2377 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2378 colorMode);
2379 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2380 for (auto intent : renderIntents) {
2381 if (intent == RenderIntent::ENHANCE) {
2382 mBuiltinDisplaySupportsEnhance = true;
2383 break;
2384 }
2385 }
2386 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002387
2388 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2389 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2390 }
Lloyd Pique09594832018-01-22 17:48:03 -08002391 }
2392 }
2393
Peiyong Lin62665892018-04-16 11:07:44 -07002394 HdrCapabilities hdrCapabilities;
2395 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002396
2397 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2398 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2399
2400 /*
2401 * Create our display's surface
2402 */
2403 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2404 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2405 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2406 renderSurface->setNativeWindow(nativeWindow.get());
2407 const int displayWidth = renderSurface->queryWidth();
2408 const int displayHeight = renderSurface->queryHeight();
2409
2410 // Make sure that composition can never be stalled by a virtual display
2411 // consumer that isn't processing buffers fast enough. We have to do this
2412 // in two places:
2413 // * Here, in case the display is composed entirely by HWC.
2414 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2415 // window's swap interval in eglMakeCurrent, so they'll override the
2416 // interval we set here.
2417 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2418 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2419 }
2420
2421 // virtual displays are always considered enabled
2422 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2423 : HWC_POWER_MODE_OFF;
2424
2425 sp<DisplayDevice> hw =
2426 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2427 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002428 hasWideColorGamut, hdrCapabilities,
2429 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002430 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002431
2432 if (maxFrameBufferAcquiredBuffers >= 3) {
2433 nativeWindowSurface->preallocateBuffers();
2434 }
2435
2436 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002437 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2438 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002439 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002440 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002441 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002442 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2443 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002444 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2445 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2446 }
Lloyd Pique09594832018-01-22 17:48:03 -08002447 hw->setLayerStack(state.layerStack);
2448 hw->setProjection(state.orientation, state.viewport, state.frame);
2449 hw->setDisplayName(state.displayName);
2450
2451 return hw;
2452}
2453
Lloyd Pique347200f2017-12-14 17:00:15 -08002454void SurfaceFlinger::processDisplayChangesLocked() {
2455 // here we take advantage of Vector's copy-on-write semantics to
2456 // improve performance by skipping the transaction entirely when
2457 // know that the lists are identical
2458 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2459 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2460 if (!curr.isIdenticalTo(draw)) {
2461 mVisibleRegionsDirty = true;
2462 const size_t cc = curr.size();
2463 size_t dc = draw.size();
2464
2465 // find the displays that were removed
2466 // (ie: in drawing state but not in current state)
2467 // also handle displays that changed
2468 // (ie: displays that are in both lists)
2469 for (size_t i = 0; i < dc;) {
2470 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2471 if (j < 0) {
2472 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002473 // Call makeCurrent() on the primary display so we can
2474 // be sure that nothing associated with this display
2475 // is current.
2476 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2477 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2478 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2479 if (hw != nullptr) hw->disconnect(getHwComposer());
2480 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2481 mEventThread->onHotplugReceived(draw[i].type, false);
2482 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002483 } else {
2484 // this display is in both lists. see if something changed.
2485 const DisplayDeviceState& state(curr[j]);
2486 const wp<IBinder>& display(curr.keyAt(j));
2487 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2488 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2489 if (state_binder != draw_binder) {
2490 // changing the surface is like destroying and
2491 // recreating the DisplayDevice, so we just remove it
2492 // from the drawing state, so that it get re-added
2493 // below.
2494 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2495 if (hw != nullptr) hw->disconnect(getHwComposer());
2496 mDisplays.removeItem(display);
2497 mDrawingState.displays.removeItemsAt(i);
2498 dc--;
2499 // at this point we must loop to the next item
2500 continue;
2501 }
2502
2503 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2504 if (disp != nullptr) {
2505 if (state.layerStack != draw[i].layerStack) {
2506 disp->setLayerStack(state.layerStack);
2507 }
2508 if ((state.orientation != draw[i].orientation) ||
2509 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2510 disp->setProjection(state.orientation, state.viewport, state.frame);
2511 }
2512 if (state.width != draw[i].width || state.height != draw[i].height) {
2513 disp->setDisplaySize(state.width, state.height);
2514 }
2515 }
2516 }
2517 ++i;
2518 }
2519
2520 // find displays that were added
2521 // (ie: in current state but not in drawing state)
2522 for (size_t i = 0; i < cc; i++) {
2523 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2524 const DisplayDeviceState& state(curr[i]);
2525
2526 sp<DisplaySurface> dispSurface;
2527 sp<IGraphicBufferProducer> producer;
2528 sp<IGraphicBufferProducer> bqProducer;
2529 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002530 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002531
2532 int32_t hwcId = -1;
2533 if (state.isVirtualDisplay()) {
2534 // Virtual displays without a surface are dormant:
2535 // they have external state (layer stack, projection,
2536 // etc.) but no internal state (i.e. a DisplayDevice).
2537 if (state.surface != nullptr) {
2538 // Allow VR composer to use virtual displays.
2539 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2540 int width = 0;
2541 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2542 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2543 int height = 0;
2544 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2545 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2546 int intFormat = 0;
2547 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2548 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002549 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002550
2551 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2552 }
2553
2554 // TODO: Plumb requested format back up to consumer
2555
2556 sp<VirtualDisplaySurface> vds =
2557 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2558 bqProducer, bqConsumer,
2559 state.displayName);
2560
2561 dispSurface = vds;
2562 producer = vds;
2563 }
2564 } else {
2565 ALOGE_IF(state.surface != nullptr,
2566 "adding a supported display, but rendering "
2567 "surface is provided (%p), ignoring it",
2568 state.surface.get());
2569
2570 hwcId = state.type;
2571 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2572 producer = bqProducer;
2573 }
2574
2575 const wp<IBinder>& display(curr.keyAt(i));
2576 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002577 mDisplays.add(display,
2578 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2579 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 if (!state.isVirtualDisplay()) {
2581 mEventThread->onHotplugReceived(state.type, true);
2582 }
2583 }
2584 }
2585 }
2586 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587
2588 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002589}
2590
Mathias Agopian87baae12012-07-31 12:38:26 -07002591void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002592{
Dan Stoza7dde5992015-05-22 09:51:44 -07002593 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002594 mCurrentState.traverseInZOrder([](Layer* layer) {
2595 layer->notifyAvailableFrames();
2596 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 /*
2599 * Traversal of the children
2600 * (perform the transaction for each of them if needed)
2601 */
2602
Mathias Agopian3559b072012-08-15 13:46:03 -07002603 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002604 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002606 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
2608 const uint32_t flags = layer->doTransaction(0);
2609 if (flags & Layer::eVisibleRegion)
2610 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002611 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 }
2613
2614 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002615 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616 */
2617
Mathias Agopiane57f2922012-08-09 16:29:12 -07002618 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002620 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002624 // The transform hint might have changed for some layers
2625 // (either because a display has changed, or because a layer
2626 // as changed).
2627 //
2628 // Walk through all the layers in currentLayers,
2629 // and update their transform hint.
2630 //
2631 // If a layer is visible only on a single display, then that
2632 // display is used to calculate the hint, otherwise we use the
2633 // default display.
2634 //
2635 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2636 // the hint is set before we acquire a buffer from the surface texture.
2637 //
2638 // NOTE: layer transactions have taken place already, so we use their
2639 // drawing state. However, SurfaceFlinger's own transaction has not
2640 // happened yet, so we must use the current state layer list
2641 // (soon to become the drawing state list).
2642 //
2643 sp<const DisplayDevice> disp;
2644 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002645 bool first = true;
2646 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002647 // NOTE: we rely on the fact that layers are sorted by
2648 // layerStack first (so we don't have to traverse the list
2649 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002651 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002652 currentlayerStack = layerStack;
2653 // figure out if this layerstack is mirrored
2654 // (more than one display) if so, pick the default display,
2655 // if not, pick the only display it's on.
2656 disp.clear();
2657 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2658 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002659 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002660 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002661 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002662 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002663 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002664 break;
2665 }
2666 }
2667 }
2668 }
Chet Haase91d25932013-04-11 15:24:55 -07002669
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002670 if (disp == nullptr) {
2671 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2672 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002673
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002674 // could be null when this layer is using a layerStack
2675 // that is not visible on any display. Also can occur at
2676 // screen off/on times.
2677 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002678 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002679
2680 // disp can be null if there is no display available at all to get
2681 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002682 if (disp != nullptr) {
2683 layer->updateTransformHint(disp);
2684 }
Robert Carr2047fae2016-11-28 14:09:09 -08002685
2686 first = false;
2687 });
Mathias Agopian84300952012-11-21 16:02:13 -08002688 }
2689
2690
Mathias Agopian3559b072012-08-15 13:46:03 -07002691 /*
2692 * Perform our own transaction if needed
2693 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694
2695 if (mLayersAdded) {
2696 mLayersAdded = false;
2697 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002698 mVisibleRegionsDirty = true;
2699 }
2700
2701 // some layers might have been removed, so
2702 // we need to update the regions they're exposing.
2703 if (mLayersRemoved) {
2704 mLayersRemoved = false;
2705 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002706 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002707 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002708 // this layer is not visible anymore
2709 // TODO: we could traverse the tree from front to back and
2710 // compute the actual visible region
2711 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 Region visibleReg;
2713 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002714 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002715 }
Robert Carr2047fae2016-11-28 14:09:09 -08002716 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 }
2718
2719 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002720
2721 updateCursorAsync();
2722}
2723
2724void SurfaceFlinger::updateCursorAsync()
2725{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2727 auto& displayDevice = mDisplays[displayId];
2728 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002729 continue;
2730 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731
2732 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2733 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002734 }
2735 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002736}
2737
2738void SurfaceFlinger::commitTransaction()
2739{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002740 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 for (const auto& l : mLayersPendingRemoval) {
2743 recordBufferingStats(l->getName().string(),
2744 l->getOccupancyHistory(true));
2745 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 }
2747 mLayersPendingRemoval.clear();
2748 }
2749
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002750 // If this transaction is part of a window animation then the next frame
2751 // we composite should be considered an animation as well.
2752 mAnimCompositionPending = mAnimTransactionPending;
2753
Mathias Agopian4fec8732012-06-29 14:12:52 -07002754 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002755 // clear the "changed" flags in current state
2756 mCurrentState.colorMatrixChanged = false;
2757
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758 mDrawingState.traverseInZOrder([](Layer* layer) {
2759 layer->commitChildList();
2760 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002761 mTransactionPending = false;
2762 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002763 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764}
2765
Chia-I Wuab0c3192017-08-01 11:29:00 -07002766void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002767 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768{
Mathias Agopian841cde52012-03-01 15:44:37 -08002769 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 Region aboveOpaqueLayers;
2773 Region aboveCoveredLayers;
2774 Region dirty;
2775
Mathias Agopian87baae12012-07-31 12:38:26 -07002776 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002780 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Jesse Hall01e29052013-02-19 16:13:35 -08002782 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002783 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002784 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002785
Mathias Agopianab028732010-03-16 16:41:46 -07002786 /*
2787 * opaqueRegion: area of a surface that is fully opaque.
2788 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002790
2791 /*
2792 * visibleRegion: area of a surface that is visible on screen
2793 * and not fully transparent. This is essentially the layer's
2794 * footprint minus the opaque regions above it.
2795 * Areas covered by a translucent surface are considered visible.
2796 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002798
2799 /*
2800 * coveredRegion: area of a surface that is covered by all
2801 * visible regions above it (which includes the translucent areas).
2802 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002804
Jesse Halla8026d22012-09-25 13:25:04 -07002805 /*
2806 * transparentRegion: area of a surface that is hinted to be completely
2807 * transparent. This is only used to tell when the layer has no visible
2808 * non-transparent regions and can be removed from the layer list. It
2809 * does not affect the visibleRegion of this layer or any layers
2810 * beneath it. The hint may not be correct if apps don't respect the
2811 * SurfaceView restrictions (which, sadly, some don't).
2812 */
2813 Region transparentRegion;
2814
Mathias Agopianab028732010-03-16 16:41:46 -07002815
2816 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002817 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002818 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002821 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002822 if (!visibleRegion.isEmpty()) {
2823 // Remove the transparent area from the visible region
2824 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002825 if (tr.preserveRects()) {
2826 // transform the transparent region
2827 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002828 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002829 // transformation too complex, can't do the
2830 // transparent region optimization.
2831 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002832 }
Mathias Agopianab028732010-03-16 16:41:46 -07002833 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
Mathias Agopianab028732010-03-16 16:41:46 -07002835 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002836 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002837 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002838 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2839 // the opaque region is the layer's footprint
2840 opaqueRegion = visibleRegion;
2841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 }
2843 }
2844
Robert Carre5f4f692018-01-12 13:12:28 -08002845 if (visibleRegion.isEmpty()) {
2846 layer->clearVisibilityRegions();
2847 return;
2848 }
2849
Mathias Agopianab028732010-03-16 16:41:46 -07002850 // Clip the covered region to the visible region
2851 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2852
2853 // Update aboveCoveredLayers for next (lower) layer
2854 aboveCoveredLayers.orSelf(visibleRegion);
2855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 // subtract the opaque region covered by the layers above us
2857 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858
2859 // compute this layer's dirty region
2860 if (layer->contentDirty) {
2861 // we need to invalidate the whole region
2862 dirty = visibleRegion;
2863 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 layer->contentDirty = false;
2866 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002867 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002868 * the exposed region consists of two components:
2869 * 1) what's VISIBLE now and was COVERED before
2870 * 2) what's EXPOSED now less what was EXPOSED before
2871 *
2872 * note that (1) is conservative, we start with the whole
2873 * visible region but only keep what used to be covered by
2874 * something -- which mean it may have been exposed.
2875 *
2876 * (2) handles areas that were not covered by anything but got
2877 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002878 */
Mathias Agopianab028732010-03-16 16:41:46 -07002879 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880 const Region oldVisibleRegion = layer->visibleRegion;
2881 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002882 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2883 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 }
2885 dirty.subtractSelf(aboveOpaqueLayers);
2886
2887 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002888 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889
Mathias Agopianab028732010-03-16 16:41:46 -07002890 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002892
Jesse Halla8026d22012-09-25 13:25:04 -07002893 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 layer->setVisibleRegion(visibleRegion);
2895 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002896 layer->setVisibleNonTransparentRegion(
2897 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002898 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899
Mathias Agopian87baae12012-07-31 12:38:26 -07002900 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901}
2902
Chia-I Wuab0c3192017-08-01 11:29:00 -07002903void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002904 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002905 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002906 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002907 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002908 }
2909 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002910}
2911
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 ALOGV("handlePageFlip");
2915
Brian Andersond6927fb2016-07-23 23:37:30 -07002916 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002919 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002920 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002921
2922 // Store the set of layers that need updates. This set must not change as
2923 // buffers are being latched, as this could result in a deadlock.
2924 // Example: Two producers share the same command stream and:
2925 // 1.) Layer 0 is latched
2926 // 2.) Layer 0 gets a new frame
2927 // 2.) Layer 1 gets a new frame
2928 // 3.) Layer 1 is latched.
2929 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2930 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002931 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 if (layer->hasQueuedFrame()) {
2933 frameQueued = true;
2934 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002935 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002936 } else {
2937 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002939 } else {
2940 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002941 }
Robert Carr2047fae2016-11-28 14:09:09 -08002942 });
2943
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002945 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002946 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002947 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002948 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002949 newDataLatched = true;
2950 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002951 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002952
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002953 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002954
2955 // If we will need to wake up at some time in the future to deal with a
2956 // queued frame that shouldn't be displayed during this vsync period, wake
2957 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002958 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002959 signalLayerUpdate();
2960 }
2961
2962 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002963 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Mathias Agopianad456f92011-01-13 17:53:01 -08002966void SurfaceFlinger::invalidateHwcGeometry()
2967{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002969}
2970
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002971
Fabien Sanglard830b8472016-11-30 16:35:58 -08002972void SurfaceFlinger::doDisplayComposition(
2973 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002974 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975{
Dan Stoza71433162014-02-04 16:22:36 -08002976 // We only need to actually compose the display if:
2977 // 1) It is being handled by hardware composer, which may need this to
2978 // keep its virtual display state machine in sync, or
2979 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002980 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002981 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002983 return;
2984 }
2985
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002987 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002988
2989 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002990 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991}
2992
Chia-I Wub02087d2017-11-09 10:19:54 -08002993bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002994{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002996
Chia-I Wub02087d2017-11-09 10:19:54 -08002997 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002998 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002999 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003000 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003001 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003002
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003004 bool needsLegacyColorMatrix = false;
3005 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003006
Dan Stoza9e56aa02015-11-02 13:00:03 -08003007 if (hasClientComposition) {
3008 ALOGV("hasClientComposition");
3009
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003010 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003011 if (displayDevice->hasWideColorGamut()) {
3012 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003013 }
3014 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003015 getBE().mRenderEngine->setDisplayMaxLuminance(
3016 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003017
Chia-I Wu8e50e692018-05-04 10:12:37 -07003018 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
3019 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3020 HWC2::Capability::SkipClientColorTransform);
3021
3022 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3023 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003024 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003025 }
3026
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003027 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07003028 outputDataspace != Dataspace::UNKNOWN &&
3029 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003030
Chia-I Wu7f402902017-11-09 12:51:10 -08003031 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003032 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003034 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003035
3036 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003037 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003038 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3039 }
3040 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003041 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003042
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003043 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003045 // when using overlays, we assume a fully transparent framebuffer
3046 // NOTE: we could reduce how much we need to clear, for instance
3047 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003048 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003049 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003050 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003051 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003052 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003053 // we're left with the letterbox region
3054 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003055 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003056
3057 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003059
Mathias Agopianb9494d52012-04-18 02:28:45 -07003060 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003061 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003062 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003064 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003065 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003066
Dan Stoza9e56aa02015-11-02 13:00:03 -08003067 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003068 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003069 // scissor on the main display. It should never be needed
3070 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003071 const Rect& bounds(displayDevice->getBounds());
3072 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003073 if (scissor != bounds) {
3074 // scissor doesn't match the screen's dimensions, so we
3075 // need to clear everything outside of it and enable
3076 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003077
Mathias Agopianf45c5102012-10-24 16:29:17 -07003078 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003079 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003080 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003081 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003082 }
3083 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003084 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003085
Mathias Agopian85d751c2012-08-29 16:59:24 -07003086 /*
3087 * and then, render the layers targeted at the framebuffer
3088 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003089
Dan Stoza9e56aa02015-11-02 13:00:03 -08003090 ALOGV("Rendering client layers");
3091 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003092 bool firstLayer = true;
3093 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3094 const Region clip(bounds.intersect(
3095 displayTransform.transform(layer->visibleRegion)));
3096 ALOGV("Layer: %s", layer->getName().string());
3097 ALOGV(" Composition type: %s",
3098 to_string(layer->getCompositionType(hwcId)).c_str());
3099 if (!clip.isEmpty()) {
3100 switch (layer->getCompositionType(hwcId)) {
3101 case HWC2::Composition::Cursor:
3102 case HWC2::Composition::Device:
3103 case HWC2::Composition::Sideband:
3104 case HWC2::Composition::SolidColor: {
3105 const Layer::State& state(layer->getDrawingState());
3106 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3107 layer->isOpaque(state) && (state.color.a == 1.0f)
3108 && hasClientComposition) {
3109 // never clear the very first layer since we're
3110 // guaranteed the FB is already cleared
3111 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003112 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003114 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003115 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003116 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003117 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3118 if (!legacyColorMatrixApplied) {
3119 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3120 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003122 } else if (legacyColorMatrixApplied) {
3123 getRenderEngine().setSaturationMatrix(mat4());
3124 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003126
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003127 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003128 break;
3129 }
3130 default:
3131 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003132 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003133 } else {
3134 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003135 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003136 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003137 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003138
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003139 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003140 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003141 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003142 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3143 getRenderEngine().setSaturationMatrix(mat4());
3144 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003145
Mathias Agopianf45c5102012-10-24 16:29:17 -07003146 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003147 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003148 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149}
3150
Fabien Sanglard830b8472016-11-30 16:35:58 -08003151void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3152 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003153 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003154 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Dan Stoza7d89d062015-04-30 13:29:25 -07003157status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003158 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003159 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003160 const sp<Layer>& lbc,
3161 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003162{
Dan Stoza7d89d062015-04-30 13:29:25 -07003163 // add this layer to the current state list
3164 {
3165 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003167 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3168 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003169 return NO_MEMORY;
3170 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 if (parent == nullptr) {
3172 mCurrentState.layersSortedByZ.add(lbc);
3173 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003174 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003175 ALOGE("addClientLayer called with a removed parent");
3176 return NAME_NOT_FOUND;
3177 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003178 parent->addChild(lbc);
3179 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003180
Yiwei Zhang243b3782018-05-15 17:40:04 -07003181 if (gbc != nullptr) {
3182 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3183 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3184 mMaxGraphicBufferProducerListSize,
3185 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3186 mGraphicBufferProducerList.size(),
3187 mMaxGraphicBufferProducerListSize, mNumLayers);
3188 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 mLayersAdded = true;
3190 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003191 }
3192
Mathias Agopian96f08192010-06-02 23:28:45 -07003193 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003194 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003195
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003197}
3198
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003199status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003200 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003201 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3202}
Robert Carr7f9b8992017-03-10 11:08:39 -08003203
chaviwca27f252018-02-06 16:46:39 -08003204status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3205 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003206 if (layer->isPendingRemoval()) {
3207 return NO_ERROR;
3208 }
3209
Robert Carr1f0a16a2016-10-24 16:27:39 -07003210 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003211 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003212 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003213 if (topLevelOnly) {
3214 return NO_ERROR;
3215 }
3216
Chia-I Wu98f1c102017-05-30 14:54:08 -07003217 sp<Layer> ancestor = p;
3218 while (ancestor->getParent() != nullptr) {
3219 ancestor = ancestor->getParent();
3220 }
3221 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3222 ALOGE("removeLayer called with a layer whose parent has been removed");
3223 return NAME_NOT_FOUND;
3224 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003225
3226 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003227 } else {
3228 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003229 }
3230
Robert Carr136e2f62017-02-08 17:54:29 -08003231 // As a matter of normal operation, the LayerCleaner will produce a second
3232 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3233 // so we will succeed in promoting it, but it's already been removed
3234 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3235 // otherwise something has gone wrong and we are leaking the layer.
3236 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003237 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3238 layer->getName().string(),
3239 (p != nullptr) ? p->getName().string() : "no-parent");
3240 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003241 } else if (index < 0) {
3242 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003243 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003244
Chia-I Wuc6657022017-08-15 11:18:17 -07003245 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246 mLayersPendingRemoval.add(layer);
3247 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003248 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003249 setTransactionFlags(eTransactionNeeded);
3250 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251}
3252
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003253uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003254 return android_atomic_release_load(&mTransactionFlags);
3255}
3256
Mathias Agopian3f844832013-08-07 21:24:32 -07003257uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3259}
3260
Mathias Agopian3f844832013-08-07 21:24:32 -07003261uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003262 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3263}
3264
3265uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3266 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003268 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003270 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 }
3272 return old;
3273}
3274
chaviwca27f252018-02-06 16:46:39 -08003275bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3276 for (const ComposerState& state : states) {
3277 // Here we need to check that the interface we're given is indeed
3278 // one of our own. A malicious client could give us a nullptr
3279 // IInterface, or one of its own or even one of our own but a
3280 // different type. All these situations would cause us to crash.
3281 if (state.client == nullptr) {
3282 return true;
3283 }
3284
3285 sp<IBinder> binder = IInterface::asBinder(state.client);
3286 if (binder == nullptr) {
3287 return true;
3288 }
3289
3290 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3291 return true;
3292 }
3293 }
3294 return false;
3295}
3296
Mathias Agopian8b33f032012-07-24 20:43:54 -07003297void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003298 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003299 const Vector<DisplayState>& displays,
3300 uint32_t flags)
3301{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003302 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003303 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003304 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003305
chaviwca27f252018-02-06 16:46:39 -08003306 if (containsAnyInvalidClientState(states)) {
3307 return;
3308 }
3309
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 if (flags & eAnimation) {
3311 // For window updates that are part of an animation we must wait for
3312 // previous animation "frames" to be handled.
3313 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003314 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003315 if (CC_UNLIKELY(err != NO_ERROR)) {
3316 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003317 // caller after a few seconds.
3318 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3319 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003320 mAnimTransactionPending = false;
3321 break;
3322 }
3323 }
3324 }
3325
chaviwca27f252018-02-06 16:46:39 -08003326 for (const DisplayState& display : displays) {
3327 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003328 }
3329
chaviwca27f252018-02-06 16:46:39 -08003330 for (const ComposerState& state : states) {
3331 transactionFlags |= setClientStateLocked(state);
3332 }
3333
3334 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3335 // as destroyed should only occur after setting all other states. This is to allow for a
3336 // child re-parent to happen before marking its original parent as destroyed (which would
3337 // then mark the child as destroyed).
3338 for (const ComposerState& state : states) {
3339 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003340 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003341
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003342 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3343 // anyway. This can be used as a flush mechanism for previous async transactions.
3344 // Empty animation transaction can be used to simulate back-pressure, so also force a
3345 // transaction for empty animation transactions.
3346 if (transactionFlags == 0 &&
3347 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003348 transactionFlags = eTransactionNeeded;
3349 }
3350
Mathias Agopian386aa982011-11-07 21:58:03 -08003351 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003352 if (mInterceptor->isEnabled()) {
3353 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003354 }
Irvel468051e2016-06-13 16:44:44 -07003355
Mathias Agopian386aa982011-11-07 21:58:03 -08003356 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003357 const auto start = (flags & eEarlyWakeup)
3358 ? VSyncModulator::TransactionStart::EARLY
3359 : VSyncModulator::TransactionStart::NORMAL;
3360 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003361
3362 // if this is a synchronous transaction, wait for it to take effect
3363 // before returning.
3364 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003366 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003367 if (flags & eAnimation) {
3368 mAnimTransactionPending = true;
3369 }
3370 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003371 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3372 if (CC_UNLIKELY(err != NO_ERROR)) {
3373 // just in case something goes wrong in SF, return to the
3374 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3376 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003377 break;
3378 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380 }
3381}
3382
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3384{
Jesse Hall9a143922012-10-04 16:29:19 -07003385 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3386 if (dpyIdx < 0)
3387 return 0;
3388
Mathias Agopiane57f2922012-08-09 16:29:12 -07003389 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003390 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003391 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003392 const uint32_t what = s.what;
3393 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003394 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395 disp.surface = s.surface;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 }
3399 if (what & DisplayState::eLayerStackChanged) {
3400 if (disp.layerStack != s.layerStack) {
3401 disp.layerStack = s.layerStack;
3402 flags |= eDisplayTransactionNeeded;
3403 }
3404 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003405 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003406 if (disp.orientation != s.orientation) {
3407 disp.orientation = s.orientation;
3408 flags |= eDisplayTransactionNeeded;
3409 }
3410 if (disp.frame != s.frame) {
3411 disp.frame = s.frame;
3412 flags |= eDisplayTransactionNeeded;
3413 }
3414 if (disp.viewport != s.viewport) {
3415 disp.viewport = s.viewport;
3416 flags |= eDisplayTransactionNeeded;
3417 }
3418 }
Michael Lentine47e45402014-07-18 15:34:25 -07003419 if (what & DisplayState::eDisplaySizeChanged) {
3420 if (disp.width != s.width) {
3421 disp.width = s.width;
3422 flags |= eDisplayTransactionNeeded;
3423 }
3424 if (disp.height != s.height) {
3425 disp.height = s.height;
3426 flags |= eDisplayTransactionNeeded;
3427 }
3428 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 }
3430 return flags;
3431}
3432
chaviwca27f252018-02-06 16:46:39 -08003433uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3434 const layer_state_t& s = composerState.state;
3435 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3436
Mathias Agopian13127d82013-03-05 17:47:11 -08003437 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003438 if (layer == nullptr) {
3439 return 0;
3440 }
3441
3442 if (layer->isPendingRemoval()) {
3443 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3444 return 0;
3445 }
3446
3447 uint32_t flags = 0;
3448
3449 const uint32_t what = s.what;
3450 bool geometryAppliesWithResize =
3451 what & layer_state_t::eGeometryAppliesWithResize;
3452 if (what & layer_state_t::ePositionChanged) {
3453 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3454 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 }
3457 if (what & layer_state_t::eLayerChanged) {
3458 // NOTE: index needs to be calculated before we update the state
3459 const auto& p = layer->getParent();
3460 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003461 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003462 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003463 mCurrentState.layersSortedByZ.removeAt(idx);
3464 mCurrentState.layersSortedByZ.add(layer);
3465 // we need traversal (state changed)
3466 // AND transaction (list changed)
3467 flags |= eTransactionNeeded|eTraversalNeeded;
3468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 } else {
3470 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003471 flags |= eTransactionNeeded|eTraversalNeeded;
3472 }
3473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 }
3475 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003476 // NOTE: index needs to be calculated before we update the state
3477 const auto& p = layer->getParent();
3478 if (p == nullptr) {
3479 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3480 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3481 mCurrentState.layersSortedByZ.removeAt(idx);
3482 mCurrentState.layersSortedByZ.add(layer);
3483 // we need traversal (state changed)
3484 // AND transaction (list changed)
3485 flags |= eTransactionNeeded|eTraversalNeeded;
3486 }
3487 } else {
3488 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3489 flags |= eTransactionNeeded|eTraversalNeeded;
3490 }
chaviw8b3871a2017-11-01 17:41:01 -07003491 }
3492 }
3493 if (what & layer_state_t::eSizeChanged) {
3494 if (layer->setSize(s.w, s.h)) {
3495 flags |= eTraversalNeeded;
3496 }
3497 }
3498 if (what & layer_state_t::eAlphaChanged) {
3499 if (layer->setAlpha(s.alpha))
3500 flags |= eTraversalNeeded;
3501 }
3502 if (what & layer_state_t::eColorChanged) {
3503 if (layer->setColor(s.color))
3504 flags |= eTraversalNeeded;
3505 }
3506 if (what & layer_state_t::eMatrixChanged) {
3507 if (layer->setMatrix(s.matrix))
3508 flags |= eTraversalNeeded;
3509 }
3510 if (what & layer_state_t::eTransparentRegionChanged) {
3511 if (layer->setTransparentRegionHint(s.transparentRegion))
3512 flags |= eTraversalNeeded;
3513 }
3514 if (what & layer_state_t::eFlagsChanged) {
3515 if (layer->setFlags(s.flags, s.mask))
3516 flags |= eTraversalNeeded;
3517 }
3518 if (what & layer_state_t::eCropChanged) {
3519 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eFinalCropChanged) {
3523 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3524 flags |= eTraversalNeeded;
3525 }
3526 if (what & layer_state_t::eLayerStackChanged) {
3527 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3528 // We only allow setting layer stacks for top level layers,
3529 // everything else inherits layer stack from its parent.
3530 if (layer->hasParent()) {
3531 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3532 layer->getName().string());
3533 } else if (idx < 0) {
3534 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3535 "that also does not appear in the top level layer list. Something"
3536 " has gone wrong.", layer->getName().string());
3537 } else if (layer->setLayerStack(s.layerStack)) {
3538 mCurrentState.layersSortedByZ.removeAt(idx);
3539 mCurrentState.layersSortedByZ.add(layer);
3540 // we need traversal (state changed)
3541 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003542 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003543 }
3544 }
3545 if (what & layer_state_t::eDeferTransaction) {
3546 if (s.barrierHandle != nullptr) {
3547 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3548 } else if (s.barrierGbp != nullptr) {
3549 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3550 if (authenticateSurfaceTextureLocked(gbp)) {
3551 const auto& otherLayer =
3552 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3553 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3554 } else {
3555 ALOGE("Attempt to defer transaction to to an"
3556 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003557 }
3558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 // We don't trigger a traversal here because if no other state is
3560 // changed, we don't want this to cause any more work
3561 }
3562 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003563 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003565 if (!hadParent) {
3566 mCurrentState.layersSortedByZ.remove(layer);
3567 }
chaviw8b3871a2017-11-01 17:41:01 -07003568 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 }
3571 if (what & layer_state_t::eReparentChildren) {
3572 if (layer->reparentChildren(s.reparentHandle)) {
3573 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003574 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (what & layer_state_t::eDetachChildren) {
3577 layer->detachChildren();
3578 }
3579 if (what & layer_state_t::eOverrideScalingModeChanged) {
3580 layer->setOverrideScalingMode(s.overrideScalingMode);
3581 // We don't trigger a traversal here because if no other state is
3582 // changed, we don't want this to cause any more work
3583 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003584 return flags;
3585}
3586
chaviwca27f252018-02-06 16:46:39 -08003587void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3588 const layer_state_t& state = composerState.state;
3589 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3590
3591 sp<Layer> layer(client->getLayerUser(state.surface));
3592 if (layer == nullptr) {
3593 return;
3594 }
3595
3596 if (layer->isPendingRemoval()) {
3597 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3598 return;
3599 }
3600
3601 if (state.what & layer_state_t::eDestroySurface) {
3602 removeLayerLocked(mStateLock, layer);
3603 }
3604}
3605
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003607 const String8& name,
3608 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003610 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003611 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003613 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003614 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003615 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003617 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003618
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619 status_t result = NO_ERROR;
3620
3621 sp<Layer> layer;
3622
Cody Northropbc755282017-03-31 12:00:08 -06003623 String8 uniqueName = getUniqueLayerName(name);
3624
Mathias Agopian3165cc22012-08-08 19:42:09 -07003625 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3626 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003627 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003628 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003629 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003630
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 break;
chaviw13fdc492017-06-27 12:40:18 -07003632 case ISurfaceComposerClient::eFXSurfaceColor:
3633 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003634 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003635 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 break;
3637 default:
3638 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003639 break;
3640 }
3641
Dan Stoza7d89d062015-04-30 13:29:25 -07003642 if (result != NO_ERROR) {
3643 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003645
Chia-I Wuab0c3192017-08-01 11:29:00 -07003646 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3647 // TODO b/64227542
3648 if (windowType == 441731) {
3649 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3650 layer->setPrimaryDisplayOnly();
3651 }
3652
Albert Chaulk479c60c2017-01-27 14:21:34 -05003653 layer->setInfo(windowType, ownerUid);
3654
Robert Carr1f0a16a2016-10-24 16:27:39 -07003655 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003656 if (result != NO_ERROR) {
3657 return result;
3658 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003659 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003660
3661 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003662 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663}
3664
Cody Northropbc755282017-03-31 12:00:08 -06003665String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3666{
3667 bool matchFound = true;
3668 uint32_t dupeCounter = 0;
3669
3670 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3671 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3672
3673 // Loop over layers until we're sure there is no matching name
3674 while (matchFound) {
3675 matchFound = false;
3676 mDrawingState.traverseInZOrder([&](Layer* layer) {
3677 if (layer->getName() == uniqueName) {
3678 matchFound = true;
3679 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3680 }
3681 });
3682 }
3683
3684 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3685
3686 return uniqueName;
3687}
3688
David Sodman0c69cad2017-08-21 12:12:51 -07003689status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3691 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692{
3693 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003694 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695 case PIXEL_FORMAT_TRANSPARENT:
3696 case PIXEL_FORMAT_TRANSLUCENT:
3697 format = PIXEL_FORMAT_RGBA_8888;
3698 break;
3699 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003700 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701 break;
3702 }
3703
David Sodman0c69cad2017-08-21 12:12:51 -07003704 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3705 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003706 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003707 *handle = layer->getHandle();
3708 *gbp = layer->getProducer();
3709 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003711
David Sodman0c69cad2017-08-21 12:12:51 -07003712 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003713 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714}
3715
chaviw13fdc492017-06-27 12:40:18 -07003716status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003717 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003718 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719{
chaviw13fdc492017-06-27 12:40:18 -07003720 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003721 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003722 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003723}
3724
Mathias Agopianac9fa422013-02-11 16:40:36 -08003725status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726{
Robert Carr9524cb32017-02-13 11:32:32 -08003727 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003728 status_t err = NO_ERROR;
3729 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003730 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003731 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003732 err = removeLayer(l);
3733 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3734 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003735 }
3736 return err;
3737}
3738
Mathias Agopian13127d82013-03-05 17:47:11 -08003739status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003740{
Mathias Agopian67106042013-03-14 19:18:13 -07003741 // called by ~LayerCleaner() when all references to the IBinder (handle)
3742 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003743 sp<Layer> l = layer.promote();
3744 if (l == nullptr) {
3745 // The layer has already been removed, carry on
3746 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003747 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003748 // If we have a parent, then we can continue to live as long as it does.
3749 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003750}
3751
Mathias Agopianb60314a2012-04-10 22:09:54 -07003752// ---------------------------------------------------------------------------
3753
Andy McFadden13a082e2012-08-24 10:16:42 -07003754void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003755 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003756 Vector<ComposerState> state;
3757 Vector<DisplayState> displays;
3758 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003759 d.what = DisplayState::eDisplayProjectionChanged |
3760 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003761 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003762 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003763 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003764 d.frame.makeInvalid();
3765 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003766 d.width = 0;
3767 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003768 displays.add(d);
3769 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003770 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3771 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003772
David Sodman105b7dc2017-11-04 20:28:14 -07003773 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003774 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003775 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003776
Brian Andersond0010582017-03-07 13:20:31 -08003777 // Use phase of 0 since phase is not known.
3778 // Use latency of 0, which will snap to the ideal latency.
3779 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003780}
3781
3782void SurfaceFlinger::initializeDisplays() {
3783 class MessageScreenInitialized : public MessageBase {
3784 SurfaceFlinger* flinger;
3785 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003786 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003787 virtual bool handler() {
3788 flinger->onInitializeDisplays();
3789 return true;
3790 }
3791 };
3792 sp<MessageBase> msg = new MessageScreenInitialized(this);
3793 postMessageAsync(msg); // we may be called from main thread, use async message
3794}
3795
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003797 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003798 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3799 this);
3800 int32_t type = hw->getDisplayType();
3801 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003802
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003804 return;
3805 }
3806
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003807 hw->setPowerMode(mode);
3808 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3809 ALOGW("Trying to set power mode for virtual display");
3810 return;
3811 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003812
Lloyd Pique4d234852018-01-22 17:21:36 -08003813 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003814 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003815 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3816 if (idx < 0) {
3817 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3818 return;
3819 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003820 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003821 }
3822
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003823 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003824 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003825 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003826 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3827 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003828 // FIXME: eventthread only knows about the main display right now
3829 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003830 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003833 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003834 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003835 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003836
3837 struct sched_param param = {0};
3838 param.sched_priority = 1;
3839 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3840 ALOGW("Couldn't set SCHED_FIFO on display on");
3841 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003843 // Turn off the display
3844 struct sched_param param = {0};
3845 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3846 ALOGW("Couldn't set SCHED_OTHER on display off");
3847 }
3848
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003849 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3850 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003851 disableHardwareVsync(true); // also cancels any in-progress resync
3852
Mathias Agopiancde87a32012-09-13 14:09:01 -07003853 // FIXME: eventthread only knows about the main display right now
3854 mEventThread->onScreenReleased();
3855 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003856
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 getHwComposer().setPowerMode(type, mode);
3858 mVisibleRegionsDirty = true;
3859 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003860 } else if (mode == HWC_POWER_MODE_DOZE ||
3861 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003862 // Update display while dozing
3863 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003864 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3865 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003866 // FIXME: eventthread only knows about the main display right now
3867 mEventThread->onScreenAcquired();
3868 resyncToHardwareVsync(true);
3869 }
3870 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3871 // Leave display going to doze
3872 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3873 disableHardwareVsync(true); // also cancels any in-progress resync
3874 // FIXME: eventthread only knows about the main display right now
3875 mEventThread->onScreenReleased();
3876 }
3877 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003879 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003880 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003881 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003882 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003883}
3884
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003885void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3886 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003887 SurfaceFlinger& mFlinger;
3888 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003890 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003891 MessageSetPowerMode(SurfaceFlinger& flinger,
3892 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3893 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003894 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003895 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003896 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003898 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003899 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003900 ALOGW("Attempt to set power mode = %d for virtual display",
3901 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003902 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003903 mFlinger.setPowerModeInternal(
3904 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003905 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906 return true;
3907 }
3908 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003909 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003910 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003911}
3912
3913// ---------------------------------------------------------------------------
3914
Lloyd Pique755e3192018-01-31 16:46:15 -08003915status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3916 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003918
Mathias Agopianbd115332013-04-18 16:41:04 -07003919 IPCThreadState* ipc = IPCThreadState::self();
3920 const int pid = ipc->getCallingPid();
3921 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003922
Mathias Agopianbd115332013-04-18 16:41:04 -07003923 if ((uid != AID_SHELL) &&
3924 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003925 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003926 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003928 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003929 // (this would indicate SF is stuck, but we want to be able to
3930 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003931 status_t err = mStateLock.timedLock(s2ns(1));
3932 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003933 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003934 result.appendFormat(
3935 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3936 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003937 }
3938
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939 bool dumpAll = true;
3940 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003941 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003942
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003943 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003944 if ((index < numArgs) &&
3945 (args[index] == String16("--list"))) {
3946 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003947 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003948 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949 }
3950
3951 if ((index < numArgs) &&
3952 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003953 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003955 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003956 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957
3958 if ((index < numArgs) &&
3959 (args[index] == String16("--latency-clear"))) {
3960 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003961 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003962 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003964
3965 if ((index < numArgs) &&
3966 (args[index] == String16("--dispsync"))) {
3967 index++;
3968 mPrimaryDispSync.dump(result);
3969 dumpAll = false;
3970 }
Dan Stozab90cf072015-03-05 11:05:59 -08003971
3972 if ((index < numArgs) &&
3973 (args[index] == String16("--static-screen"))) {
3974 index++;
3975 dumpStaticScreenStats(result);
3976 dumpAll = false;
3977 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003978
3979 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003980 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003981 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003982 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003983 dumpAll = false;
3984 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003985
3986 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3987 index++;
3988 dumpWideColorInfo(result);
3989 dumpAll = false;
3990 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003991
3992 if ((index < numArgs) &&
3993 (args[index] == String16("--enable-layer-stats"))) {
3994 index++;
3995 mLayerStats.enable();
3996 dumpAll = false;
3997 }
3998
3999 if ((index < numArgs) &&
4000 (args[index] == String16("--disable-layer-stats"))) {
4001 index++;
4002 mLayerStats.disable();
4003 dumpAll = false;
4004 }
4005
4006 if ((index < numArgs) &&
4007 (args[index] == String16("--clear-layer-stats"))) {
4008 index++;
4009 mLayerStats.clear();
4010 dumpAll = false;
4011 }
4012
4013 if ((index < numArgs) &&
4014 (args[index] == String16("--dump-layer-stats"))) {
4015 index++;
4016 mLayerStats.dump(result);
4017 dumpAll = false;
4018 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004019
4020 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4021 index++;
4022 mTimeStats.parseArgs(asProto, args, index, result);
4023 dumpAll = false;
4024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004026
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004027 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004028 if (asProto) {
4029 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4030 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4031 } else {
4032 dumpAllLocked(args, index, result);
4033 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004034 }
4035
Mathias Agopian9795c422009-08-26 16:36:26 -07004036 if (locked) {
4037 mStateLock.unlock();
4038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004039 }
4040 write(fd, result.string(), result.size());
4041 return NO_ERROR;
4042}
4043
Dan Stozac7014012014-02-14 15:03:43 -08004044void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4045 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004046{
Robert Carr2047fae2016-11-28 14:09:09 -08004047 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004048 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004049 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050}
4051
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004052void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004053 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004054{
4055 String8 name;
4056 if (index < args.size()) {
4057 name = String8(args[index]);
4058 index++;
4059 }
4060
David Sodman105b7dc2017-11-04 20:28:14 -07004061 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004062 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004063 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004064
4065 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004066 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004067 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004068 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004069 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004070 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004071 }
Robert Carr2047fae2016-11-28 14:09:09 -08004072 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004073 }
4074}
4075
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004076void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004077 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004078{
4079 String8 name;
4080 if (index < args.size()) {
4081 name = String8(args[index]);
4082 index++;
4083 }
4084
Robert Carr2047fae2016-11-28 14:09:09 -08004085 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004086 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004087 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004088 }
Robert Carr2047fae2016-11-28 14:09:09 -08004089 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004090
Svetoslavd85084b2014-03-20 10:28:31 -07004091 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004092}
4093
Jamie Gennis6547ff42013-07-16 20:12:42 -07004094// This should only be called from the main thread. Otherwise it would need
4095// the lock and should use mCurrentState rather than mDrawingState.
4096void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004097 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004098 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004099 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004100
4101 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4102}
4103
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004104void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004105{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004106 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004107
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004108 if (isLayerTripleBufferingDisabled())
4109 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004110
4111 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004112 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004113 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004114 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004115 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4116 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004117 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004118}
4119
Dan Stozab90cf072015-03-05 11:05:59 -08004120void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4121{
4122 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004123 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4124 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004125 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004126 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004127 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4128 b + 1, bucketTimeSec, percent);
4129 }
David Sodman4a36e932017-11-07 14:29:47 -08004130 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004131 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004132 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004133 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004134 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004135}
4136
Dan Stozae77c7662016-05-13 11:37:28 -07004137void SurfaceFlinger::recordBufferingStats(const char* layerName,
4138 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004139 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4140 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004141 for (const auto& segment : history) {
4142 if (!segment.usedThirdBuffer) {
4143 stats.twoBufferTime += segment.totalTime;
4144 }
4145 if (segment.occupancyAverage < 1.0f) {
4146 stats.doubleBufferedTime += segment.totalTime;
4147 } else if (segment.occupancyAverage < 2.0f) {
4148 stats.tripleBufferedTime += segment.totalTime;
4149 }
4150 ++stats.numSegments;
4151 stats.totalTime += segment.totalTime;
4152 }
4153}
4154
Brian Andersond6927fb2016-07-23 23:37:30 -07004155void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4156 result.appendFormat("Layer frame timestamps:\n");
4157
4158 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4159 const size_t count = currentLayers.size();
4160 for (size_t i=0 ; i<count ; i++) {
4161 currentLayers[i]->dumpFrameEvents(result);
4162 }
4163}
4164
Dan Stozae77c7662016-05-13 11:37:28 -07004165void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4166 result.append("Buffering stats:\n");
4167 result.append(" [Layer name] <Active time> <Two buffer> "
4168 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004169 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004170 typedef std::tuple<std::string, float, float, float> BufferTuple;
4171 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004172 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004173 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004174 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004175 if (stats.numSegments == 0) {
4176 continue;
4177 }
4178 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4179 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4180 stats.totalTime;
4181 float doubleBufferRatio = static_cast<float>(
4182 stats.doubleBufferedTime) / stats.totalTime;
4183 float tripleBufferRatio = static_cast<float>(
4184 stats.tripleBufferedTime) / stats.totalTime;
4185 sorted.insert({activeTime, {name, twoBufferRatio,
4186 doubleBufferRatio, tripleBufferRatio}});
4187 }
4188 for (const auto& sortedPair : sorted) {
4189 float activeTime = sortedPair.first;
4190 const BufferTuple& values = sortedPair.second;
4191 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4192 std::get<0>(values).c_str(), activeTime,
4193 std::get<1>(values), std::get<2>(values),
4194 std::get<3>(values));
4195 }
4196 result.append("\n");
4197}
4198
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004199void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4200 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004201 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004202
4203 // TODO: print out if wide-color mode is active or not
4204
4205 for (size_t d = 0; d < mDisplays.size(); d++) {
4206 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4207 int32_t hwcId = displayDevice->getHwcDisplayId();
4208 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4209 continue;
4210 }
4211
4212 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004213 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004214 for (auto&& mode : modes) {
4215 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4216 }
4217
Peiyong Lina52f0292018-03-14 17:26:31 -07004218 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004219 result.appendFormat(" Current color mode: %s (%d)\n",
4220 decodeColorMode(currentMode).c_str(), currentMode);
4221 }
4222 result.append("\n");
4223}
4224
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004225LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004226 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004227 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4228 const State& state = useDrawing ? mDrawingState : mCurrentState;
4229 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004230 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004231 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004232 });
4233
4234 return layersProto;
4235}
4236
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004237LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4238 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004239 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004240
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004241 SizeProto* resolution = layersProto.mutable_resolution();
4242 resolution->set_w(displayDevice->getWidth());
4243 resolution->set_h(displayDevice->getHeight());
4244
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004245 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4246 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4247 layersProto.set_global_transform(
4248 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4249
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004250 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004251 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004252 LayerProto* layerProto = layersProto.add_layers();
4253 layer->writeToProto(layerProto, hwcId);
4254 }
4255 });
4256
4257 return layersProto;
4258}
4259
Mathias Agopian74d211a2013-04-22 16:55:35 +02004260void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4261 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004262{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004263 bool colorize = false;
4264 if (index < args.size()
4265 && (args[index] == String16("--color"))) {
4266 colorize = true;
4267 index++;
4268 }
4269
4270 Colorizer colorizer(colorize);
4271
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272 // figure out if we're stuck somewhere
4273 const nsecs_t now = systemTime();
4274 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4275 const nsecs_t inTransaction(mDebugInTransaction);
4276 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4277 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4278
4279 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004280 * Dump library configuration.
4281 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004282
4283 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004284 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004285 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004286 appendSfConfigString(result);
4287 appendUiConfigString(result);
4288 appendGuiConfigString(result);
4289 result.append("\n");
4290
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004291 result.append("\nWide-Color information:\n");
4292 dumpWideColorInfo(result);
4293
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004295 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004296 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004297 result.append(SyncFeatures::getInstance().toString());
4298 result.append("\n");
4299
David Sodman105b7dc2017-11-04 20:28:14 -07004300 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004301
Andy McFadden41d67d72014-04-25 16:58:34 -07004302 colorizer.bold(result);
4303 result.append("DispSync configuration: ");
4304 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004305 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4306 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4307 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004308 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004309 result.append("\n");
4310
Dan Stozab90cf072015-03-05 11:05:59 -08004311 // Dump static screen stats
4312 result.append("\n");
4313 dumpStaticScreenStats(result);
4314 result.append("\n");
4315
Dan Stozae77c7662016-05-13 11:37:28 -07004316 dumpBufferingStats(result);
4317
Andy McFadden4803b742012-09-24 19:07:20 -07004318 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319 * Dump the visible layer list
4320 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004322 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004323 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4324 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004326
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004327 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004328 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004329 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004330 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331
4332 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004333 * Dump Display state
4334 */
4335
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004336 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004337 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004339 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4340 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004341 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004342 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004343 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004344
4345 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346 * Dump SurfaceFlinger global state
4347 */
4348
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004349 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004351 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
Mathias Agopian888c8222012-08-04 21:10:38 -07004353 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004354 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004355
David Sodmanbc815282017-11-05 18:57:52 -08004356 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004358 if (hw) {
4359 hw->undefinedRegion.dump(result, "undefinedRegion");
4360 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4361 hw->getOrientation(), hw->isDisplayOn());
4362 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004363 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364 " last eglSwapBuffers() time: %f us\n"
4365 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004366 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367 " refresh-rate : %f fps\n"
4368 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004369 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004370 " gpu_to_cpu_unsupported : %d\n"
4371 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372 mLastSwapBufferTime/1000.0,
4373 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004374 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004375 1e9 / activeConfig->getVsyncPeriod(),
4376 activeConfig->getDpiX(),
4377 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004378 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004379
Mathias Agopian74d211a2013-04-22 16:55:35 +02004380 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382
Mathias Agopian74d211a2013-04-22 16:55:35 +02004383 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004384 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385
4386 /*
4387 * VSYNC state
4388 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004389 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004390 result.append("\n");
4391
4392 /*
4393 * HWC layer minidump
4394 */
4395 for (size_t d = 0; d < mDisplays.size(); d++) {
4396 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4397 int32_t hwcId = displayDevice->getHwcDisplayId();
4398 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4399 continue;
4400 }
4401
4402 result.appendFormat("Display %d HWC layers:\n", hwcId);
4403 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004404 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004405 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004406 });
Dan Stozae22aec72016-08-01 13:20:59 -07004407 result.append("\n");
4408 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409
4410 /*
4411 * Dump HWComposer state
4412 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004414 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004415 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004416 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004417 result.appendFormat(" h/w composer %s\n",
4418 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004419 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420
4421 /*
4422 * Dump gralloc state
4423 */
4424 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4425 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004426
4427 /*
4428 * Dump VrFlinger state if in use.
4429 */
4430 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4431 result.append("VrFlinger state:\n");
4432 result.append(mVrFlinger->Dump().c_str());
4433 result.append("\n");
4434 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435}
4436
Mathias Agopian13127d82013-03-05 17:47:11 -08004437const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004438SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004439 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004440 wp<IBinder> dpy;
4441 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4442 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4443 dpy = mDisplays.keyAt(i);
4444 break;
4445 }
4446 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004447 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004448 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4449 // Just use the primary display so we have something to return
4450 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004452 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004453}
4454
Keun young Park63f165f2012-08-31 10:53:36 -07004455bool SurfaceFlinger::startDdmConnection()
4456{
4457 void* libddmconnection_dso =
4458 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4459 if (!libddmconnection_dso) {
4460 return false;
4461 }
4462 void (*DdmConnection_start)(const char* name);
4463 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004464 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004465 if (!DdmConnection_start) {
4466 dlclose(libddmconnection_dso);
4467 return false;
4468 }
4469 (*DdmConnection_start)(getServiceName());
4470 return true;
4471}
4472
Chia-I Wu28f320b2018-05-03 11:02:56 -07004473void SurfaceFlinger::updateColorMatrixLocked() {
4474 mat4 colorMatrix;
4475 if (mGlobalSaturationFactor != 1.0f) {
4476 // Rec.709 luma coefficients
4477 float3 luminance{0.213f, 0.715f, 0.072f};
4478 luminance *= 1.0f - mGlobalSaturationFactor;
4479 mat4 saturationMatrix = mat4(
4480 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4481 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4482 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4483 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4484 );
4485 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4486 } else {
4487 colorMatrix = mClientColorMatrix * mDaltonizer();
4488 }
4489
4490 if (mCurrentState.colorMatrix != colorMatrix) {
4491 mCurrentState.colorMatrix = colorMatrix;
4492 mCurrentState.colorMatrixChanged = true;
4493 setTransactionFlags(eTransactionNeeded);
4494 }
4495}
4496
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004497status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004498 switch (code) {
4499 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004500 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004501 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004502 case CLEAR_ANIMATION_FRAME_STATS:
4503 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004504 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004505 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004506 case ENABLE_VSYNC_INJECTIONS:
4507 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004508 {
4509 // codes that require permission check
4510 IPCThreadState* ipc = IPCThreadState::self();
4511 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004512 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004513 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004514 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004515 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004516 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004518 break;
4519 }
Robert Carr1db73f62016-12-21 12:58:51 -08004520 /*
4521 * Calling setTransactionState is safe, because you need to have been
4522 * granted a reference to Client* and Handle* to do anything with it.
4523 *
4524 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4525 */
4526 case SET_TRANSACTION_STATE:
4527 case CREATE_SCOPED_CONNECTION:
4528 {
4529 return OK;
4530 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004531 case CAPTURE_SCREEN:
4532 {
4533 // codes that require permission check
4534 IPCThreadState* ipc = IPCThreadState::self();
4535 const int pid = ipc->getCallingPid();
4536 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004537 if ((uid != AID_GRAPHICS) &&
4538 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004539 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004540 return PERMISSION_DENIED;
4541 }
4542 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 }
chaviwa76b2712017-09-20 12:02:26 -07004544 case CAPTURE_LAYERS: {
4545 IPCThreadState* ipc = IPCThreadState::self();
4546 const int pid = ipc->getCallingPid();
4547 const int uid = ipc->getCallingUid();
4548 if ((uid != AID_GRAPHICS) &&
4549 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4550 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4551 return PERMISSION_DENIED;
4552 }
4553 break;
4554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004555 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004556 return OK;
4557}
4558
4559status_t SurfaceFlinger::onTransact(
4560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4561{
4562 status_t credentialCheck = CheckTransactCodeCredentials(code);
4563 if (credentialCheck != OK) {
4564 return credentialCheck;
4565 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004566
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4568 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004569 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004570 IPCThreadState* ipc = IPCThreadState::self();
4571 const int uid = ipc->getCallingUid();
4572 if (CC_UNLIKELY(uid != AID_SYSTEM
4573 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004574 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004575 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004576 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004577 return PERMISSION_DENIED;
4578 }
4579 int n;
4580 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004581 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004582 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004583 return NO_ERROR;
4584 case 1002: // SHOW_UPDATES
4585 n = data.readInt32();
4586 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004587 invalidateHwcGeometry();
4588 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004591 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004592 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004594 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004595 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004596 setTransactionFlags(
4597 eTransactionNeeded|
4598 eDisplayTransactionNeeded|
4599 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004600 return NO_ERROR;
4601 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004602 case 1006:{ // send empty update
4603 signalRefresh();
4604 return NO_ERROR;
4605 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004606 case 1008: // toggle use of hw composer
4607 n = data.readInt32();
4608 mDebugDisableHWC = n ? 1 : 0;
4609 invalidateHwcGeometry();
4610 repaintEverything();
4611 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004612 case 1009: // toggle use of transform hint
4613 n = data.readInt32();
4614 mDebugDisableTransformHint = n ? 1 : 0;
4615 invalidateHwcGeometry();
4616 repaintEverything();
4617 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004618 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004619 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 reply->writeInt32(0);
4621 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004622 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004623 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 return NO_ERROR;
4625 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004626 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004627 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004628 return NO_ERROR;
4629 }
4630 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004631 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004632 // daltonize
4633 n = data.readInt32();
4634 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004635 case 1:
4636 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4637 break;
4638 case 2:
4639 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4640 break;
4641 case 3:
4642 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4643 break;
4644 default:
4645 mDaltonizer.setType(ColorBlindnessType::None);
4646 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004647 }
4648 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004649 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004650 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004651 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004652 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653
4654 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004655 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004657 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004659 // apply a color matrix
4660 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004661 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004662 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004663 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004664 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004665 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004666 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004667 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004668 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004669 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004670 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004671
4672 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4673 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004675 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4676 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4677 }
4678
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004680 return NO_ERROR;
4681 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004682 // This is an experimental interface
4683 // Needs to be shifted to proper binder interface when we productize
4684 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004685 n = data.readInt32();
4686 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004687 return NO_ERROR;
4688 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004689 case 1017: {
4690 n = data.readInt32();
4691 mForceFullDamage = static_cast<bool>(n);
4692 return NO_ERROR;
4693 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004694 case 1018: { // Modify Choreographer's phase offset
4695 n = data.readInt32();
4696 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4697 return NO_ERROR;
4698 }
4699 case 1019: { // Modify SurfaceFlinger's phase offset
4700 n = data.readInt32();
4701 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4702 return NO_ERROR;
4703 }
Irvel468051e2016-06-13 16:44:44 -07004704 case 1020: { // Layer updates interceptor
4705 n = data.readInt32();
4706 if (n) {
4707 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004708 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004709 }
4710 else{
4711 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004712 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004713 }
4714 return NO_ERROR;
4715 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004716 case 1021: { // Disable HWC virtual displays
4717 n = data.readInt32();
4718 mUseHwcVirtualDisplays = !n;
4719 return NO_ERROR;
4720 }
Romain Guy0147a172017-06-01 13:53:56 -07004721 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004722 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004723 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004724
Chia-I Wu28f320b2018-05-03 11:02:56 -07004725 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004726 return NO_ERROR;
4727 }
Romain Guy54f154a2017-10-24 21:40:32 +01004728 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004729 int32_t value = data.readInt32();
4730 if (value > 2) {
4731 return BAD_VALUE;
4732 }
4733 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4734 return BAD_VALUE;
4735 }
Romain Guy54f154a2017-10-24 21:40:32 +01004736
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004737 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004738 invalidateHwcGeometry();
4739 repaintEverything();
4740 return NO_ERROR;
4741 }
4742 case 1024: { // Is wide color gamut rendering/color management supported?
4743 reply->writeBool(hasWideColorDisplay);
4744 return NO_ERROR;
4745 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004746 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004747 n = data.readInt32();
4748 if (n) {
4749 ALOGV("LayerTracing enabled");
4750 mTracing.enable();
4751 doTracing("tracing.enable");
4752 reply->writeInt32(NO_ERROR);
4753 } else {
4754 ALOGV("LayerTracing disabled");
4755 status_t err = mTracing.disable();
4756 reply->writeInt32(err);
4757 }
4758 return NO_ERROR;
4759 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004760 case 1026: { // Get layer tracing status
4761 reply->writeBool(mTracing.isEnabled());
4762 return NO_ERROR;
4763 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004764 // Is a DisplayColorSetting supported?
4765 case 1027: {
4766 int32_t value = data.readInt32();
4767 switch (value) {
4768 case 0:
4769 reply->writeBool(hasWideColorDisplay);
4770 return NO_ERROR;
4771 case 1:
4772 reply->writeBool(true);
4773 return NO_ERROR;
4774 case 2:
4775 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4776 return NO_ERROR;
4777 default:
4778 return BAD_VALUE;
4779 }
4780 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 }
4782 }
4783 return err;
4784}
4785
Steven Thomas6d8110b2017-08-31 18:24:21 -07004786void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004787 android_atomic_or(1, &mRepaintEverything);
4788 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004789}
4790
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004791// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4792class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004793public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004794 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4795 ~WindowDisconnector() {
4796 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004797 }
4798
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004799private:
4800 ANativeWindow* mWindow;
4801 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004802};
4803
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004804status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4805 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4806 int32_t minLayerZ, int32_t maxLayerZ,
4807 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004808 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004810
chaviwa76b2712017-09-20 12:02:26 -07004811 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4812
4813 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004814 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4815
chaviwa76b2712017-09-20 12:02:26 -07004816 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4817
4818 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4819 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004820 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004821}
4822
4823status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004824 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004825 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004826 ATRACE_CALL();
4827
4828 class LayerRenderArea : public RenderArea {
4829 public:
Robert Carr578038f2018-03-09 12:25:24 -08004830 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4831 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004832 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004833 mLayer(layer),
4834 mCrop(crop),
4835 mFlinger(flinger),
4836 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004837 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004838 Rect getBounds() const override {
4839 const Layer::State& layerState(mLayer->getDrawingState());
4840 return Rect(layerState.active.w, layerState.active.h);
4841 }
4842 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4843 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4844 bool isSecure() const override { return false; }
4845 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004846 Rect getSourceCrop() const override {
4847 if (mCrop.isEmpty()) {
4848 return getBounds();
4849 } else {
4850 return mCrop;
4851 }
4852 }
Robert Carr578038f2018-03-09 12:25:24 -08004853 class ReparentForDrawing {
4854 public:
4855 const sp<Layer>& oldParent;
4856 const sp<Layer>& newParent;
4857
4858 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4859 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004860 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004861 }
Robert Carr15eae092018-03-23 13:43:53 -07004862 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004863 };
4864
4865 void render(std::function<void()> drawLayers) override {
4866 if (!mChildrenOnly) {
4867 mTransform = mLayer->getTransform().inverse();
4868 drawLayers();
4869 } else {
4870 Rect bounds = getBounds();
4871 screenshotParentLayer =
4872 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4873 bounds.getWidth(), bounds.getHeight(), 0);
4874
4875 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4876 drawLayers();
4877 }
4878 }
chaviwa76b2712017-09-20 12:02:26 -07004879
chaviwa76b2712017-09-20 12:02:26 -07004880 private:
chaviw7206d492017-11-10 16:16:12 -08004881 const sp<Layer> mLayer;
4882 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004883
4884 // In the "childrenOnly" case we reparent the children to a screenshot
4885 // layer which has no properties set and which does not draw.
4886 sp<ContainerLayer> screenshotParentLayer;
4887 Transform mTransform;
4888
4889 SurfaceFlinger* mFlinger;
4890 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004891 };
4892
4893 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4894 auto parent = layerHandle->owner.promote();
4895
chaviw7206d492017-11-10 16:16:12 -08004896 if (parent == nullptr || parent->isPendingRemoval()) {
4897 ALOGE("captureLayers called with a removed parent");
4898 return NAME_NOT_FOUND;
4899 }
4900
Robert Carr578038f2018-03-09 12:25:24 -08004901 const int uid = IPCThreadState::self()->getCallingUid();
4902 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4903 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4904 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4905 return PERMISSION_DENIED;
4906 }
4907
chaviw7206d492017-11-10 16:16:12 -08004908 Rect crop(sourceCrop);
4909 if (sourceCrop.width() <= 0) {
4910 crop.left = 0;
4911 crop.right = parent->getCurrentState().active.w;
4912 }
4913
4914 if (sourceCrop.height() <= 0) {
4915 crop.top = 0;
4916 crop.bottom = parent->getCurrentState().active.h;
4917 }
4918
4919 int32_t reqWidth = crop.width() * frameScale;
4920 int32_t reqHeight = crop.height() * frameScale;
4921
Robert Carr578038f2018-03-09 12:25:24 -08004922 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004923
Robert Carr578038f2018-03-09 12:25:24 -08004924 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004925 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4926 if (!layer->isVisible()) {
4927 return;
Robert Carr578038f2018-03-09 12:25:24 -08004928 } else if (childrenOnly && layer == parent.get()) {
4929 return;
chaviwa76b2712017-09-20 12:02:26 -07004930 }
4931 visitor(layer);
4932 });
4933 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004934 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004935}
4936
4937status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4938 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004939 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004940 bool useIdentityTransform) {
4941 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004942
Iris Chang7501ed62018-04-30 14:45:42 +08004943 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004944
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004945 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4946 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4947 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4948 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004949
4950 // This mutex protects syncFd and captureResult for communication of the return values from the
4951 // main thread back to this Binder thread
4952 std::mutex captureMutex;
4953 std::condition_variable captureCondition;
4954 std::unique_lock<std::mutex> captureLock(captureMutex);
4955 int syncFd = -1;
4956 std::optional<status_t> captureResult;
4957
Robert Carr03480e22018-01-04 16:02:06 -08004958 const int uid = IPCThreadState::self()->getCallingUid();
4959 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4960
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004961 sp<LambdaMessage> message = new LambdaMessage([&]() {
4962 // If there is a refresh pending, bug out early and tell the binder thread to try again
4963 // after the refresh.
4964 if (mRefreshPending) {
4965 ATRACE_NAME("Skipping screenshot for now");
4966 std::unique_lock<std::mutex> captureLock(captureMutex);
4967 captureResult = std::make_optional<status_t>(EAGAIN);
4968 captureCondition.notify_one();
4969 return;
4970 }
4971
4972 status_t result = NO_ERROR;
4973 int fd = -1;
4974 {
4975 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004976 renderArea.render([&]() {
4977 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4978 useIdentityTransform, forSystem, &fd);
4979 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 }
4981
4982 {
4983 std::unique_lock<std::mutex> captureLock(captureMutex);
4984 syncFd = fd;
4985 captureResult = std::make_optional<status_t>(result);
4986 captureCondition.notify_one();
4987 }
4988 });
4989
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004990 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 if (result == NO_ERROR) {
4992 captureCondition.wait(captureLock, [&]() { return captureResult; });
4993 while (*captureResult == EAGAIN) {
4994 captureResult.reset();
4995 result = postMessageAsync(message);
4996 if (result != NO_ERROR) {
4997 return result;
4998 }
4999 captureCondition.wait(captureLock, [&]() { return captureResult; });
5000 }
5001 result = *captureResult;
5002 }
5003
5004 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005005 sync_wait(syncFd, -1);
5006 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005007 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005008
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005009 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005010}
5011
chaviwa76b2712017-09-20 12:02:26 -07005012void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5013 TraverseLayersFunction traverseLayers, bool yswap,
5014 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005015 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005016
Lloyd Pique144e1162017-12-20 16:44:52 -08005017 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005018
5019 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005020 const auto raWidth = renderArea.getWidth();
5021 const auto raHeight = renderArea.getHeight();
5022
5023 const auto reqWidth = renderArea.getReqWidth();
5024 const auto reqHeight = renderArea.getReqHeight();
5025 Rect sourceCrop = renderArea.getSourceCrop();
5026
Iris Chang7501ed62018-04-30 14:45:42 +08005027 bool filtering = false;
5028 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5029 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5030 static_cast<int32_t>(reqHeight) != raWidth;
5031 } else {
5032 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5033 static_cast<int32_t>(reqHeight) != raHeight;
5034 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005035
Dan Stozac1879002014-05-22 15:59:05 -07005036 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005037 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005038 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005039 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005040 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5041 Transform tr;
5042 uint32_t flags = 0x00;
5043 switch (mPrimaryDisplayOrientation) {
5044 case DisplayState::eOrientation90:
5045 flags = Transform::ROT_90;
5046 break;
5047 case DisplayState::eOrientation180:
5048 flags = Transform::ROT_180;
5049 break;
5050 case DisplayState::eOrientation270:
5051 flags = Transform::ROT_270;
5052 break;
5053 }
5054 tr.set(flags, raWidth, raHeight);
5055 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005056 }
5057
5058 // ensure that sourceCrop is inside screen
5059 if (sourceCrop.left < 0) {
5060 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5061 }
chaviwa76b2712017-09-20 12:02:26 -07005062 if (sourceCrop.right > raWidth) {
5063 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005064 }
5065 if (sourceCrop.top < 0) {
5066 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5067 }
chaviwa76b2712017-09-20 12:02:26 -07005068 if (sourceCrop.bottom > raHeight) {
5069 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005070 }
5071
Chia-I Wu36574d92018-05-16 10:54:36 -07005072 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5073 engine.setOutputDataSpace(Dataspace::SRGB);
5074 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005075
Mathias Agopian180f10d2013-04-10 22:55:41 -07005076 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005077 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005078
Iris Chang7501ed62018-04-30 14:45:42 +08005079 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5080 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5081 // convert hw orientation into flag presentation
5082 // here inverse transform needed
5083 uint8_t hw_rot_90 = 0x00;
5084 uint8_t hw_flip_hv = 0x00;
5085 switch (mPrimaryDisplayOrientation) {
5086 case DisplayState::eOrientation90:
5087 hw_rot_90 = Transform::ROT_90;
5088 hw_flip_hv = Transform::ROT_180;
5089 break;
5090 case DisplayState::eOrientation180:
5091 hw_flip_hv = Transform::ROT_180;
5092 break;
5093 case DisplayState::eOrientation270:
5094 hw_rot_90 = Transform::ROT_90;
5095 break;
5096 }
5097
5098 // transform flags operation
5099 // 1) flip H V if both have ROT_90 flag
5100 // 2) XOR these flags
5101 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5102 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5103 if (rotation_rot_90 & hw_rot_90) {
5104 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5105 }
5106 rotation = static_cast<Transform::orientation_flags>
5107 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5108 }
5109
Mathias Agopian180f10d2013-04-10 22:55:41 -07005110 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005111 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005112 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005113 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114
chaviw50da5042018-04-09 13:49:37 -07005115 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005116 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005117 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005118
chaviwa76b2712017-09-20 12:02:26 -07005119 traverseLayers([&](Layer* layer) {
5120 if (filtering) layer->setFiltering(true);
5121 layer->draw(renderArea, useIdentityTransform);
5122 if (filtering) layer->setFiltering(false);
5123 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005124}
5125
chaviwa76b2712017-09-20 12:02:26 -07005126status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5127 TraverseLayersFunction traverseLayers,
5128 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005129 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005130 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005131 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005132 ATRACE_CALL();
5133
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005134 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005135
5136 traverseLayers([&](Layer* layer) {
5137 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5138 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005139
Robert Carr03480e22018-01-04 16:02:06 -08005140 // We allow the system server to take screenshots of secure layers for
5141 // use in situations like the Screen-rotation animation and place
5142 // the impetus on WindowManager to not persist them.
5143 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005144 ALOGW("FB is protected: PERMISSION_DENIED");
5145 return PERMISSION_DENIED;
5146 }
5147
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005148 // this binds the given EGLImage as a framebuffer for the
5149 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005150 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005151 if (bufferBond.getStatus() != NO_ERROR) {
5152 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005153 return INVALID_OPERATION;
5154 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005155
Dan Stozaabcda352017-06-01 14:37:39 -07005156 // this will in fact render into our dequeued buffer
5157 // via an FBO, which means we didn't have to create
5158 // an EGLSurface and therefore we're not
5159 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005160 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005161
Dan Stozaabcda352017-06-01 14:37:39 -07005162 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005163 getRenderEngine().finish();
5164 *outSyncFd = -1;
5165
chaviwa76b2712017-09-20 12:02:26 -07005166 const auto reqWidth = renderArea.getReqWidth();
5167 const auto reqHeight = renderArea.getReqHeight();
5168
Dan Stozaabcda352017-06-01 14:37:39 -07005169 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5170 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005171 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005172 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005173 } else {
5174 base::unique_fd syncFd = getRenderEngine().flush();
5175 if (syncFd < 0) {
5176 getRenderEngine().finish();
5177 }
5178 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005179 }
5180
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005181 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005182}
5183
Mathias Agopiand5556842013-09-19 17:08:37 -07005184void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005185 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005186 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005187 for (size_t y = 0; y < h; y++) {
5188 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5189 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005190 if (p[x] != 0xFF000000) return;
5191 }
5192 }
chaviwa76b2712017-09-20 12:02:26 -07005193 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005194
Robert Carr2047fae2016-11-28 14:09:09 -08005195 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005196 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005197 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005198 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5199 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5200 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5201 static_cast<float>(state.color.a));
5202 i++;
5203 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005204 }
5205}
5206
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005207// ---------------------------------------------------------------------------
5208
Dan Stoza412903f2017-04-27 13:42:17 -07005209void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5210 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005211}
5212
Dan Stoza412903f2017-04-27 13:42:17 -07005213void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5214 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005215}
5216
chaviwa76b2712017-09-20 12:02:26 -07005217void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5218 int32_t maxLayerZ,
5219 const LayerVector::Visitor& visitor) {
5220 // We loop through the first level of layers without traversing,
5221 // as we need to interpret min/max layer Z in the top level Z space.
5222 for (const auto& layer : mDrawingState.layersSortedByZ) {
5223 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5224 continue;
5225 }
5226 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005227 // relative layers are traversed in Layer::traverseInZOrder
5228 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005229 continue;
5230 }
5231 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005232 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5233 return;
5234 }
chaviwa76b2712017-09-20 12:02:26 -07005235 if (!layer->isVisible()) {
5236 return;
5237 }
5238 visitor(layer);
5239 });
5240 }
5241}
5242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005243}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005244
5245
5246#if defined(__gl_h_)
5247#error "don't include gl/gl.h in this file"
5248#endif
5249
5250#if defined(__gl2_h_)
5251#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005252#endif