blob: 8c46e8af152adf67eca1445c153f33039a91b5a0 [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
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.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"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070090#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
David Sodman7e4ae112018-02-09 15:02:28 -080094#include "android-base/stringprintf.h"
95
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070098#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080099#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900100#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101
chaviw1d044282017-09-27 12:19:28 -0700102#include <layerproto/LayerProtoParser.h>
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104#define DISPLAY_COUNT 1
105
Mathias Agopianfee2b462013-07-03 12:34:01 -0700106/*
107 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
108 * black pixels.
109 */
110#define DEBUG_SCREENSHOTS false
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700116using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700117using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700118using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700119using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
Steven Thomasb02664d2017-07-26 18:48:28 -0700121namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700122
123#pragma clang diagnostic push
124#pragma clang diagnostic error "-Wswitch-enum"
125
126bool isWideColorMode(const ColorMode colorMode) {
127 switch (colorMode) {
128 case ColorMode::DISPLAY_P3:
129 case ColorMode::ADOBE_RGB:
130 case ColorMode::DCI_P3:
131 case ColorMode::BT2020:
132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177} // namespace anonymous
178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179// ---------------------------------------------------------------------------
180
Mathias Agopian99b49842011-06-27 16:05:52 -0700181const String16 sHardwareTest("android.permission.HARDWARE_TEST");
182const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
183const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
184const String16 sDump("android.permission.DUMP");
185
186// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800187int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
188int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700189int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700190bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800191uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800192bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800193bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800194int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800195// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600196bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700197int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700198bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700199
Kalle Raitaa099a242017-01-11 11:17:29 -0800200std::string getHwcServiceName() {
201 char value[PROPERTY_VALUE_MAX] = {};
202 property_get("debug.sf.hwc_service_name", value, "default");
203 ALOGI("Using HWComposer service: '%s'", value);
204 return std::string(value);
205}
206
207bool useTrebleTestingOverride() {
208 char value[PROPERTY_VALUE_MAX] = {};
209 property_get("debug.sf.treble_testing_override", value, "false");
210 ALOGI("Treble testing override: '%s'", value);
211 return std::string(value) == "true";
212}
213
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800214std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
215 switch(displayColorSetting) {
216 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700217 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Enhanced");
222 default:
223 return std::string("Unknown ") +
224 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226}
227
Lloyd Pique99d3da52018-01-22 17:48:03 -0800228NativeWindowSurface::~NativeWindowSurface() = default;
229
230namespace impl {
231
232class NativeWindowSurface final : public android::NativeWindowSurface {
233public:
234 static std::unique_ptr<android::NativeWindowSurface> create(
235 const sp<IGraphicBufferProducer>& producer) {
236 return std::make_unique<NativeWindowSurface>(producer);
237 }
238
239 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
240 : surface(new Surface(producer, false)) {}
241
242 ~NativeWindowSurface() override = default;
243
244private:
245 sp<ANativeWindow> getNativeWindow() const override { return surface; }
246
247 void preallocateBuffers() override { surface->allocateBuffers(); }
248
249 sp<Surface> surface;
250};
251
252} // namespace impl
253
David Sodmanbc815282017-11-05 18:57:52 -0800254SurfaceFlingerBE::SurfaceFlingerBE()
255 : mHwcServiceName(getHwcServiceName()),
256 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800257 mFrameBuckets(),
258 mTotalTime(0),
259 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800260 mComposerSequenceId(0) {
261}
262
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800264 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700266 mTransactionPending(false),
267 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700268 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700269 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700270 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700272 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800274 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800275 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800276 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700278 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700279 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700280 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700281 mDebugInTransaction(0),
282 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700283 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700284 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700285 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800286 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800287 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800288 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700289 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800290 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800291 mCreateBufferQueue(&BufferQueue::createBufferQueue),
292 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800293
294SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800295 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800296
297 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
299
300 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
302
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800303 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700306 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
307 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
308
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700309 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
310 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
311
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800312 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
313 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
314
Steven Thomas050b2c82017-03-06 11:45:16 -0800315 // Vr flinger is only enabled on Daydream ready devices.
316 useVrFlinger = getBool< ISurfaceFlingerConfigs,
317 &ISurfaceFlingerConfigs::useVrFlinger>(false);
318
Fabien Sanglard1971b632017-03-10 14:50:03 -0800319 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
320 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
321
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322 hasWideColorDisplay =
323 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700324 useColorManagement =
325 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600326
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation primaryDisplayOrientation =
328 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
329 V1_1::DisplayOrientation::ORIENTATION_0);
330
331 switch (primaryDisplayOrientation) {
332 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800346
Lloyd Pique41be5d22018-06-21 13:11:48 -0700347 // Note: We create a local temporary with the real DispSync implementation
348 // type temporarily so we can initialize it with the configured values,
349 // before storing it for more generic use using the interface type.
350 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
351 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
352 SurfaceFlinger::dispSyncPresentTimeOffset);
353 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700354
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355 // debugging stuff...
356 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357
Mathias Agopianb4b17302013-03-20 18:36:41 -0700358 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700359 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361 property_get("debug.sf.showupdates", value, "0");
362 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364 property_get("debug.sf.ddms", value, "0");
365 mDebugDDMS = atoi(value);
366 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700367 if (!startDdmConnection()) {
368 // start failed, and DDMS debugging not enabled
369 mDebugDDMS = 0;
370 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700371 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700372 ALOGI_IF(mDebugRegion, "showupdates enabled");
373 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700374
375 property_get("debug.sf.disable_backpressure", value, "0");
376 mPropagateBackpressure = !atoi(value);
377 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700378
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800379 property_get("debug.sf.enable_hwc_vds", value, "0");
380 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800381 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800383 property_get("ro.sf.disable_triple_buffer", value, "1");
384 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800385 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700386
Yiwei Zhang243b3782018-05-15 17:40:04 -0700387 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700388 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
389 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
390
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200391 property_get("debug.sf.early_phase_offset_ns", value, "-1");
392 const int earlySfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
395 const int earlyGlSfOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
398 const int earlyAppOffsetNs = atoi(value);
399
400 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
401 const int earlyGlAppOffsetNs = atoi(value);
402
Ana Krulec98b5b242018-08-10 15:03:23 -0700403 property_get("debug.sf.use_scheduler", value, "0");
404 mUseScheduler = atoi(value);
405
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200406 const VSyncModulator::Offsets earlyOffsets =
407 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
409 const VSyncModulator::Offsets earlyGlOffsets =
410 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
411 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
412 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
413 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700414
Romain Guy11d63f42017-07-20 12:47:14 -0700415 // We should be reading 'persist.sys.sf.color_saturation' here
416 // but since /data may be encrypted, we need to wait until after vold
417 // comes online to attempt to read the property. The property is
418 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800419
420 if (useTrebleTestingOverride()) {
421 // Without the override SurfaceFlinger cannot connect to HIDL
422 // services that are not listed in the manifests. Considered
423 // deriving the setting from the set service name, but it
424 // would be brittle if the name that's not 'default' is used
425 // for production purposes later on.
426 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430void SurfaceFlinger::onFirstRef()
431{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800432 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435SurfaceFlinger::~SurfaceFlinger()
436{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437}
438
Dan Stozac7014012014-02-14 15:03:43 -0800439void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440{
441 // the window manager died on us. prepare its eulogy.
442
Andy McFadden13a082e2012-08-24 10:16:42 -0700443 // restore initial conditions (default device unblank, etc)
444 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445
446 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700447 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800448}
449
Robert Carr1db73f62016-12-21 12:58:51 -0800450static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700451 status_t err = client->initCheck();
452 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800453 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454 }
Robert Carr1db73f62016-12-21 12:58:51 -0800455 return nullptr;
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
459 return initClient(new Client(this));
460}
461
462sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
463 const sp<IGraphicBufferProducer>& gbp) {
464 if (authenticateSurfaceTexture(gbp) == false) {
465 return nullptr;
466 }
467 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
468 if (layer == nullptr) {
469 return nullptr;
470 }
471
472 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473}
474
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700475sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
476 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477{
478 class DisplayToken : public BBinder {
479 sp<SurfaceFlinger> flinger;
480 virtual ~DisplayToken() {
481 // no more references, this display must be terminated
482 Mutex::Autolock _l(flinger->mStateLock);
483 flinger->mCurrentState.displays.removeItem(this);
484 flinger->setTransactionFlags(eDisplayTransactionNeeded);
485 }
486 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700487 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700488 : flinger(flinger) {
489 }
490 };
491
492 sp<BBinder> token = new DisplayToken(this);
493
494 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 DisplayDeviceState info;
496 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700497 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800500 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 return token;
502}
503
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700504void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 Mutex::Autolock _l(mStateLock);
506
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700507 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700508 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700509 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700510 return;
511 }
512
513 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 ALOGE("destroyDisplay called for non-virtual display");
516 return;
517 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700518 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 mCurrentState.displays.removeItemsAt(idx);
520 setTransactionFlags(eDisplayTransactionNeeded);
521}
522
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700524 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800526 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700528 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531void SurfaceFlinger::bootFinished()
532{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700533 if (mStartPropertySetThread->join() != NO_ERROR) {
534 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536 const nsecs_t now = systemTime();
537 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000538 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700539
540 // wait patiently for the window manager death
541 const String16 name("window");
542 sp<IBinder> window(defaultServiceManager()->getService(name));
543 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700544 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545 }
546
Steven Thomas050b2c82017-03-06 11:45:16 -0800547 if (mVrFlinger) {
548 mVrFlinger->OnBootFinished();
549 }
550
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700552 // formerly we would just kill the process, but we now ask it to exit so it
553 // can choose where to stop the animation.
554 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700555
556 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
557 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
558 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700559
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800560 postMessageAsync(new LambdaMessage([this] {
561 readPersistentProperties();
562 mBootStage = BootStage::FINISHED;
563 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800564}
565
Dan Stoza436ccf32018-06-21 12:10:12 -0700566uint32_t SurfaceFlinger::getNewTexture() {
567 {
568 std::lock_guard lock(mTexturePoolMutex);
569 if (!mTexturePool.empty()) {
570 uint32_t name = mTexturePool.back();
571 mTexturePool.pop_back();
572 ATRACE_INT("TexturePoolSize", mTexturePool.size());
573 return name;
574 }
575
576 // The pool was too small, so increase it for the future
577 ++mTexturePoolSize;
578 }
579
580 // The pool was empty, so we need to get a new texture name directly using a
581 // blocking call to the main thread
582 uint32_t name = 0;
583 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
584 return name;
585}
586
Mathias Agopian3f844832013-08-07 21:24:32 -0700587void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700588 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700589}
590
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591// Do not call property_set on main thread which will be blocked by init
592// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700594 ALOGI( "SurfaceFlinger's main thread ready to run. "
595 "Initializing graphics H/W...");
596
Thierry Strudel2924d012017-08-14 15:19:37 -0700597 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700602 if (mUseScheduler) {
603 mScheduler = std::make_unique<Scheduler>();
604 mAppConnectionHandle =
605 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
606 SurfaceFlinger::vsyncPhaseOffsetNs,
607 [this] { resyncWithRateLimit(); },
608 impl::EventThread::InterceptVSyncsCallback());
609 mSfConnectionHandle =
610 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
611 SurfaceFlinger::sfVsyncPhaseOffsetNs,
612 [this] { resyncWithRateLimit(); },
613 [this](nsecs_t timestamp) {
614 mInterceptor->saveVSyncEvent(timestamp);
615 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800616
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
618 mVsyncModulator.setEventThreads(mScheduler->getEventThread(mSfConnectionHandle),
619 mScheduler->getEventThread(mAppConnectionHandle));
620 } else {
621 mEventThreadSource =
622 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
623 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
624 mEventThread =
625 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
626 [this] { resyncWithRateLimit(); },
627 impl::EventThread::InterceptVSyncsCallback(),
628 "appEventThread");
629 mSfEventThreadSource =
630 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
631 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
632
633 mSFEventThread =
634 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
635 [this] { resyncWithRateLimit(); },
636 [this](nsecs_t timestamp) {
637 mInterceptor->saveVSyncEvent(timestamp);
638 },
639 "sfEventThread");
640 mEventQueue->setEventThread(mSFEventThread.get());
641 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
642 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800643
Steven Thomasb02664d2017-07-26 18:48:28 -0700644 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700645 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700646 renderEngineFeature |= (useColorManagement ?
647 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
648 getBE().mRenderEngine = renderengine::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
649 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800650 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700651
652 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
653 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800654 getBE().mHwc.reset(
655 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700656 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800657 // Process any initial hotplug and resulting display changes.
658 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700659 const auto display = getDefaultDisplayDeviceLocked();
660 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
661 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
662 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800663
Lloyd Piquefcd86612017-12-14 17:15:36 -0800664 // make the default display GLContext current so that we can create textures
665 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800667
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700670 // This callback is called from the vr flinger dispatch thread. We
671 // need to call signalTransaction(), which requires holding
672 // mStateLock when we're not on the main thread. Acquiring
673 // mStateLock from the vr flinger dispatch thread might trigger a
674 // deadlock in surface flinger (see b/66916578), so post a message
675 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
678 mVrFlingerRequestsDisplay = requestDisplay;
679 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
683 getHwComposer()
684 .getHwcDisplayId(display->getId())
685 .value_or(0),
686 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (!mVrFlinger) {
688 ALOGE("Failed to start vrflinger");
689 }
690 }
691
Lloyd Pique379adc12018-01-22 17:31:47 -0800692 mEventControlThread = std::make_unique<impl::EventControlThread>(
693 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700694
Mathias Agopian92a979a2012-08-02 18:32:23 -0700695 // initialize our drawing state
696 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700697
Andy McFadden13a082e2012-08-24 10:16:42 -0700698 // set initial conditions (e.g. unblank default device)
699 initializeDisplays();
700
David Sodmanbc815282017-11-05 18:57:52 -0800701 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700702
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 // Inform native graphics APIs whether the present timestamp is supported:
704 if (getHwComposer().hasCapability(
705 HWC2::Capability::PresentFenceIsNotReliable)) {
706 mStartPropertySetThread = new StartPropertySetThread(false);
707 } else {
708 mStartPropertySetThread = new StartPropertySetThread(true);
709 }
710
711 if (mStartPropertySetThread->Start() != NO_ERROR) {
712 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714
Chia-I Wud49d6692018-06-27 07:17:41 +0800715 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
716 // is used to saturate legacy sRGB content. However, to make sure the same color under
717 // Display P3 will be saturated to the same color, we intentionally break the API spec
718 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
719 // such saturation matrix on Display P3 is understood fully, the API should always return
720 // identify matrix.
721 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
722 Dataspace::SRGB_LINEAR);
723
724 // we will apply this on Display P3.
725 if (mEnhancedSaturationMatrix != mat4()) {
726 ColorSpace srgb(ColorSpace::sRGB());
727 ColorSpace displayP3(ColorSpace::DisplayP3());
728 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
729 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
730 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
731 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700734}
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 Mutex::Autolock _l(mStateLock);
738
Romain Guy11d63f42017-07-20 12:47:14 -0700739 char value[PROPERTY_VALUE_MAX];
740
741 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700743 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100745
746 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700747 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700748}
749
Mathias Agopiana67e4182012-06-19 17:26:12 -0700750void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800751 // Start boot animation service by setting a property mailbox
752 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700753 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800754 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700755 if (mStartPropertySetThread->join() != NO_ERROR) {
756 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800757 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758}
759
Mathias Agopian875d8e12013-06-07 15:35:48 -0700760size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800761 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800765 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800768// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800769
Jamie Gennis582270d2011-08-17 18:19:00 -0700770bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800771 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800772 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800773 return authenticateSurfaceTextureLocked(bufferProducer);
774}
775
776bool SurfaceFlinger::authenticateSurfaceTextureLocked(
777 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800778 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800779 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800780}
781
Brian Anderson6b376712017-04-04 10:51:39 -0700782status_t SurfaceFlinger::getSupportedFrameTimestamps(
783 std::vector<FrameEvent>* outSupported) const {
784 *outSupported = {
785 FrameEvent::REQUESTED_PRESENT,
786 FrameEvent::ACQUIRE,
787 FrameEvent::LATCH,
788 FrameEvent::FIRST_REFRESH_START,
789 FrameEvent::LAST_REFRESH_START,
790 FrameEvent::GPU_COMPOSITION_DONE,
791 FrameEvent::DEQUEUE_READY,
792 FrameEvent::RELEASE,
793 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700794 ConditionalLock _l(mStateLock,
795 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700796 if (!getHwComposer().hasCapability(
797 HWC2::Capability::PresentFenceIsNotReliable)) {
798 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
799 }
800 return NO_ERROR;
801}
802
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700803status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
804 Vector<DisplayInfo>* configs) {
805 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 return BAD_VALUE;
807 }
808
Jesse Hall692c7232012-11-08 15:41:56 -0800809 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700810 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
811 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700812 type = i;
813 break;
814 }
815 }
816
817 if (type < 0) {
818 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 // TODO: Not sure if display density should handled by SF any longer
822 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700825 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800826 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 }
829 return density;
830 }
831 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("ro.sf.lcd_density"); }
836 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Steven Thomas6d8110b2017-08-31 18:24:21 -0700840 ConditionalLock _l(mStateLock,
841 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 DisplayInfo info = DisplayInfo();
844
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845 float xdpi = hwConfig->getDpiX();
846 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700847
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700848 info.w = hwConfig->getWidth();
849 info.h = hwConfig->getHeight();
850 // Default display viewport to display width and height
851 info.viewportW = info.w;
852 info.viewportH = info.h;
853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 if (type == DisplayDevice::DISPLAY_PRIMARY) {
855 // The density of the device is provided by a build property
856 float density = Density::getBuildDensity() / 160.0f;
857 if (density == 0) {
858 // the build doesn't provide a density -- this is wrong!
859 // use xdpi instead
860 ALOGE("ro.sf.lcd_density must be defined as a build property");
861 density = xdpi / 160.0f;
862 }
863 if (Density::getEmuDensity()) {
864 // if "qemu.sf.lcd_density" is specified, it overrides everything
865 xdpi = ydpi = density = Density::getEmuDensity();
866 density /= 160.0f;
867 }
868 info.density = density;
869
870 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700871 const auto display = getDefaultDisplayDeviceLocked();
872 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700873
874 // This is for screenrecord
875 const Rect viewport = display->getViewport();
876 if (viewport.isValid()) {
877 info.viewportW = uint32_t(viewport.getWidth());
878 info.viewportH = uint32_t(viewport.getHeight());
879 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700880 } else {
881 // TODO: where should this value come from?
882 static const int TV_DENSITY = 213;
883 info.density = TV_DENSITY / 160.0f;
884 info.orientation = 0;
885 }
886
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 info.xdpi = xdpi;
888 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900890 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891
Andy McFadden91b2ca82014-06-13 14:04:23 -0700892 // This is how far in advance a buffer must be queued for
893 // presentation at a given time. If you want a buffer to appear
894 // on the screen at time N, you must submit the buffer before
895 // (N - presentationDeadline).
896 //
897 // Normally it's one full refresh period (to give SF a chance to
898 // latch the buffer), but this can be reduced by configuring a
899 // DispSync offset. Any additional delays introduced by the hardware
900 // composer or panel must be accounted for here.
901 //
902 // We add an additional 1ms to allow for processing time and
903 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800905 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700906
907 // All non-virtual displays are currently considered secure.
908 info.secure = true;
909
Iris Chang7501ed62018-04-30 14:45:42 +0800910 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700911 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800912 std::swap(info.w, info.h);
913 }
914
Michael Wright28f24d02016-07-12 13:30:53 -0700915 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700916 }
917
Dan Stoza7f7da322014-05-02 15:26:25 -0700918 return NO_ERROR;
919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
922 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700923 return BAD_VALUE;
924 }
925
926 // FIXME for now we always return stats for the primary display
927 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700928 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
929 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return NO_ERROR;
931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
934 const auto display = getDisplayDevice(displayToken);
935 if (!display) {
936 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
944 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700946 return;
947 }
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700950 ALOGW("Trying to set config for virtual display");
951 return;
952 }
953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 display->setActiveConfig(mode);
955 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700956}
957
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700959 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960 Vector<DisplayInfo> configs;
961 getDisplayConfigs(displayToken, &configs);
962 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
963 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
964 configs.size());
965 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700967 const auto display = getDisplayDevice(displayToken);
968 if (!display) {
969 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
970 displayToken.get());
971 } else if (display->isVirtual()) {
972 ALOGW("Attempt to set active config %d for virtual display", mode);
973 } else {
974 setActiveConfigInternal(display, mode);
975 }
976 }));
977
Mathias Agopian888c8222012-08-04 21:10:38 -0700978 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700979}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
981 Vector<ColorMode>* outColorModes) {
982 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700983 return BAD_VALUE;
984 }
985
Michael Wright28f24d02016-07-12 13:30:53 -0700986 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
988 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 type = i;
990 break;
991 }
992 }
993
994 if (type < 0) {
995 return type;
996 }
997
Peiyong Lina52f0292018-03-14 17:26:31 -0700998 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700999 {
1000 ConditionalLock _l(mStateLock,
1001 std::this_thread::get_id() != mMainThreadId);
1002 modes = getHwComposer().getColorModes(type);
1003 }
Michael Wright28f24d02016-07-12 13:30:53 -07001004 outColorModes->clear();
1005 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1006
1007 return NO_ERROR;
1008}
1009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1011 if (const auto display = getDisplayDevice(displayToken)) {
1012 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001013 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001015}
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1018 Dataspace dataSpace, RenderIntent renderIntent) {
1019 ColorMode currentMode = display->getActiveColorMode();
1020 Dataspace currentDataSpace = display->getCompositionDataSpace();
1021 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001022
Peiyong Lin38e9a562018-04-10 16:24:20 -07001023 if (mode == currentMode && dataSpace == currentDataSpace &&
1024 renderIntent == currentRenderIntent) {
1025 return;
1026 }
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001029 ALOGW("Trying to set config for virtual display");
1030 return;
1031 }
1032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033 display->setActiveColorMode(mode);
1034 display->setCompositionDataSpace(dataSpace);
1035 display->setActiveRenderIntent(renderIntent);
1036 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001037
1038 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1040 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001041}
1042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001044 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045 Vector<ColorMode> modes;
1046 getDisplayColorModes(displayToken, &modes);
1047 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1048 if (mode < ColorMode::NATIVE || !exists) {
1049 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1050 decodeColorMode(mode).c_str(), mode, displayToken.get());
1051 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001052 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 const auto display = getDisplayDevice(displayToken);
1054 if (!display) {
1055 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1056 decodeColorMode(mode).c_str(), mode, displayToken.get());
1057 } else if (display->isVirtual()) {
1058 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1059 decodeColorMode(mode).c_str(), mode);
1060 } else {
1061 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1062 RenderIntent::COLORIMETRIC);
1063 }
1064 }));
1065
Michael Wright28f24d02016-07-12 13:30:53 -07001066 return NO_ERROR;
1067}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001068
Svetoslavd85084b2014-03-20 10:28:31 -07001069status_t SurfaceFlinger::clearAnimationFrameStats() {
1070 Mutex::Autolock _l(mStateLock);
1071 mAnimFrameTracker.clearStats();
1072 return NO_ERROR;
1073}
1074
1075status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1076 Mutex::Autolock _l(mStateLock);
1077 mAnimFrameTracker.getStats(outStats);
1078 return NO_ERROR;
1079}
1080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1082 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001083 Mutex::Autolock _l(mStateLock);
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const auto display = getDisplayDeviceLocked(displayToken);
1086 if (!display) {
1087 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 return BAD_VALUE;
1089 }
1090
Peiyong Linfb069302018-04-25 14:34:31 -07001091 // At this point the DisplayDeivce should already be set up,
1092 // meaning the luminance information is already queried from
1093 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001095 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1096 capabilities.getDesiredMaxLuminance(),
1097 capabilities.getDesiredMaxAverageLuminance(),
1098 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001099
1100 return NO_ERROR;
1101}
1102
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001103status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001104 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001105 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001106
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 if (mInjectVSyncs == enable) {
1108 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001109 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110
Ana Krulec98b5b242018-08-10 15:03:23 -07001111 // TODO(akrulec): Part of the Injector should be refactored, so that it
1112 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 if (enable) {
1114 ALOGV("VSync Injections enabled");
1115 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001116 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001117 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001119 impl::EventThread::InterceptVSyncsCallback(),
1120 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001122 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 } else {
1124 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001125 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 }
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001129 }));
1130
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131 return NO_ERROR;
1132}
1133
1134status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 Mutex::Autolock _l(mStateLock);
1136
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137 if (!mInjectVSyncs) {
1138 ALOGE("VSync Injections not enabled");
1139 return BAD_VALUE;
1140 }
1141 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1142 ALOGV("Injecting VSync inside SurfaceFlinger");
1143 mVSyncInjector->onInjectSyncEvent(when);
1144 }
1145 return NO_ERROR;
1146}
1147
Lloyd Pique755e3192018-01-31 16:46:15 -08001148status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1149 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001150 // Try to acquire a lock for 1s, fail gracefully
1151 const status_t err = mStateLock.timedLock(s2ns(1));
1152 const bool locked = (err == NO_ERROR);
1153 if (!locked) {
1154 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1155 return TIMED_OUT;
1156 }
1157
1158 outLayers->clear();
1159 mCurrentState.traverseInZOrder([&](Layer* layer) {
1160 outLayers->push_back(layer->getLayerDebugInfo());
1161 });
1162
1163 mStateLock.unlock();
1164 return NO_ERROR;
1165}
1166
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001167// ----------------------------------------------------------------------------
1168
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001169sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1170 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001171 if (mUseScheduler) {
1172 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1173 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1174 } else {
1175 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1176 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001177 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001178 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1179 return mSFEventThread->createEventConnection();
1180 } else {
1181 return mEventThread->createEventConnection();
1182 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001183 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001184}
1185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187
1188void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001201 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001206 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001207 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208}
1209
1210status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001211 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213 if (res == NO_ERROR) {
1214 msg->wait();
1215 }
1216 return res;
1217}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001218
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001219void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001220 do {
1221 waitForEvent();
1222 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001223}
1224
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225void SurfaceFlinger::enableHardwareVsync() {
1226 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001228 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001229 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001231 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232}
1233
Jesse Hall948fe0c2013-10-14 12:56:09 -07001234void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 Mutex::Autolock _l(mHWVsyncLock);
1236
Jesse Hall948fe0c2013-10-14 12:56:09 -07001237 if (makeAvailable) {
1238 mHWVsyncAvailable = true;
1239 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001240 // Hardware vsync is not currently available, so abort the resync
1241 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001242 return;
1243 }
1244
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001245 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1246 if (!getHwComposer().isConnected(displayId)) {
1247 return;
1248 }
1249
1250 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252
Lloyd Pique41be5d22018-06-21 13:11:48 -07001253 mPrimaryDispSync->reset();
1254 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255
1256 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001257 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryHWVsyncEnabled = true;
1260 }
1261}
1262
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 Mutex::Autolock _l(mHWVsyncLock);
1265 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001266 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001267 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryHWVsyncEnabled = false;
1269 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001270 if (makeUnavailable) {
1271 mHWVsyncAvailable = false;
1272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273}
1274
Tim Murray4a4e4a22016-04-19 16:29:23 +00001275void SurfaceFlinger::resyncWithRateLimit() {
1276 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001277
1278 // No explicit locking is needed here since EventThread holds a lock while calling this method
1279 static nsecs_t sLastResyncAttempted = 0;
1280 const nsecs_t now = systemTime();
1281 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001283 }
Dan Stoza57164302017-05-08 14:03:54 -07001284 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285}
1286
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001287void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1288 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001289 ATRACE_NAME("SF onVsync");
1290
Steven Thomas3cfac282017-02-06 12:29:30 -08001291 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001293 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 return;
1295 }
1296
1297 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001298 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001299 return;
1300 }
1301
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001302 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1303 // For now, we don't do anything with external display vsyncs.
1304 return;
1305 }
1306
Jamie Gennisd1700752013-10-14 12:22:52 -07001307 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001308
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 { // Scope for the lock
1310 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001311 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001312 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001314 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001315
1316 if (needsHwVsync) {
1317 enableHardwareVsync();
1318 } else {
1319 disableHardwareVsync(false);
1320 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001321}
1322
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001323void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001324 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1325 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001326}
1327
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001328void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001329 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001330 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001331 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332
Lloyd Piqueba04e622017-12-14 17:11:26 -08001333 // Ignore events that do not have the right sequenceId.
1334 if (sequenceId != getBE().mComposerSequenceId) {
1335 return;
1336 }
1337
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 // Only lock if we're not on the main thread. This function is normally
1339 // called on a hwbinder thread, but for the primary display it's called on
1340 // the main thread with the state lock already held, so don't attempt to
1341 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001342 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001343
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001344 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001345
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001346 if (std::this_thread::get_id() == mMainThreadId) {
1347 // Process all pending hot plug events immediately if we are on the main thread.
1348 processDisplayHotplugEventsLocked();
1349 }
1350
Lloyd Piqueba04e622017-12-14 17:11:26 -08001351 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001352}
1353
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001354void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001355 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001356 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001359 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001360}
1361
Dan Stoza9e56aa02015-11-02 13:00:03 -08001362void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001363 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365 getHwComposer().setVsyncEnabled(disp,
1366 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001367}
1368
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001370void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001371 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001372 // Clear the drawing state so that the logic inside of
1373 // handleTransactionLocked will fire. It will determine the delta between
1374 // mCurrentState and mDrawingState and re-apply all changes when we make the
1375 // transition.
1376 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001377 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378 mDisplays.clear();
1379}
1380
Steven Thomas050b2c82017-03-06 11:45:16 -08001381void SurfaceFlinger::updateVrFlinger() {
1382 if (!mVrFlinger)
1383 return;
1384 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001386 return;
1387 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 ALOGE("Vr flinger is only supported for remote hardware composer"
1391 " service connections. Ignoring request to transition to vr"
1392 " flinger.");
1393 mVrFlingerRequestsDisplay = false;
1394 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398
Steven Thomas0123ac62018-07-12 11:32:34 -07001399 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001400 LOG_ALWAYS_FATAL_IF(!display);
1401 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001402 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1403 // called below. Clear the reference now so we don't accidentally use it
1404 // later.
1405 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001412 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001413 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1414 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001415 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416
David Sodman105b7dc2017-11-04 20:28:14 -07001417 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1418 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001419
1420 if (vrFlingerRequestsDisplay) {
1421 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
1424 mVisibleRegionsDirty = true;
1425 invalidateHwcGeometry();
1426
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001427 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001428 display = getDefaultDisplayDeviceLocked();
1429 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001430 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001433 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 const nsecs_t period = activeConfig->getVsyncPeriod();
1435 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001437 // The present fences returned from vr_hwc are not an accurate
1438 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001439 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1440 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 // Use phase of 0 since phase is not known.
1443 // Use latency of 0, which will snap to the ideal latency.
1444 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001445
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 resyncToHardwareVsync(false);
1447
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 android_atomic_or(1, &mRepaintEverything);
1449 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450}
1451
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001453 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001456 bool frameMissed = !mHadClientComposition &&
1457 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458 (mPreviousPresentFence->getSignalTime() ==
1459 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001460 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001461 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001462 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001463 mTimeStats.incrementMissedFrames();
1464 if (mPropagateBackpressure) {
1465 signalLayerUpdate();
1466 break;
1467 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001468 }
Dan Stoza50182882016-07-08 12:02:20 -07001469
Steven Thomas050b2c82017-03-06 11:45:16 -08001470 // Now that we're going to make it to the handleMessageTransaction()
1471 // call below it's safe to call updateVrFlinger(), which will
1472 // potentially trigger a display handoff.
1473 updateVrFlinger();
1474
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 bool refreshNeeded = handleMessageTransaction();
1476 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001477 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001478 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001479 // Signal a refresh if a transaction modified the window state,
1480 // a new buffer was latched, or if HWC has requested a full
1481 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 signalRefresh();
1483 }
1484 break;
1485 }
1486 case MessageQueue::REFRESH: {
1487 handleMessageRefresh();
1488 break;
1489 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490 }
1491}
1492
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001494 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001496 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500}
1501
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001504
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001505 mRefreshPending = false;
1506
David Sodmanfa9b2af2017-12-24 13:28:59 -08001507 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001508 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001509 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001510 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001511
David Sodmanfa9b2af2017-12-24 13:28:59 -08001512 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001513 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001514 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001515 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1516 setUpHWComposer(compositionInfo);
1517 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001518 prepareFrame(display);
1519 doDebugFlashRegions(display, repaintEverything);
1520 doComposition(display, repaintEverything);
1521 }
1522
Adrian Roos1e1a1282017-11-01 19:05:31 +01001523 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001524 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001525
1526 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001527 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001530 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001531 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001532 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001533 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001534
Jorim Jaggi90535212018-05-23 23:44:06 +02001535 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001536
David Sodman7e4ae112018-02-09 15:02:28 -08001537 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001538 for (const auto& [token, display] : mDisplays) {
1539 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001540 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001541 compositionInfo.hwc.hwcLayer = nullptr;
1542 }
David Sodmanba340492018-08-05 21:51:33 -07001543 }
David Sodman7e4ae112018-02-09 15:02:28 -08001544
1545 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001547
David Sodmanfa9b2af2017-12-24 13:28:59 -08001548
1549bool SurfaceFlinger::handleMessageInvalidate() {
1550 ATRACE_CALL();
1551 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001552}
1553
David Sodman79bba0e2018-08-05 18:07:49 -07001554void SurfaceFlinger::calculateWorkingSet() {
1555 ATRACE_CALL();
1556 ALOGV(__FUNCTION__);
1557
David Sodman79bba0e2018-08-05 18:07:49 -07001558 // build the h/w work list
1559 if (CC_UNLIKELY(mGeometryInvalid)) {
1560 mGeometryInvalid = false;
1561 for (const auto& [token, display] : mDisplays) {
1562 const auto displayId = display->getId();
1563 if (displayId >= 0) {
1564 const Vector<sp<Layer>>& currentLayers(
1565 display->getVisibleLayersSortedByZ());
1566 for (size_t i = 0; i < currentLayers.size(); i++) {
1567 const auto& layer = currentLayers[i];
1568
1569 if (!layer->hasHwcLayer(displayId)) {
1570 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1571 layer->forceClientComposition(displayId);
1572 continue;
1573 }
1574 }
1575
1576 layer->setGeometry(display, i);
1577 if (mDebugDisableHWC || mDebugRegion) {
1578 layer->forceClientComposition(displayId);
1579 }
1580 }
1581 }
1582 }
1583 }
1584
1585 // Set the per-frame data
1586 for (const auto& [token, display] : mDisplays) {
1587 const auto displayId = display->getId();
1588 if (displayId < 0) {
1589 continue;
1590 }
1591
1592 if (mDrawingState.colorMatrixChanged) {
1593 display->setColorTransform(mDrawingState.colorMatrix);
1594 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1595 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1596 "display %d: %d", displayId, result);
1597 }
1598 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1599 if (layer->isHdrY410()) {
1600 layer->forceClientComposition(displayId);
1601 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1602 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1603 !display->hasHDR10Support()) {
1604 layer->forceClientComposition(displayId);
1605 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1606 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1607 !display->hasHLGSupport()) {
1608 layer->forceClientComposition(displayId);
1609 }
1610
1611 if (layer->getForceClientComposition(displayId)) {
1612 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1613 layer->setCompositionType(displayId, HWC2::Composition::Client);
1614 continue;
1615 }
1616
1617 layer->setPerFrameData(display);
1618 }
1619
Peiyong Lin13effd12018-07-24 17:01:47 -07001620 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001621 ColorMode colorMode;
1622 Dataspace dataSpace;
1623 RenderIntent renderIntent;
1624 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1625 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1626 }
1627 }
1628
1629 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001630
1631 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001632 const auto displayId = display->getId();
1633 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001634 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1635 auto displayId = display->getId();
1636 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1637 if (!layer->setHwcLayer(displayId)) {
1638 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1639 }
David Sodman15fb96e2018-01-07 10:23:24 -08001640 layer->getBE().compositionInfo.hwc.displayId = displayId;
1641 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001642 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1643 }
1644 }
David Sodman79bba0e2018-08-05 18:07:49 -07001645}
1646
David Sodmanfa9b2af2017-12-24 13:28:59 -08001647void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001649 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001650 // is debugging enabled
1651 if (CC_LIKELY(!mDebugRegion))
1652 return;
1653
David Sodmanfa9b2af2017-12-24 13:28:59 -08001654 if (display->isPoweredOn()) {
1655 // transform the dirty region into this screen's coordinate space
1656 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1657 if (!dirtyRegion.isEmpty()) {
1658 // redraw the whole screen
1659 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001660
David Sodmanfa9b2af2017-12-24 13:28:59 -08001661 // and draw the dirty region
1662 const int32_t height = display->getHeight();
1663 auto& engine(getRenderEngine());
1664 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001665
David Sodmanfa9b2af2017-12-24 13:28:59 -08001666 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667 }
1668 }
1669
David Sodmanfa9b2af2017-12-24 13:28:59 -08001670 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671
1672 if (mDebugRegion > 1) {
1673 usleep(mDebugRegion * 1000);
1674 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001677 status_t result = display->prepareFrame(
1678 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679 ALOGE_IF(result != NO_ERROR,
1680 "prepareFrame for display %d failed:"
1681 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001682 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001683 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684}
1685
Adrian Roos1e1a1282017-11-01 19:05:31 +01001686void SurfaceFlinger::doTracing(const char* where) {
1687 ATRACE_CALL();
1688 ATRACE_NAME(where);
1689 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001690 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001691 }
1692}
1693
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001694void SurfaceFlinger::logLayerStats() {
1695 ATRACE_CALL();
1696 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001697 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001698 if (display->isPrimary()) {
1699 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001700 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001701 }
1702 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001703
1704 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001705 }
1706}
1707
David Sodman2b406362017-12-15 13:33:47 -08001708void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 ATRACE_CALL();
1711 ALOGV("preComposition");
1712
David Sodman2b406362017-12-15 13:33:47 -08001713 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1714
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001716 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001717 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718 needExtraInvalidate = true;
1719 }
Robert Carr2047fae2016-11-28 14:09:09 -08001720 });
1721
Mathias Agopiancd60f992012-08-16 16:28:27 -07001722 if (needExtraInvalidate) {
1723 signalLayerUpdate();
1724 }
1725}
1726
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727void SurfaceFlinger::updateCompositorTiming(
1728 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1729 std::shared_ptr<FenceTime>& presentFenceTime) {
1730 // Update queue of past composite+present times and determine the
1731 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001732 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001734 while (!getBE().mCompositePresentTimes.empty()) {
1735 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736 // Cached values should have been updated before calling this method,
1737 // which helps avoid duplicate syscalls.
1738 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1739 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1740 break;
1741 }
1742 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001743 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 }
1745
1746 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001747 while (getBE().mCompositePresentTimes.size() > 16) {
1748 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 }
1750
Brian Andersond0010582017-03-07 13:20:31 -08001751 setCompositorTimingSnapped(
1752 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1753}
1754
1755void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1756 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757 // Integer division and modulo round toward 0 not -inf, so we need to
1758 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001759 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1761 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1762
Brian Andersond0010582017-03-07 13:20:31 -08001763 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1764 if (idealLatency <= 0) {
1765 idealLatency = vsyncInterval;
1766 }
1767
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 // Snap the latency to a value that removes scheduling jitter from the
1769 // composition and present times, which often have >1ms of jitter.
1770 // Reducing jitter is important if an app attempts to extrapolate
1771 // something (such as user input) to an accurate diasplay time.
1772 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1773 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001774 nsecs_t bias = vsyncInterval / 2;
1775 int64_t extraVsyncs =
1776 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1777 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1778 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
David Sodman99974d22017-11-28 12:04:33 -08001780 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1781 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1782 getBE().mCompositorTiming.interval = vsyncInterval;
1783 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784}
1785
David Sodman2b406362017-12-15 13:33:47 -08001786void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001787{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001788 ATRACE_CALL();
1789 ALOGV("postComposition");
1790
Brian Anderson3546a3f2016-07-14 11:51:14 -07001791 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001792 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001793 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001794 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001795 }
1796
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001797 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001798 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001799
David Sodman73beded2017-11-15 11:56:06 -08001800 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001801 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001802 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001803 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001804 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001805 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001806 } else {
1807 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1808 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001809
David Sodman73beded2017-11-15 11:56:06 -08001810 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001811 mPreviousPresentFence =
1812 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1813 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001814 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001815
Lloyd Pique41be5d22018-06-21 13:11:48 -07001816 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1817 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818
David Sodman2b406362017-12-15 13:33:47 -08001819 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820 // when we started doing work for this frame, but that should be okay
1821 // since updateCompositorTiming has snapping logic.
1822 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001823 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001824 CompositorTiming compositorTiming;
1825 {
David Sodman99974d22017-11-28 12:04:33 -08001826 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1827 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001828 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829
Robert Carr2047fae2016-11-28 14:09:09 -08001830 mDrawingState.traverseInZOrder([&](Layer* layer) {
1831 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001832 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001833 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001834 recordBufferingStats(layer->getName().string(),
1835 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001836 }
Robert Carr2047fae2016-11-28 14:09:09 -08001837 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001838
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001839 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001840 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001841 enableHardwareVsync();
1842 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001843 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001844 }
1845 }
1846
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001847 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001848 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001849 enableHardwareVsync();
1850 }
1851 }
1852
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001853 if (mAnimCompositionPending) {
1854 mAnimCompositionPending = false;
1855
Brian Anderson4e606e32017-03-16 15:34:57 -07001856 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001857 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001858 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001859 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001860 // The HWC doesn't support present fences, so use the refresh
1861 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001862 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001863 mAnimFrameTracker.setActualPresentTime(presentTime);
1864 }
1865 mAnimFrameTracker.advanceFrame();
1866 }
Dan Stozab90cf072015-03-05 11:05:59 -08001867
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001868 mTimeStats.incrementTotalFrames();
1869 if (mHadClientComposition) {
1870 mTimeStats.incrementClientCompositionFrames();
1871 }
1872
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001873 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001875 return;
1876 }
1877
1878 nsecs_t currentTime = systemTime();
1879 if (mHasPoweredOff) {
1880 mHasPoweredOff = false;
1881 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001882 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001884 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1885 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001886 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001887 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001888 }
David Sodman4a36e932017-11-07 14:29:47 -08001889 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001890 }
David Sodman4a36e932017-11-07 14:29:47 -08001891 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001892
1893 {
1894 std::lock_guard lock(mTexturePoolMutex);
1895 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1896 if (refillCount > 0) {
1897 const size_t offset = mTexturePool.size();
1898 mTexturePool.resize(mTexturePoolSize);
1899 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1900 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1901 }
1902 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903}
1904
1905void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 ATRACE_CALL();
1907 ALOGV("rebuildLayerStacks");
1908
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001910 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001911 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001912 mVisibleRegionsDirty = false;
1913 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001914
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001915 for (const auto& pair : mDisplays) {
1916 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001917 Region opaqueRegion;
1918 Region dirtyRegion;
1919 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001920 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001921 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 const Rect bounds = display->getBounds();
1923 if (display->isPoweredOn()) {
1924 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925
Jeff Sharkey76488112017-02-27 14:15:18 -07001926 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001927 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001929 Region drawRegion(tr.transform(
1930 layer->visibleNonTransparentRegion));
1931 drawRegion.andSelf(bounds);
1932 if (!drawRegion.isEmpty()) {
1933 layersSortedByZ.add(layer);
1934 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001935 // Clear out the HWC layer if this layer was
1936 // previously visible, but no longer is
1937 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001938 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001939 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001940 // WM changes display->layerStack upon sleep/awake.
1941 // Here we make sure we delete the HWC layers even if
1942 // WM changed their layer stack.
1943 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001944 }
1945
1946 // If a layer is not going to get a release fence because
1947 // it is invisible, but it is also going to release its
1948 // old buffer, add it to the list of layers needing
1949 // fences.
1950 if (hwcLayerDestroyed) {
1951 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1952 mLayersWithQueuedFrames.cend(), layer);
1953 if (found != mLayersWithQueuedFrames.cend()) {
1954 layersNeedingFences.add(layer);
1955 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001956 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001957 });
1958 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001959 display->setVisibleLayersSortedByZ(layersSortedByZ);
1960 display->setLayersNeedingFences(layersNeedingFences);
1961 display->undefinedRegion.set(bounds);
1962 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1963 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001964 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001965 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001967
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001968// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001970// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001971// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001972// The returned HDR data space is one of
1973// - Dataspace::UNKNOWN
1974// - Dataspace::BT2020_HLG
1975// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1977 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001978 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 *outHdrDataSpace = Dataspace::UNKNOWN;
1980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001982 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983 case Dataspace::V0_SCRGB:
1984 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001985 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001986 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001987 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001988 case Dataspace::BT2020_PQ:
1989 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001990 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001992 case Dataspace::BT2020_HLG:
1993 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001994 // When there's mixed PQ content and HLG content, we set the HDR
1995 // data space to be BT2020_PQ and convert HLG to PQ.
1996 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1997 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001998 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001999 break;
2000 default:
2001 break;
2002 }
Romain Guy54f154a2017-10-24 21:40:32 +01002003 }
2004
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002005 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002006}
2007
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002009void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2010 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2012 *outMode = ColorMode::NATIVE;
2013 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002016 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002017
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020
Peiyong Lindfde5112018-06-05 10:58:41 -07002021 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002022 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002023 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002024 if (isHdr) {
2025 bestDataSpace = hdrDataSpace;
2026 }
2027
Chia-I Wu0d711262018-05-21 15:19:35 -07002028 RenderIntent intent;
2029 switch (mDisplayColorSetting) {
2030 case DisplayColorSetting::MANAGED:
2031 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002032 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002033 break;
2034 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002035 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002036 break;
2037 default: // vendor display color setting
2038 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2039 break;
2040 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002043}
2044
David Sodman10a41ff2018-08-05 12:14:17 -07002045void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2046{
2047 HWC2::Error error;
2048 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2049 "CompositionType is sideband, but sideband stream is nullptr");
2050 error = (compositionInfo.hwc.hwcLayer)
2051 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2052 if (error != HWC2::Error::None) {
2053 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2054 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2055 static_cast<int32_t>(error));
2056 }
2057}
2058
2059void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2060{
2061 HWC2::Error error;
2062
2063 if (!compositionInfo.hwc.skipGeometry) {
2064 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2065 ALOGE_IF(error != HWC2::Error::None,
2066 "[SF] Failed to set blend mode %s:"
2067 " %s (%d)",
2068 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2069 static_cast<int32_t>(error));
2070
2071 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2072 ALOGE_IF(error != HWC2::Error::None,
2073 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2074 compositionInfo.hwc.displayFrame.left,
2075 compositionInfo.hwc.displayFrame.right,
2076 compositionInfo.hwc.displayFrame.top,
2077 compositionInfo.hwc.displayFrame.bottom,
2078 to_string(error).c_str(), static_cast<int32_t>(error));
2079
2080 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2081 ALOGE_IF(error != HWC2::Error::None,
2082 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2083 compositionInfo.hwc.sourceCrop.left,
2084 compositionInfo.hwc.sourceCrop.right,
2085 compositionInfo.hwc.sourceCrop.top,
2086 compositionInfo.hwc.sourceCrop.bottom,
2087 to_string(error).c_str(), static_cast<int32_t>(error));
2088
2089 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2090 ALOGE_IF(error != HWC2::Error::None,
2091 "[SF] Failed to set plane alpha %.3f: "
2092 "%s (%d)",
2093 compositionInfo.hwc.alpha,
2094 to_string(error).c_str(), static_cast<int32_t>(error));
2095
2096
2097 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2098 ALOGE_IF(error != HWC2::Error::None,
2099 "[SF] Failed to set Z %u: %s (%d)",
2100 compositionInfo.hwc.z,
2101 to_string(error).c_str(), static_cast<int32_t>(error));
2102
2103 error = (compositionInfo.hwc.hwcLayer)
2104 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2105 ALOGE_IF(error != HWC2::Error::None,
2106 "[SF] Failed to set info (%d)",
2107 static_cast<int32_t>(error));
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set transform %s: "
2112 "%s (%d)",
2113 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2114 static_cast<int32_t>(error));
2115 }
2116
2117 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2118 ALOGE_IF(error != HWC2::Error::None,
2119 "[SF] Failed to set composition type: %s (%d)",
2120 to_string(error).c_str(), static_cast<int32_t>(error));
2121
2122 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2123 ALOGE_IF(error != HWC2::Error::None,
2124 "[SF] Failed to set dataspace: %s (%d)",
2125 to_string(error).c_str(), static_cast<int32_t>(error));
2126
2127 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2128 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2129 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2130 "[SF] Failed to set hdrMetadata: %s (%d)",
2131 to_string(error).c_str(), static_cast<int32_t>(error));
2132
2133 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2134 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2135 ALOGE_IF(error != HWC2::Error::None,
2136 "[SF] Failed to set color: %s (%d)",
2137 to_string(error).c_str(), static_cast<int32_t>(error));
2138 }
2139
2140 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2141 ALOGE_IF(error != HWC2::Error::None,
2142 "[SF] Failed to set visible region: %s (%d)",
2143 to_string(error).c_str(), static_cast<int32_t>(error));
2144
2145 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2146 ALOGE_IF(error != HWC2::Error::None,
2147 "[SF] Failed to set surface damage: %s (%d)",
2148 to_string(error).c_str(), static_cast<int32_t>(error));
2149}
2150
2151void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2152{
2153 HWC2::Error error;
2154
2155 if (compositionInfo.hwc.fence) {
2156 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2157 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2158 ALOGE_IF(error != HWC2::Error::None,
2159 "[SF] Failed to set buffer: %s (%d)",
2160 to_string(error).c_str(), static_cast<int32_t>(error));
2161 }
2162}
2163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002165{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166 bool dirty = !display->getDirtyRegion(false).isEmpty();
2167 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2168 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002169
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170 // If nothing has changed (!dirty), don't recompose.
2171 // If something changed, but we don't currently have any visible layers,
2172 // and didn't when we last did a composition, then skip it this time.
2173 // The second rule does two things:
2174 // - When all layers are removed from a display, we'll emit one black
2175 // frame, then nothing more until we get new layers.
2176 // - When a display is created with a private layer stack, we won't
2177 // emit any black frames until a layer is added to the layer stack.
2178 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002179
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002180 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2181 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002182 mustRecompose ? "doing" : "skipping",
2183 dirty ? "+" : "-",
2184 empty ? "+" : "-",
2185 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002186
David Sodmanfa9b2af2017-12-24 13:28:59 -08002187 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002188
David Sodmanfa9b2af2017-12-24 13:28:59 -08002189 if (mustRecompose) {
2190 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002191 }
2192}
2193
David Sodmanfa9b2af2017-12-24 13:28:59 -08002194void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002195{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002196 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002197 if (!display->isPoweredOn()) {
2198 return;
David Sodman2b406362017-12-15 13:33:47 -08002199 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200
David Sodmanfb95bcc2017-12-22 15:45:30 -08002201 status_t result = display->prepareFrame(
2202 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203 ALOGE_IF(result != NO_ERROR,
2204 "prepareFrame for display %d failed:"
2205 " %d (%s)",
2206 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002207}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002208
David Sodman10a41ff2018-08-05 12:14:17 -07002209void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2210 ATRACE_CALL();
2211 ALOGV("setUpHWComposer");
2212
2213 switch (compositionInfo.compositionType)
2214 {
2215 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002216 break;
2217
David Sodman10a41ff2018-08-05 12:14:17 -07002218 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002219 if (compositionInfo.hwc.hwcLayer) {
2220 auto error = (compositionInfo.hwc.hwcLayer)->
2221 setCompositionType(compositionInfo.compositionType);
2222 ALOGE_IF(error != HWC2::Error::None,
2223 "[SF] Failed to set composition type: %s (%d)",
2224 to_string(error).c_str(), static_cast<int32_t>(error));
2225 }
David Sodman10a41ff2018-08-05 12:14:17 -07002226 break;
2227
2228 case HWC2::Composition::Sideband:
2229 configureHwcCommonData(compositionInfo);
2230 configureSidebandComposition(compositionInfo);
2231 break;
2232
2233 case HWC2::Composition::SolidColor:
2234 configureHwcCommonData(compositionInfo);
2235 break;
2236
2237 case HWC2::Composition::Device:
2238 case HWC2::Composition::Cursor:
2239 configureHwcCommonData(compositionInfo);
2240 configureDeviceComposition(compositionInfo);
2241 break;
2242 }
2243}
2244
David Sodmanfa9b2af2017-12-24 13:28:59 -08002245void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002246 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002247 ALOGV("doComposition");
2248
David Sodmanfa9b2af2017-12-24 13:28:59 -08002249 if (display->isPoweredOn()) {
2250 // transform the dirty region into this screen's coordinate space
2251 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002252
David Sodmanfa9b2af2017-12-24 13:28:59 -08002253 // repaint the framebuffer (if needed)
2254 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002255
David Sodmanfa9b2af2017-12-24 13:28:59 -08002256 display->dirtyRegion.clear();
2257 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002258 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002259 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002260}
2261
David Sodmanfa9b2af2017-12-24 13:28:59 -08002262void SurfaceFlinger::postFrame()
2263{
2264 // |mStateLock| not needed as we are on the main thread
2265 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2266 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2267 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2268 logFrameStats();
2269 }
2270 }
2271}
2272
2273void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274{
Mathias Agopian841cde52012-03-01 15:44:37 -08002275 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002276 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002277
David Sodmanfa9b2af2017-12-24 13:28:59 -08002278 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002279
David Sodmanfa9b2af2017-12-24 13:28:59 -08002280 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002281 const auto displayId = display->getId();
2282 if (displayId >= 0) {
2283 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002284 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 display->onSwapBuffersCompleted();
2286 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002287 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002288 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002289 // The layer buffer from the previous frame (if any) is released
2290 // by HWC only when the release fence from this frame (if any) is
2291 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002292 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2293 if ((displayId >= 0) && hwcLayer) {
2294 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002295 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002296
2297 // If the layer was client composited in the previous frame, we
2298 // need to merge with the previous client target acquire fence.
2299 // Since we do not track that, always merge with the current
2300 // client target acquire fence when it is available, even though
2301 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002302 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002303 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002305 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002306
David Sodman10a41ff2018-08-05 12:14:17 -07002307 if (compositionInfo.layer) {
2308 compositionInfo.layer->onLayerDisplayed(releaseFence);
2309 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002310 }
Chia-I Wu83806892017-11-16 10:50:20 -08002311
2312 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002314 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002316 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002318 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002319 }
2320 }
2321
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 if (displayId >= 0) {
2323 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002324 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002325 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326}
2327
Mathias Agopian87baae12012-07-31 12:38:26 -07002328void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329{
Mathias Agopian841cde52012-03-01 15:44:37 -08002330 ATRACE_CALL();
2331
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002332 // here we keep a copy of the drawing state (that is the state that's
2333 // going to be overwritten by handleTransactionLocked()) outside of
2334 // mStateLock so that the side-effects of the State assignment
2335 // don't happen with mStateLock held (which can cause deadlocks).
2336 State drawingState(mDrawingState);
2337
Mathias Agopianca4d3602011-05-19 15:38:14 -07002338 Mutex::Autolock _l(mStateLock);
2339 const nsecs_t now = systemTime();
2340 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341
Mathias Agopianca4d3602011-05-19 15:38:14 -07002342 // Here we're guaranteed that some transaction flags are set
2343 // so we can call handleTransactionLocked() unconditionally.
2344 // We call getTransactionFlags(), which will also clear the flags,
2345 // with mStateLock held to guarantee that mCurrentState won't change
2346 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002347
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002348 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002349 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002350 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002351
Mathias Agopianca4d3602011-05-19 15:38:14 -07002352 mLastTransactionTime = systemTime() - now;
2353 mDebugInTransaction = 0;
2354 invalidateHwcGeometry();
2355 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002356}
2357
Dominik Laskowski7e045462018-05-30 13:02:02 -07002358DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002360 // Figure out whether the event is for the primary display or an
2361 // external display by matching the Hwc display id against one for a
2362 // connected display. If we did not find a match, we then check what
2363 // displays are not already connected to determine the type. If we don't
2364 // have a connected primary display, we assume the new display is meant to
2365 // be the primary display, and then if we don't have an external display,
2366 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002367 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2368 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002369 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002370 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002371 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002372 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002373 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002374 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002375 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002377 return DisplayDevice::DISPLAY_EXTERNAL;
2378 }
2379
2380 return DisplayDevice::DISPLAY_ID_INVALID;
2381}
2382
Lloyd Piqueba04e622017-12-14 17:11:26 -08002383void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2384 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002385 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002386 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002387 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002388 continue;
2389 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002390
2391 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2392 ALOGE("External displays are not supported by the vr hardware composer.");
2393 continue;
2394 }
2395
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002396 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002397 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002398 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002399 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002400 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002401
2402 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002404 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002405 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002406 DisplayDeviceState info;
2407 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002408 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2409 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002410 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002411 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002412 mInterceptor->saveDisplayCreation(info);
2413 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002415 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002418 if (idx >= 0) {
2419 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002420 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002421 mCurrentState.displays.removeItemsAt(idx);
2422 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002424 }
2425
2426 processDisplayChangesLocked();
2427 }
2428
2429 mPendingHotplugEvents.clear();
2430}
2431
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002433 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002435 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002436 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002437 HdrCapabilities hdrCapabilities;
2438 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002439
Peiyong Lin13effd12018-07-24 17:01:47 -07002440 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002441 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002443 if (isWideColorMode(colorMode)) {
2444 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002446
Dominik Laskowski7e045462018-05-30 13:02:02 -07002447 std::vector<RenderIntent> renderIntents =
2448 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002449 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450 }
tangrobin6753a022018-08-10 10:58:54 +08002451 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002452
tangrobin6753a022018-08-10 10:58:54 +08002453 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002454 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2455 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2456 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457
2458 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2459 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2460
2461 /*
2462 * Create our display's surface
2463 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002464 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002466 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467 renderSurface->setNativeWindow(nativeWindow.get());
2468 const int displayWidth = renderSurface->queryWidth();
2469 const int displayHeight = renderSurface->queryHeight();
2470
2471 // Make sure that composition can never be stalled by a virtual display
2472 // consumer that isn't processing buffers fast enough. We have to do this
2473 // in two places:
2474 // * Here, in case the display is composed entirely by HWC.
2475 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2476 // window's swap interval in eglMakeCurrent, so they'll override the
2477 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002478 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2480 }
2481
Chia-I Wua02871c2018-08-27 14:38:23 -07002482 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2483 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2484
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002486 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002489 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2490 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002491 displayHeight, displayInstallOrientation, hasWideColorGamut,
2492 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2493 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494
2495 if (maxFrameBufferAcquiredBuffers >= 3) {
2496 nativeWindowSurface->preallocateBuffers();
2497 }
2498
2499 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002500 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2501 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002503 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002505 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002506 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002507 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002509 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 display->setLayerStack(state.layerStack);
2511 display->setProjection(state.orientation, state.viewport, state.frame);
2512 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515}
2516
Lloyd Pique347200f2017-12-14 17:00:15 -08002517void SurfaceFlinger::processDisplayChangesLocked() {
2518 // here we take advantage of Vector's copy-on-write semantics to
2519 // improve performance by skipping the transaction entirely when
2520 // know that the lists are identical
2521 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2522 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2523 if (!curr.isIdenticalTo(draw)) {
2524 mVisibleRegionsDirty = true;
2525 const size_t cc = curr.size();
2526 size_t dc = draw.size();
2527
2528 // find the displays that were removed
2529 // (ie: in drawing state but not in current state)
2530 // also handle displays that changed
2531 // (ie: displays that are in both lists)
2532 for (size_t i = 0; i < dc;) {
2533 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2534 if (j < 0) {
2535 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002536 // Call makeCurrent() on the primary display so we can
2537 // be sure that nothing associated with this display
2538 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2540 defaultDisplay->makeCurrent();
2541 }
2542 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2543 display->disconnect(getHwComposer());
2544 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002545 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002546 if (mUseScheduler) {
2547 mScheduler->hotplugReceived(mAppConnectionHandle,
2548 EventThread::DisplayType::Primary, false);
2549 } else {
2550 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2551 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002552 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002553 if (mUseScheduler) {
2554 mScheduler->hotplugReceived(mAppConnectionHandle,
2555 EventThread::DisplayType::External, false);
2556 } else {
2557 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2558 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002559 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002561 } else {
2562 // this display is in both lists. see if something changed.
2563 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002564 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2566 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2567 if (state_binder != draw_binder) {
2568 // changing the surface is like destroying and
2569 // recreating the DisplayDevice, so we just remove it
2570 // from the drawing state, so that it get re-added
2571 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002572 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2573 display->disconnect(getHwComposer());
2574 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002575 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002576 mDrawingState.displays.removeItemsAt(i);
2577 dc--;
2578 // at this point we must loop to the next item
2579 continue;
2580 }
2581
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002582 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002585 }
2586 if ((state.orientation != draw[i].orientation) ||
2587 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002589 }
2590 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002591 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 }
2593 }
2594 }
2595 ++i;
2596 }
2597
2598 // find displays that were added
2599 // (ie: in current state but not in drawing state)
2600 for (size_t i = 0; i < cc; i++) {
2601 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2602 const DisplayDeviceState& state(curr[i]);
2603
2604 sp<DisplaySurface> dispSurface;
2605 sp<IGraphicBufferProducer> producer;
2606 sp<IGraphicBufferProducer> bqProducer;
2607 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002608 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002609
Dominik Laskowski7e045462018-05-30 13:02:02 -07002610 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002611 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 // Virtual displays without a surface are dormant:
2613 // they have external state (layer stack, projection,
2614 // etc.) but no internal state (i.e. a DisplayDevice).
2615 if (state.surface != nullptr) {
2616 // Allow VR composer to use virtual displays.
2617 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2618 int width = 0;
2619 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2620 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2621 int height = 0;
2622 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2623 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2624 int intFormat = 0;
2625 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2626 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002627 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002628
Dominik Laskowski7e045462018-05-30 13:02:02 -07002629 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2630 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002631 }
2632
2633 // TODO: Plumb requested format back up to consumer
2634
2635 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002636 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002637 bqProducer, bqConsumer,
2638 state.displayName);
2639
2640 dispSurface = vds;
2641 producer = vds;
2642 }
2643 } else {
2644 ALOGE_IF(state.surface != nullptr,
2645 "adding a supported display, but rendering "
2646 "surface is provided (%p), ignoring it",
2647 state.surface.get());
2648
Dominik Laskowski7e045462018-05-30 13:02:02 -07002649 displayId = state.type;
2650 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 producer = bqProducer;
2652 }
2653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002656 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002657 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002659 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002660 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002661 if (mUseScheduler) {
2662 mScheduler->hotplugReceived(mAppConnectionHandle,
2663 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002664 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002665 } else {
2666 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2667 true);
2668 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002669 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002670 if (mUseScheduler) {
2671 mScheduler->hotplugReceived(mAppConnectionHandle,
2672 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002673 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002674 } else {
2675 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2676 true);
2677 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002678 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 }
2680 }
2681 }
2682 }
2683 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002684
2685 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002686}
2687
Mathias Agopian87baae12012-07-31 12:38:26 -07002688void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002689{
Dan Stoza7dde5992015-05-22 09:51:44 -07002690 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002691 mCurrentState.traverseInZOrder([](Layer* layer) {
2692 layer->notifyAvailableFrames();
2693 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 /*
2696 * Traversal of the children
2697 * (perform the transaction for each of them if needed)
2698 */
2699
Mathias Agopian3559b072012-08-15 13:46:03 -07002700 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002701 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002703 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704
2705 const uint32_t flags = layer->doTransaction(0);
2706 if (flags & Layer::eVisibleRegion)
2707 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002708 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 }
2710
2711 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002712 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 */
2714
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002717 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002720 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002721 // The transform hint might have changed for some layers
2722 // (either because a display has changed, or because a layer
2723 // as changed).
2724 //
2725 // Walk through all the layers in currentLayers,
2726 // and update their transform hint.
2727 //
2728 // If a layer is visible only on a single display, then that
2729 // display is used to calculate the hint, otherwise we use the
2730 // default display.
2731 //
2732 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2733 // the hint is set before we acquire a buffer from the surface texture.
2734 //
2735 // NOTE: layer transactions have taken place already, so we use their
2736 // drawing state. However, SurfaceFlinger's own transaction has not
2737 // happened yet, so we must use the current state layer list
2738 // (soon to become the drawing state list).
2739 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002741 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002742 bool first = true;
2743 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002744 // NOTE: we rely on the fact that layers are sorted by
2745 // layerStack first (so we don't have to traverse the list
2746 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002748 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002749 currentlayerStack = layerStack;
2750 // figure out if this layerstack is mirrored
2751 // (more than one display) if so, pick the default display,
2752 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 hintDisplay = nullptr;
2754 for (const auto& [token, display] : mDisplays) {
2755 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2756 if (hintDisplay) {
2757 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002758 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002761 }
2762 }
2763 }
2764 }
Chet Haase91d25932013-04-11 15:24:55 -07002765
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002767 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2768 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002769
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002770 // could be null when this layer is using a layerStack
2771 // that is not visible on any display. Also can occur at
2772 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002773 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002774 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002775
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002777 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 if (hintDisplay) {
2779 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002780 }
Robert Carr2047fae2016-11-28 14:09:09 -08002781
2782 first = false;
2783 });
Mathias Agopian84300952012-11-21 16:02:13 -08002784 }
2785
2786
Mathias Agopian3559b072012-08-15 13:46:03 -07002787 /*
2788 * Perform our own transaction if needed
2789 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790
2791 if (mLayersAdded) {
2792 mLayersAdded = false;
2793 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 mVisibleRegionsDirty = true;
2795 }
2796
2797 // some layers might have been removed, so
2798 // we need to update the regions they're exposing.
2799 if (mLayersRemoved) {
2800 mLayersRemoved = false;
2801 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002802 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002804 // this layer is not visible anymore
2805 // TODO: we could traverse the tree from front to back and
2806 // compute the actual visible region
2807 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 Region visibleReg;
2809 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002810 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002811 }
Robert Carr2047fae2016-11-28 14:09:09 -08002812 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814
2815 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002816
2817 updateCursorAsync();
2818}
2819
2820void SurfaceFlinger::updateCursorAsync()
2821{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002823 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002824 continue;
2825 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002827 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2828 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002829 }
2830 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831}
2832
2833void SurfaceFlinger::commitTransaction()
2834{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002835 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002836 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 for (const auto& l : mLayersPendingRemoval) {
2838 recordBufferingStats(l->getName().string(),
2839 l->getOccupancyHistory(true));
2840 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002841 }
2842 mLayersPendingRemoval.clear();
2843 }
2844
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002845 // If this transaction is part of a window animation then the next frame
2846 // we composite should be considered an animation as well.
2847 mAnimCompositionPending = mAnimTransactionPending;
2848
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002850 // clear the "changed" flags in current state
2851 mCurrentState.colorMatrixChanged = false;
2852
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 mDrawingState.traverseInZOrder([](Layer* layer) {
2854 layer->commitChildList();
2855 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002856 mTransactionPending = false;
2857 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002861void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2862 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002863 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 Region aboveOpaqueLayers;
2867 Region aboveCoveredLayers;
2868 Region dirty;
2869
Mathias Agopian87baae12012-07-31 12:38:26 -07002870 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
Robert Carr2047fae2016-11-28 14:09:09 -08002872 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002874 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875
Jesse Hall01e29052013-02-19 16:13:35 -08002876 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002877 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002878 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002879 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002880
Mathias Agopianab028732010-03-16 16:41:46 -07002881 /*
2882 * opaqueRegion: area of a surface that is fully opaque.
2883 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002885
2886 /*
2887 * visibleRegion: area of a surface that is visible on screen
2888 * and not fully transparent. This is essentially the layer's
2889 * footprint minus the opaque regions above it.
2890 * Areas covered by a translucent surface are considered visible.
2891 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002893
2894 /*
2895 * coveredRegion: area of a surface that is covered by all
2896 * visible regions above it (which includes the translucent areas).
2897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002899
Jesse Halla8026d22012-09-25 13:25:04 -07002900 /*
2901 * transparentRegion: area of a surface that is hinted to be completely
2902 * transparent. This is only used to tell when the layer has no visible
2903 * non-transparent regions and can be removed from the layer list. It
2904 * does not affect the visibleRegion of this layer or any layers
2905 * beneath it. The hint may not be correct if apps don't respect the
2906 * SurfaceView restrictions (which, sadly, some don't).
2907 */
2908 Region transparentRegion;
2909
Mathias Agopianab028732010-03-16 16:41:46 -07002910
2911 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002912 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002913 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002916 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002917 if (!visibleRegion.isEmpty()) {
2918 // Remove the transparent area from the visible region
2919 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002920 if (tr.preserveRects()) {
2921 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002922 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002923 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002924 // transformation too complex, can't do the
2925 // transparent region optimization.
2926 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002927 }
Mathias Agopianab028732010-03-16 16:41:46 -07002928 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929
Mathias Agopianab028732010-03-16 16:41:46 -07002930 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002932 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002933 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002934 // the opaque region is the layer's footprint
2935 opaqueRegion = visibleRegion;
2936 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 }
2938 }
2939
Robert Carre5f4f692018-01-12 13:12:28 -08002940 if (visibleRegion.isEmpty()) {
2941 layer->clearVisibilityRegions();
2942 return;
2943 }
2944
Mathias Agopianab028732010-03-16 16:41:46 -07002945 // Clip the covered region to the visible region
2946 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2947
2948 // Update aboveCoveredLayers for next (lower) layer
2949 aboveCoveredLayers.orSelf(visibleRegion);
2950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 // subtract the opaque region covered by the layers above us
2952 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953
2954 // compute this layer's dirty region
2955 if (layer->contentDirty) {
2956 // we need to invalidate the whole region
2957 dirty = visibleRegion;
2958 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 layer->contentDirty = false;
2961 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002962 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002963 * the exposed region consists of two components:
2964 * 1) what's VISIBLE now and was COVERED before
2965 * 2) what's EXPOSED now less what was EXPOSED before
2966 *
2967 * note that (1) is conservative, we start with the whole
2968 * visible region but only keep what used to be covered by
2969 * something -- which mean it may have been exposed.
2970 *
2971 * (2) handles areas that were not covered by anything but got
2972 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002973 */
Mathias Agopianab028732010-03-16 16:41:46 -07002974 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 const Region oldVisibleRegion = layer->visibleRegion;
2976 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002977 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2978 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 }
2980 dirty.subtractSelf(aboveOpaqueLayers);
2981
2982 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002983 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984
Mathias Agopianab028732010-03-16 16:41:46 -07002985 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002987
Jesse Halla8026d22012-09-25 13:25:04 -07002988 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 layer->setVisibleRegion(visibleRegion);
2990 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002991 layer->setVisibleNonTransparentRegion(
2992 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002993 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994
Mathias Agopian87baae12012-07-31 12:38:26 -07002995 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Chia-I Wuab0c3192017-08-01 11:29:00 -07002998void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002999 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003000 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3001 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003002 }
3003 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003004}
3005
Dan Stoza6b9454d2014-11-07 16:00:59 -08003006bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 ALOGV("handlePageFlip");
3009
Brian Andersond6927fb2016-07-23 23:37:30 -07003010 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003013 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003014 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003015
3016 // Store the set of layers that need updates. This set must not change as
3017 // buffers are being latched, as this could result in a deadlock.
3018 // Example: Two producers share the same command stream and:
3019 // 1.) Layer 0 is latched
3020 // 2.) Layer 0 gets a new frame
3021 // 2.) Layer 1 gets a new frame
3022 // 3.) Layer 1 is latched.
3023 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3024 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003025 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003026 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003027 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003028 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003029 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003030 } else {
3031 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003032 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003033 } else {
3034 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035 }
Robert Carr2047fae2016-11-28 14:09:09 -08003036 });
3037
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003039 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003040 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003041 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003042 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003043 newDataLatched = true;
3044 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003046
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003047 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048
3049 // If we will need to wake up at some time in the future to deal with a
3050 // queued frame that shouldn't be displayed during this vsync period, wake
3051 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003052 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003053 signalLayerUpdate();
3054 }
3055
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003056 // enter boot animation on first buffer latch
3057 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3058 ALOGI("Enter boot animation");
3059 mBootStage = BootStage::BOOTANIMATION;
3060 }
3061
Dan Stoza6b9454d2014-11-07 16:00:59 -08003062 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003063 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064}
3065
Mathias Agopianad456f92011-01-13 17:53:01 -08003066void SurfaceFlinger::invalidateHwcGeometry()
3067{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003069}
3070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3072 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003073 // We only need to actually compose the display if:
3074 // 1) It is being handled by hardware composer, which may need this to
3075 // keep its virtual display state machine in sync, or
3076 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003077 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003078 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003079 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003080 return;
3081 }
3082
Dan Stoza9e56aa02015-11-02 13:00:03 -08003083 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003084 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003085
3086 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003087 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088}
3089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003090bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 const Region bounds(display->bounds());
3094 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003095 const auto displayId = display->getId();
3096 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003097 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003098
Chia-I Wu8e50e692018-05-04 10:12:37 -07003099 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003100 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003101
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 if (hasClientComposition) {
3103 ALOGV("hasClientComposition");
3104
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003105 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003106 if (display->hasWideColorGamut()) {
3107 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003108 }
3109 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003110 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003111 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003112
Dominik Laskowski7e045462018-05-30 13:02:02 -07003113 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003114 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3115 HWC2::Capability::SkipClientColorTransform);
3116
Chia-I Wud49d6692018-06-27 07:17:41 +08003117 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003118 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3119 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003120 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 }
3122
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 // The current enhanced saturation matrix is designed to enhance Display P3,
3124 // thus we only apply this matrix when the render intent is not colorimetric
3125 // and the output color space is Display P3.
3126 needsEnhancedColorMatrix =
3127 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3128 outputDataspace == Dataspace::DISPLAY_P3);
3129 if (needsEnhancedColorMatrix) {
3130 colorMatrix *= mEnhancedSaturationMatrix;
3131 }
3132
3133 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003135 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003136 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003137 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003138 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003139
3140 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003141 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3142 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3143 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003144 }
3145 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003146 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003147
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003148 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003149 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003150 // when using overlays, we assume a fully transparent framebuffer
3151 // NOTE: we could reduce how much we need to clear, for instance
3152 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003153 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003154 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003155 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003156 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003157 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003158 // we're left with the letterbox region
3159 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003160 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003161
3162 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003163 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003164
Mathias Agopianb9494d52012-04-18 02:28:45 -07003165 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003166 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003167 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003168 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003169 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003170 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003171
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003172 const Rect& bounds = display->getBounds();
3173 const Rect& scissor = display->getScissor();
3174 if (scissor != bounds) {
3175 // scissor doesn't match the screen's dimensions, so we
3176 // need to clear everything outside of it and enable
3177 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003178
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003179 // enable scissor for this frame
3180 const uint32_t height = display->getHeight();
3181 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3182 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003183 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003184 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003185
Mathias Agopian85d751c2012-08-29 16:59:24 -07003186 /*
3187 * and then, render the layers targeted at the framebuffer
3188 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003189
Dan Stoza9e56aa02015-11-02 13:00:03 -08003190 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003191 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003192 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003193 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3194 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003195 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003196 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3197 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003198 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003199 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003200 case HWC2::Composition::Cursor:
3201 case HWC2::Composition::Device:
3202 case HWC2::Composition::Sideband:
3203 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003204 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3205 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3206 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3207 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003208 // never clear the very first layer since we're
3209 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003210 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003211 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003213 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003214 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003215 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003216 break;
3217 }
3218 default:
3219 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003220 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003221 } else {
3222 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003223 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003224 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003225 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003226
Chia-I Wud49d6692018-06-27 07:17:41 +08003227 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003228 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003229 }
3230
Mathias Agopianf45c5102012-10-24 16:29:17 -07003231 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003232 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003233 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234}
3235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003236void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3237 const Region& region) const {
3238 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003239 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003240 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241}
3242
Dan Stoza7d89d062015-04-30 13:29:25 -07003243status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003244 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003245 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246 const sp<Layer>& lbc,
3247 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003248{
Dan Stoza7d89d062015-04-30 13:29:25 -07003249 // add this layer to the current state list
3250 {
3251 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003252 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003253 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3254 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003255 return NO_MEMORY;
3256 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 if (parent == nullptr) {
3258 mCurrentState.layersSortedByZ.add(lbc);
3259 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003260 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003261 ALOGE("addClientLayer called with a removed parent");
3262 return NAME_NOT_FOUND;
3263 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003264 parent->addChild(lbc);
3265 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003266
Yiwei Zhang243b3782018-05-15 17:40:04 -07003267 if (gbc != nullptr) {
3268 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3269 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3270 mMaxGraphicBufferProducerListSize,
3271 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3272 mGraphicBufferProducerList.size(),
3273 mMaxGraphicBufferProducerListSize, mNumLayers);
3274 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 mLayersAdded = true;
3276 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003277 }
3278
Mathias Agopian96f08192010-06-02 23:28:45 -07003279 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003280 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003281
Dan Stoza7d89d062015-04-30 13:29:25 -07003282 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003283}
3284
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003285status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003286 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003287 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3288}
Robert Carr7f9b8992017-03-10 11:08:39 -08003289
chaviwca27f252018-02-06 16:46:39 -08003290status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3291 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003292 if (layer->isPendingRemoval()) {
3293 return NO_ERROR;
3294 }
3295
Robert Carr1f0a16a2016-10-24 16:27:39 -07003296 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003297 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003298 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003299 if (topLevelOnly) {
3300 return NO_ERROR;
3301 }
3302
Chia-I Wu98f1c102017-05-30 14:54:08 -07003303 sp<Layer> ancestor = p;
3304 while (ancestor->getParent() != nullptr) {
3305 ancestor = ancestor->getParent();
3306 }
3307 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3308 ALOGE("removeLayer called with a layer whose parent has been removed");
3309 return NAME_NOT_FOUND;
3310 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003311
3312 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003313 } else {
3314 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003315 }
3316
Robert Carr136e2f62017-02-08 17:54:29 -08003317 // As a matter of normal operation, the LayerCleaner will produce a second
3318 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3319 // so we will succeed in promoting it, but it's already been removed
3320 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3321 // otherwise something has gone wrong and we are leaking the layer.
3322 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003323 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3324 layer->getName().string(),
3325 (p != nullptr) ? p->getName().string() : "no-parent");
3326 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003327 } else if (index < 0) {
3328 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003329 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003330
Chia-I Wuc6657022017-08-15 11:18:17 -07003331 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003332 mLayersPendingRemoval.add(layer);
3333 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003334 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003335 setTransactionFlags(eTransactionNeeded);
3336 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337}
3338
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003339uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003340 return android_atomic_release_load(&mTransactionFlags);
3341}
3342
Mathias Agopian3f844832013-08-07 21:24:32 -07003343uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3345}
3346
Mathias Agopian3f844832013-08-07 21:24:32 -07003347uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003348 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3349}
3350
3351uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3352 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003354 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003356 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 }
3358 return old;
3359}
3360
chaviwca27f252018-02-06 16:46:39 -08003361bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3362 for (const ComposerState& state : states) {
3363 // Here we need to check that the interface we're given is indeed
3364 // one of our own. A malicious client could give us a nullptr
3365 // IInterface, or one of its own or even one of our own but a
3366 // different type. All these situations would cause us to crash.
3367 if (state.client == nullptr) {
3368 return true;
3369 }
3370
3371 sp<IBinder> binder = IInterface::asBinder(state.client);
3372 if (binder == nullptr) {
3373 return true;
3374 }
3375
3376 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3377 return true;
3378 }
3379 }
3380 return false;
3381}
3382
Mathias Agopian8b33f032012-07-24 20:43:54 -07003383void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003384 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003385 const Vector<DisplayState>& displays,
3386 uint32_t flags)
3387{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003388 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003389 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003390 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391
chaviwca27f252018-02-06 16:46:39 -08003392 if (containsAnyInvalidClientState(states)) {
3393 return;
3394 }
3395
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003396 if (flags & eAnimation) {
3397 // For window updates that are part of an animation we must wait for
3398 // previous animation "frames" to be handled.
3399 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003400 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003401 if (CC_UNLIKELY(err != NO_ERROR)) {
3402 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003403 // caller after a few seconds.
3404 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3405 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003406 mAnimTransactionPending = false;
3407 break;
3408 }
3409 }
3410 }
3411
chaviwca27f252018-02-06 16:46:39 -08003412 for (const DisplayState& display : displays) {
3413 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003414 }
3415
chaviwca27f252018-02-06 16:46:39 -08003416 for (const ComposerState& state : states) {
3417 transactionFlags |= setClientStateLocked(state);
3418 }
3419
3420 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3421 // as destroyed should only occur after setting all other states. This is to allow for a
3422 // child re-parent to happen before marking its original parent as destroyed (which would
3423 // then mark the child as destroyed).
3424 for (const ComposerState& state : states) {
3425 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003426 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003427
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003428 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3429 // anyway. This can be used as a flush mechanism for previous async transactions.
3430 // Empty animation transaction can be used to simulate back-pressure, so also force a
3431 // transaction for empty animation transactions.
3432 if (transactionFlags == 0 &&
3433 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003434 transactionFlags = eTransactionNeeded;
3435 }
3436
Mathias Agopian386aa982011-11-07 21:58:03 -08003437 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003438 if (mInterceptor->isEnabled()) {
3439 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003440 }
Irvel468051e2016-06-13 16:44:44 -07003441
Mathias Agopian386aa982011-11-07 21:58:03 -08003442 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003443 const auto start = (flags & eEarlyWakeup)
3444 ? VSyncModulator::TransactionStart::EARLY
3445 : VSyncModulator::TransactionStart::NORMAL;
3446 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003447
3448 // if this is a synchronous transaction, wait for it to take effect
3449 // before returning.
3450 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003451 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003452 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003453 if (flags & eAnimation) {
3454 mAnimTransactionPending = true;
3455 }
3456 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003457 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3458 if (CC_UNLIKELY(err != NO_ERROR)) {
3459 // just in case something goes wrong in SF, return to the
3460 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003461 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3462 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 break;
3464 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003465 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466 }
3467}
3468
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003469uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3470 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3471 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003472
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003474 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3475
3476 const uint32_t what = s.what;
3477 if (what & DisplayState::eSurfaceChanged) {
3478 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3479 state.surface = s.surface;
3480 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003481 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003483 if (what & DisplayState::eLayerStackChanged) {
3484 if (state.layerStack != s.layerStack) {
3485 state.layerStack = s.layerStack;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 }
3489 if (what & DisplayState::eDisplayProjectionChanged) {
3490 if (state.orientation != s.orientation) {
3491 state.orientation = s.orientation;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 if (state.frame != s.frame) {
3495 state.frame = s.frame;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 if (state.viewport != s.viewport) {
3499 state.viewport = s.viewport;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 }
3503 if (what & DisplayState::eDisplaySizeChanged) {
3504 if (state.width != s.width) {
3505 state.width = s.width;
3506 flags |= eDisplayTransactionNeeded;
3507 }
3508 if (state.height != s.height) {
3509 state.height = s.height;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 }
3513
Mathias Agopiane57f2922012-08-09 16:29:12 -07003514 return flags;
3515}
3516
Robert Carrd4ae7f32018-06-07 16:10:57 -07003517bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3518 IPCThreadState* ipc = IPCThreadState::self();
3519 const int pid = ipc->getCallingPid();
3520 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003521 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003522 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003523 return false;
3524 }
3525 return true;
3526}
3527
chaviwca27f252018-02-06 16:46:39 -08003528uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3529 const layer_state_t& s = composerState.state;
3530 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3531
Mathias Agopian13127d82013-03-05 17:47:11 -08003532 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003533 if (layer == nullptr) {
3534 return 0;
3535 }
3536
3537 if (layer->isPendingRemoval()) {
3538 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3539 return 0;
3540 }
3541
3542 uint32_t flags = 0;
3543
3544 const uint32_t what = s.what;
3545 bool geometryAppliesWithResize =
3546 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003547
3548 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3549 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003550 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003551 layer->pushPendingState();
3552 }
3553
chaviw8b3871a2017-11-01 17:41:01 -07003554 if (what & layer_state_t::ePositionChanged) {
3555 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3556 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 }
3559 if (what & layer_state_t::eLayerChanged) {
3560 // NOTE: index needs to be calculated before we update the state
3561 const auto& p = layer->getParent();
3562 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003563 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 mCurrentState.layersSortedByZ.removeAt(idx);
3566 mCurrentState.layersSortedByZ.add(layer);
3567 // we need traversal (state changed)
3568 // AND transaction (list changed)
3569 flags |= eTransactionNeeded|eTraversalNeeded;
3570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 } else {
3572 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003573 flags |= eTransactionNeeded|eTraversalNeeded;
3574 }
3575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 }
3577 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003578 // NOTE: index needs to be calculated before we update the state
3579 const auto& p = layer->getParent();
3580 if (p == nullptr) {
3581 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3582 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3583 mCurrentState.layersSortedByZ.removeAt(idx);
3584 mCurrentState.layersSortedByZ.add(layer);
3585 // we need traversal (state changed)
3586 // AND transaction (list changed)
3587 flags |= eTransactionNeeded|eTraversalNeeded;
3588 }
3589 } else {
3590 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 }
3594 }
3595 if (what & layer_state_t::eSizeChanged) {
3596 if (layer->setSize(s.w, s.h)) {
3597 flags |= eTraversalNeeded;
3598 }
3599 }
3600 if (what & layer_state_t::eAlphaChanged) {
3601 if (layer->setAlpha(s.alpha))
3602 flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eColorChanged) {
3605 if (layer->setColor(s.color))
3606 flags |= eTraversalNeeded;
3607 }
3608 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003609 // TODO: b/109894387
3610 //
3611 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3612 // rotation. To see the problem observe that if we have a square parent, and a child
3613 // of the same size, then we rotate the child 45 degrees around it's center, the child
3614 // must now be cropped to a non rectangular 8 sided region.
3615 //
3616 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3617 // private API, and the WindowManager only uses rotation in one case, which is on a top
3618 // level layer in which cropping is not an issue.
3619 //
3620 // However given that abuse of rotation matrices could lead to surfaces extending outside
3621 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3622 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3623 // transformations.
3624 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003625 flags |= eTraversalNeeded;
3626 }
3627 if (what & layer_state_t::eTransparentRegionChanged) {
3628 if (layer->setTransparentRegionHint(s.transparentRegion))
3629 flags |= eTraversalNeeded;
3630 }
3631 if (what & layer_state_t::eFlagsChanged) {
3632 if (layer->setFlags(s.flags, s.mask))
3633 flags |= eTraversalNeeded;
3634 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003635 if (what & layer_state_t::eCropChanged_legacy) {
3636 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003637 flags |= eTraversalNeeded;
3638 }
chaviw8b3871a2017-11-01 17:41:01 -07003639 if (what & layer_state_t::eLayerStackChanged) {
3640 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3641 // We only allow setting layer stacks for top level layers,
3642 // everything else inherits layer stack from its parent.
3643 if (layer->hasParent()) {
3644 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3645 layer->getName().string());
3646 } else if (idx < 0) {
3647 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3648 "that also does not appear in the top level layer list. Something"
3649 " has gone wrong.", layer->getName().string());
3650 } else if (layer->setLayerStack(s.layerStack)) {
3651 mCurrentState.layersSortedByZ.removeAt(idx);
3652 mCurrentState.layersSortedByZ.add(layer);
3653 // we need traversal (state changed)
3654 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003655 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003656 }
3657 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003658 if (what & layer_state_t::eDeferTransaction_legacy) {
3659 if (s.barrierHandle_legacy != nullptr) {
3660 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3661 } else if (s.barrierGbp_legacy != nullptr) {
3662 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003663 if (authenticateSurfaceTextureLocked(gbp)) {
3664 const auto& otherLayer =
3665 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003666 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003667 } else {
3668 ALOGE("Attempt to defer transaction to to an"
3669 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003670 }
3671 }
chaviw8b3871a2017-11-01 17:41:01 -07003672 // We don't trigger a traversal here because if no other state is
3673 // changed, we don't want this to cause any more work
3674 }
3675 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003676 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003677 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003678 if (!hadParent) {
3679 mCurrentState.layersSortedByZ.remove(layer);
3680 }
chaviw8b3871a2017-11-01 17:41:01 -07003681 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003682 }
chaviw8b3871a2017-11-01 17:41:01 -07003683 }
3684 if (what & layer_state_t::eReparentChildren) {
3685 if (layer->reparentChildren(s.reparentHandle)) {
3686 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003687 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003688 }
chaviw8b3871a2017-11-01 17:41:01 -07003689 if (what & layer_state_t::eDetachChildren) {
3690 layer->detachChildren();
3691 }
3692 if (what & layer_state_t::eOverrideScalingModeChanged) {
3693 layer->setOverrideScalingMode(s.overrideScalingMode);
3694 // We don't trigger a traversal here because if no other state is
3695 // changed, we don't want this to cause any more work
3696 }
Marissa Wall61c58622018-07-18 10:12:20 -07003697 if (what & layer_state_t::eTransformChanged) {
3698 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3699 }
3700 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3701 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3702 flags |= eTraversalNeeded;
3703 }
3704 if (what & layer_state_t::eCropChanged) {
3705 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3706 }
3707 if (what & layer_state_t::eBufferChanged) {
3708 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eAcquireFenceChanged) {
3711 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3712 }
3713 if (what & layer_state_t::eDataspaceChanged) {
3714 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eHdrMetadataChanged) {
3717 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3718 }
3719 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3720 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eApiChanged) {
3723 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3724 }
3725 if (what & layer_state_t::eSidebandStreamChanged) {
3726 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3727 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003728 return flags;
3729}
3730
chaviwca27f252018-02-06 16:46:39 -08003731void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3732 const layer_state_t& state = composerState.state;
3733 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3734
3735 sp<Layer> layer(client->getLayerUser(state.surface));
3736 if (layer == nullptr) {
3737 return;
3738 }
3739
3740 if (layer->isPendingRemoval()) {
3741 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3742 return;
3743 }
3744
3745 if (state.what & layer_state_t::eDestroySurface) {
3746 removeLayerLocked(mStateLock, layer);
3747 }
3748}
3749
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003751 const String8& name,
3752 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003753 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003754 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003755 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003757 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003758 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003759 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003761 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003762
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003763 status_t result = NO_ERROR;
3764
3765 sp<Layer> layer;
3766
Cody Northropbc755282017-03-31 12:00:08 -06003767 String8 uniqueName = getUniqueLayerName(name);
3768
Mathias Agopian3165cc22012-08-08 19:42:09 -07003769 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003770 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003771 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3772 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003775 case ISurfaceComposerClient::eFXSurfaceBufferState:
3776 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3777 break;
chaviw13fdc492017-06-27 12:40:18 -07003778 case ISurfaceComposerClient::eFXSurfaceColor:
3779 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003780 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003781 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003782 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003783 case ISurfaceComposerClient::eFXSurfaceContainer:
3784 result = createContainerLayer(client,
3785 uniqueName, w, h, flags,
3786 handle, &layer);
3787 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003788 default:
3789 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 break;
3791 }
3792
Dan Stoza7d89d062015-04-30 13:29:25 -07003793 if (result != NO_ERROR) {
3794 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003795 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003796
Chia-I Wuab0c3192017-08-01 11:29:00 -07003797 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3798 // TODO b/64227542
3799 if (windowType == 441731) {
3800 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3801 layer->setPrimaryDisplayOnly();
3802 }
3803
Albert Chaulk479c60c2017-01-27 14:21:34 -05003804 layer->setInfo(windowType, ownerUid);
3805
Robert Carr1f0a16a2016-10-24 16:27:39 -07003806 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003807 if (result != NO_ERROR) {
3808 return result;
3809 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003810 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003811
3812 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814}
3815
Cody Northropbc755282017-03-31 12:00:08 -06003816String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3817{
3818 bool matchFound = true;
3819 uint32_t dupeCounter = 0;
3820
3821 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3822 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3823
Dan Stoza436ccf32018-06-21 12:10:12 -07003824 // Grab the state lock since we're accessing mCurrentState
3825 Mutex::Autolock lock(mStateLock);
3826
Cody Northropbc755282017-03-31 12:00:08 -06003827 // Loop over layers until we're sure there is no matching name
3828 while (matchFound) {
3829 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003830 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003831 if (layer->getName() == uniqueName) {
3832 matchFound = true;
3833 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3834 }
3835 });
3836 }
3837
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003838 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3839 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003840
3841 return uniqueName;
3842}
3843
Marissa Wallfd668622018-05-10 10:21:13 -07003844status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3845 uint32_t w, uint32_t h, uint32_t flags,
3846 PixelFormat& format, sp<IBinder>* handle,
3847 sp<IGraphicBufferProducer>* gbp,
3848 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003850 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 case PIXEL_FORMAT_TRANSPARENT:
3852 case PIXEL_FORMAT_TRANSLUCENT:
3853 format = PIXEL_FORMAT_RGBA_8888;
3854 break;
3855 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003856 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 break;
3858 }
3859
Marissa Wallfd668622018-05-10 10:21:13 -07003860 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3861 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003862 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003863 *handle = layer->getHandle();
3864 *gbp = layer->getProducer();
3865 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003867
Marissa Wallfd668622018-05-10 10:21:13 -07003868 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003869 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003870}
3871
Marissa Wall61c58622018-07-18 10:12:20 -07003872status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3873 uint32_t w, uint32_t h, uint32_t flags,
3874 sp<IBinder>* handle, sp<Layer>* outLayer) {
3875 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3876 *handle = layer->getHandle();
3877 *outLayer = layer;
3878
3879 return NO_ERROR;
3880}
3881
chaviw13fdc492017-06-27 12:40:18 -07003882status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003884 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885{
chaviw13fdc492017-06-27 12:40:18 -07003886 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003889}
3890
Robert Carr6b3f6c52018-08-13 13:05:17 -07003891status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3892 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3893 sp<IBinder>* handle, sp<Layer>* outLayer)
3894{
3895 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3896 *handle = (*outLayer)->getHandle();
3897 return NO_ERROR;
3898}
3899
3900
Mathias Agopianac9fa422013-02-11 16:40:36 -08003901status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902{
Robert Carr9524cb32017-02-13 11:32:32 -08003903 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003904 status_t err = NO_ERROR;
3905 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003906 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003907 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003908 err = removeLayer(l);
3909 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3910 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003911 }
3912 return err;
3913}
3914
Mathias Agopian13127d82013-03-05 17:47:11 -08003915status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003916{
Mathias Agopian67106042013-03-14 19:18:13 -07003917 // called by ~LayerCleaner() when all references to the IBinder (handle)
3918 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003919 sp<Layer> l = layer.promote();
3920 if (l == nullptr) {
3921 // The layer has already been removed, carry on
3922 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003923 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003924 // If we have a parent, then we can continue to live as long as it does.
3925 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926}
3927
Mathias Agopianb60314a2012-04-10 22:09:54 -07003928// ---------------------------------------------------------------------------
3929
Andy McFadden13a082e2012-08-24 10:16:42 -07003930void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003931 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3932 if (!displayToken) return;
3933
Jesse Hall01e29052013-02-19 16:13:35 -08003934 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003935 Vector<ComposerState> state;
3936 Vector<DisplayState> displays;
3937 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003938 d.what = DisplayState::eDisplayProjectionChanged |
3939 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003940 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003941 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003942 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003943 d.frame.makeInvalid();
3944 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003945 d.width = 0;
3946 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003947 displays.add(d);
3948 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003949
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003950 const auto display = getDisplayDevice(displayToken);
3951 if (!display) return;
3952
3953 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3954
3955 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003956 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003957 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003958
Brian Andersond0010582017-03-07 13:20:31 -08003959 // Use phase of 0 since phase is not known.
3960 // Use latency of 0, which will snap to the ideal latency.
3961 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003962}
3963
3964void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003965 // Async since we may be called from the main thread.
3966 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003967}
3968
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003969void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3970 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003971 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003972 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003973
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003975 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003976 return;
3977 }
3978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003980 ALOGW("Trying to set power mode for virtual display");
3981 return;
3982 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003984 display->setPowerMode(mode);
3985
Lloyd Pique4dccc412018-01-22 17:21:36 -08003986 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003987 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003988 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003989 if (idx < 0) {
3990 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3991 return;
3992 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003993 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003994 }
3995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003997 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003998 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003999 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004001 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004002 if (mUseScheduler) {
4003 mScheduler->onScreenAcquired(mAppConnectionHandle);
4004 } else {
4005 mEventThread->onScreenAcquired();
4006 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004007 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004010 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004011 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004012 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004013
4014 struct sched_param param = {0};
4015 param.sched_priority = 1;
4016 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4017 ALOGW("Couldn't set SCHED_FIFO on display on");
4018 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004019 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004020 // Turn off the display
4021 struct sched_param param = {0};
4022 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4023 ALOGW("Couldn't set SCHED_OTHER on display off");
4024 }
4025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004026 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004027 disableHardwareVsync(true); // also cancels any in-progress resync
4028
Mathias Agopiancde87a32012-09-13 14:09:01 -07004029 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004030 if (mUseScheduler) {
4031 mScheduler->onScreenReleased(mAppConnectionHandle);
4032 } else {
4033 mEventThread->onScreenReleased();
4034 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004035 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004036
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 getHwComposer().setPowerMode(type, mode);
4038 mVisibleRegionsDirty = true;
4039 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004040 } else if (mode == HWC_POWER_MODE_DOZE ||
4041 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004042 // Update display while dozing
4043 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004044 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004045 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004046 if (mUseScheduler) {
4047 mScheduler->onScreenAcquired(mAppConnectionHandle);
4048 } else {
4049 mEventThread->onScreenAcquired();
4050 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004051 resyncToHardwareVsync(true);
4052 }
4053 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4054 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004055 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004056 disableHardwareVsync(true); // also cancels any in-progress resync
4057 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004058 if (mUseScheduler) {
4059 mScheduler->onScreenReleased(mAppConnectionHandle);
4060 } else {
4061 mEventThread->onScreenReleased();
4062 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004063 }
4064 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004065 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004066 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004067 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004068 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004069
4070 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004071}
4072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004073void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004074 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075 const auto display = getDisplayDevice(displayToken);
4076 if (!display) {
4077 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4078 displayToken.get());
4079 } else if (display->isVirtual()) {
4080 ALOGW("Attempt to set power mode %d for virtual display", mode);
4081 } else {
4082 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004083 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004084 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004085}
4086
4087// ---------------------------------------------------------------------------
4088
Lloyd Pique755e3192018-01-31 16:46:15 -08004089status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4090 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004092
Mathias Agopianbd115332013-04-18 16:41:04 -07004093 IPCThreadState* ipc = IPCThreadState::self();
4094 const int pid = ipc->getCallingPid();
4095 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004096
Mathias Agopianbd115332013-04-18 16:41:04 -07004097 if ((uid != AID_SHELL) &&
4098 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004099 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004100 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004101 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004102 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004103 // (this would indicate SF is stuck, but we want to be able to
4104 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004105 status_t err = mStateLock.timedLock(s2ns(1));
4106 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004107 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004108 result.appendFormat(
4109 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4110 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004111 }
4112
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004113 bool dumpAll = true;
4114 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004115 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004116
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004117 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004118 if ((index < numArgs) &&
4119 (args[index] == String16("--list"))) {
4120 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004121 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004122 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004123 }
4124
4125 if ((index < numArgs) &&
4126 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004127 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004128 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004129 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004130 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004131
4132 if ((index < numArgs) &&
4133 (args[index] == String16("--latency-clear"))) {
4134 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004136 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004138
4139 if ((index < numArgs) &&
4140 (args[index] == String16("--dispsync"))) {
4141 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004142 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004143 dumpAll = false;
4144 }
Dan Stozab90cf072015-03-05 11:05:59 -08004145
4146 if ((index < numArgs) &&
4147 (args[index] == String16("--static-screen"))) {
4148 index++;
4149 dumpStaticScreenStats(result);
4150 dumpAll = false;
4151 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004152
4153 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004154 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004155 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004156 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004157 dumpAll = false;
4158 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004159
4160 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4161 index++;
4162 dumpWideColorInfo(result);
4163 dumpAll = false;
4164 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004165
4166 if ((index < numArgs) &&
4167 (args[index] == String16("--enable-layer-stats"))) {
4168 index++;
4169 mLayerStats.enable();
4170 dumpAll = false;
4171 }
4172
4173 if ((index < numArgs) &&
4174 (args[index] == String16("--disable-layer-stats"))) {
4175 index++;
4176 mLayerStats.disable();
4177 dumpAll = false;
4178 }
4179
4180 if ((index < numArgs) &&
4181 (args[index] == String16("--clear-layer-stats"))) {
4182 index++;
4183 mLayerStats.clear();
4184 dumpAll = false;
4185 }
4186
4187 if ((index < numArgs) &&
4188 (args[index] == String16("--dump-layer-stats"))) {
4189 index++;
4190 mLayerStats.dump(result);
4191 dumpAll = false;
4192 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004193
4194 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004195 (args[index] == String16("--frame-composition"))) {
4196 index++;
4197 dumpFrameCompositionInfo(result);
4198 dumpAll = false;
4199 }
4200
4201 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004202 (args[index] == String16("--display-identification"))) {
4203 index++;
4204 dumpDisplayIdentificationData(result);
4205 dumpAll = false;
4206 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004207
4208 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4209 index++;
4210 mTimeStats.parseArgs(asProto, args, index, result);
4211 dumpAll = false;
4212 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004213 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004214
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004216 if (asProto) {
4217 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4218 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4219 } else {
4220 dumpAllLocked(args, index, result);
4221 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004222 }
4223
Mathias Agopian9795c422009-08-26 16:36:26 -07004224 if (locked) {
4225 mStateLock.unlock();
4226 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227 }
4228 write(fd, result.string(), result.size());
4229 return NO_ERROR;
4230}
4231
Dan Stozac7014012014-02-14 15:03:43 -08004232void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4233 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004234{
Robert Carr2047fae2016-11-28 14:09:09 -08004235 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004236 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004237 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004238}
4239
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004240void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004241 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242{
4243 String8 name;
4244 if (index < args.size()) {
4245 name = String8(args[index]);
4246 index++;
4247 }
4248
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004249 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4250 getHwComposer().isConnected(displayId)) {
4251 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4252 const nsecs_t period = activeConfig->getVsyncPeriod();
4253 result.appendFormat("%" PRId64 "\n", period);
4254 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004255
4256 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004257 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004258 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004259 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004260 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004261 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004262 }
Robert Carr2047fae2016-11-28 14:09:09 -08004263 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264 }
4265}
4266
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004267void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004268 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004269{
4270 String8 name;
4271 if (index < args.size()) {
4272 name = String8(args[index]);
4273 index++;
4274 }
4275
Robert Carr2047fae2016-11-28 14:09:09 -08004276 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004277 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004278 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004279 }
Robert Carr2047fae2016-11-28 14:09:09 -08004280 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004281
Svetoslavd85084b2014-03-20 10:28:31 -07004282 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004283}
4284
Jamie Gennis6547ff42013-07-16 20:12:42 -07004285// This should only be called from the main thread. Otherwise it would need
4286// the lock and should use mCurrentState rather than mDrawingState.
4287void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004288 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004289 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004290 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004291
4292 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4293}
4294
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004295void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004296{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004297 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004298
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004299 if (isLayerTripleBufferingDisabled())
4300 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004301
4302 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004303 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004304 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004305 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004306 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4307 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004308 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004309}
4310
Dan Stozab90cf072015-03-05 11:05:59 -08004311void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4312{
4313 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004314 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4315 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004316 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004317 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004318 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4319 b + 1, bucketTimeSec, percent);
4320 }
David Sodman4a36e932017-11-07 14:29:47 -08004321 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004322 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004323 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004324 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004325 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004326}
4327
Dan Stozae77c7662016-05-13 11:37:28 -07004328void SurfaceFlinger::recordBufferingStats(const char* layerName,
4329 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004330 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4331 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004332 for (const auto& segment : history) {
4333 if (!segment.usedThirdBuffer) {
4334 stats.twoBufferTime += segment.totalTime;
4335 }
4336 if (segment.occupancyAverage < 1.0f) {
4337 stats.doubleBufferedTime += segment.totalTime;
4338 } else if (segment.occupancyAverage < 2.0f) {
4339 stats.tripleBufferedTime += segment.totalTime;
4340 }
4341 ++stats.numSegments;
4342 stats.totalTime += segment.totalTime;
4343 }
4344}
4345
Brian Andersond6927fb2016-07-23 23:37:30 -07004346void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4347 result.appendFormat("Layer frame timestamps:\n");
4348
4349 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4350 const size_t count = currentLayers.size();
4351 for (size_t i=0 ; i<count ; i++) {
4352 currentLayers[i]->dumpFrameEvents(result);
4353 }
4354}
4355
Dan Stozae77c7662016-05-13 11:37:28 -07004356void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4357 result.append("Buffering stats:\n");
4358 result.append(" [Layer name] <Active time> <Two buffer> "
4359 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004360 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004361 typedef std::tuple<std::string, float, float, float> BufferTuple;
4362 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004363 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004364 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004365 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004366 if (stats.numSegments == 0) {
4367 continue;
4368 }
4369 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4370 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4371 stats.totalTime;
4372 float doubleBufferRatio = static_cast<float>(
4373 stats.doubleBufferedTime) / stats.totalTime;
4374 float tripleBufferRatio = static_cast<float>(
4375 stats.tripleBufferedTime) / stats.totalTime;
4376 sorted.insert({activeTime, {name, twoBufferRatio,
4377 doubleBufferRatio, tripleBufferRatio}});
4378 }
4379 for (const auto& sortedPair : sorted) {
4380 float activeTime = sortedPair.first;
4381 const BufferTuple& values = sortedPair.second;
4382 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4383 std::get<0>(values).c_str(), activeTime,
4384 std::get<1>(values), std::get<2>(values),
4385 std::get<3>(values));
4386 }
4387 result.append("\n");
4388}
4389
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004390void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004391 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004392 const int32_t displayId = display->getId();
4393 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4394 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004395 continue;
4396 }
4397
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004399 uint8_t port;
4400 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004401 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004402 result.append("no identification data\n");
4403 continue;
4404 }
4405
4406 if (!isEdid(data)) {
4407 result.append("unknown identification data: ");
4408 for (uint8_t byte : data) {
4409 result.appendFormat("%x ", byte);
4410 }
4411 result.append("\n");
4412 continue;
4413 }
4414
4415 const auto edid = parseEdid(data);
4416 if (!edid) {
4417 result.append("invalid EDID: ");
4418 for (uint8_t byte : data) {
4419 result.appendFormat("%x ", byte);
4420 }
4421 result.append("\n");
4422 continue;
4423 }
4424
4425 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4426 result.append(edid->displayName.data(), edid->displayName.length());
4427 result.append("\"\n");
4428 }
4429 result.append("\n");
4430}
4431
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004432void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004433 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4434 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004435 result.appendFormat("DisplayColorSetting: %s\n",
4436 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004437
4438 // TODO: print out if wide-color mode is active or not
4439
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004440 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004441 const int32_t displayId = display->getId();
4442 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004443 continue;
4444 }
4445
Dominik Laskowski7e045462018-05-30 13:02:02 -07004446 result.appendFormat("Display %d color modes:\n", displayId);
4447 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448 for (auto&& mode : modes) {
4449 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4450 }
4451
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004452 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004453 result.appendFormat(" Current color mode: %s (%d)\n",
4454 decodeColorMode(currentMode).c_str(), currentMode);
4455 }
4456 result.append("\n");
4457}
4458
David Sodman7e4ae112018-02-09 15:02:28 -08004459void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4460 std::string stringResult;
4461
4462 for (const auto& [token, display] : mDisplays) {
4463 const auto displayId = display->getId();
4464 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4465 continue;
4466 }
4467
4468 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4469 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4470 break;
4471 }
4472 const auto& compositionInfoList = compositionInfoIt->second;
4473 stringResult += base::StringPrintf("Display: %d\n", displayId);
4474 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4475 for (const auto& compositionInfo : compositionInfoList) {
4476 compositionInfo.dump(stringResult, nullptr);
4477 stringResult += base::StringPrintf("\n");
4478 }
4479 }
4480
4481 result.append(stringResult.c_str());
4482}
4483
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004484LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004485 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004486 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4487 const State& state = useDrawing ? mDrawingState : mCurrentState;
4488 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004489 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004490 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004491 });
4492
4493 return layersProto;
4494}
4495
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004496LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004497 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004498
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004499 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004500 resolution->set_w(display.getWidth());
4501 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004502
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004503 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4504 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4505 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004506
Dominik Laskowski7e045462018-05-30 13:02:02 -07004507 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004508 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004509 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004510 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004511 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004512 }
4513 });
4514
4515 return layersProto;
4516}
4517
Mathias Agopian74d211a2013-04-22 16:55:35 +02004518void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4519 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004520{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004521 bool colorize = false;
4522 if (index < args.size()
4523 && (args[index] == String16("--color"))) {
4524 colorize = true;
4525 index++;
4526 }
4527
4528 Colorizer colorizer(colorize);
4529
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004530 // figure out if we're stuck somewhere
4531 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4534
4535 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004536 * Dump library configuration.
4537 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538
4539 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004540 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004542 appendSfConfigString(result);
4543 appendUiConfigString(result);
4544 appendGuiConfigString(result);
4545 result.append("\n");
4546
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004547 result.append("\nDisplay identification data:\n");
4548 dumpDisplayIdentificationData(result);
4549
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004550 result.append("\nWide-Color information:\n");
4551 dumpWideColorInfo(result);
4552
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004553 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004554 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004556 result.append(SyncFeatures::getInstance().toString());
4557 result.append("\n");
4558
Andy McFadden41d67d72014-04-25 16:58:34 -07004559 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004560 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004561 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004562
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004563 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4564 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004565 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4566 getHwComposer().isConnected(displayId)) {
4567 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004568 result.appendFormat("Display %d: "
4569 "app phase %" PRId64 " ns, "
4570 "sf phase %" PRId64 " ns, "
4571 "early app phase %" PRId64 " ns, "
4572 "early sf phase %" PRId64 " ns, "
4573 "early app gl phase %" PRId64 " ns, "
4574 "early sf gl phase %" PRId64 " ns, "
4575 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4576 displayId,
4577 vsyncPhaseOffsetNs,
4578 sfVsyncPhaseOffsetNs,
4579 appEarlyOffset,
4580 sfEarlyOffset,
4581 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004582 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004583 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004584 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004585 result.append("\n");
4586
Dan Stozab90cf072015-03-05 11:05:59 -08004587 // Dump static screen stats
4588 result.append("\n");
4589 dumpStaticScreenStats(result);
4590 result.append("\n");
4591
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004592 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4593
Dan Stozae77c7662016-05-13 11:37:28 -07004594 dumpBufferingStats(result);
4595
Andy McFadden4803b742012-09-24 19:07:20 -07004596 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597 * Dump the visible layer list
4598 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004599 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004600 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004601 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4602 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004603 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004604
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004605 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004606 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004607 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004608 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609
David Sodman7e4ae112018-02-09 15:02:28 -08004610 result.append("\nFrame-Composition information:\n");
4611 dumpFrameCompositionInfo(result);
4612 result.append("\n");
4613
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004614 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004615 * Dump Display state
4616 */
4617
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004619 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004621 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004622 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004623 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004624 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004625
4626 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627 * Dump SurfaceFlinger global state
4628 */
4629
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004630 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004631 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004632 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633
Mathias Agopian888c8222012-08-04 21:10:38 -07004634 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004635 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004636
David Sodmanbc815282017-11-05 18:57:52 -08004637 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004639 if (display) {
4640 display->undefinedRegion.dump(result, "undefinedRegion");
4641 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4642 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004643 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004644 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004645 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004646 mTransactionFlags, !mGpuToCpuSupported);
4647
4648 if (display) {
4649 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4650 result.appendFormat(" refresh-rate : %f fps\n"
4651 " x-dpi : %f\n"
4652 " y-dpi : %f\n",
4653 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4654 activeConfig->getDpiY());
4655 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656
Mathias Agopian74d211a2013-04-22 16:55:35 +02004657 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004659
Ana Krulec98b5b242018-08-10 15:03:23 -07004660 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004661 /*
4662 * VSYNC state
4663 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004664 if (mUseScheduler) {
4665 mScheduler->dump(mAppConnectionHandle, result);
4666 } else {
4667 mEventThread->dump(result);
4668 }
Dan Stozae22aec72016-08-01 13:20:59 -07004669 result.append("\n");
4670
4671 /*
4672 * HWC layer minidump
4673 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004674 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004675 const int32_t displayId = display->getId();
4676 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004677 continue;
4678 }
4679
Dominik Laskowski7e045462018-05-30 13:02:02 -07004680 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004681 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004682 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004683 result.append("\n");
4684 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685
4686 /*
4687 * Dump HWComposer state
4688 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004690 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004691 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004692 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004693 result.appendFormat(" h/w composer %s\n",
4694 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004695 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696
4697 /*
4698 * Dump gralloc state
4699 */
4700 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4701 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004702
4703 /*
4704 * Dump VrFlinger state if in use.
4705 */
4706 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4707 result.append("VrFlinger state:\n");
4708 result.append(mVrFlinger->Dump().c_str());
4709 result.append("\n");
4710 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711}
4712
Dominik Laskowski7e045462018-05-30 13:02:02 -07004713const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004714 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004715 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004716 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004717 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004718 }
4719 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004720
4721 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4722 static const Vector<sp<Layer>> empty;
4723 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004724}
4725
Keun young Park63f165f2012-08-31 10:53:36 -07004726bool SurfaceFlinger::startDdmConnection()
4727{
4728 void* libddmconnection_dso =
4729 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4730 if (!libddmconnection_dso) {
4731 return false;
4732 }
4733 void (*DdmConnection_start)(const char* name);
4734 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004735 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004736 if (!DdmConnection_start) {
4737 dlclose(libddmconnection_dso);
4738 return false;
4739 }
4740 (*DdmConnection_start)(getServiceName());
4741 return true;
4742}
4743
Chia-I Wu28f320b2018-05-03 11:02:56 -07004744void SurfaceFlinger::updateColorMatrixLocked() {
4745 mat4 colorMatrix;
4746 if (mGlobalSaturationFactor != 1.0f) {
4747 // Rec.709 luma coefficients
4748 float3 luminance{0.213f, 0.715f, 0.072f};
4749 luminance *= 1.0f - mGlobalSaturationFactor;
4750 mat4 saturationMatrix = mat4(
4751 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4752 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4753 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4754 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4755 );
4756 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4757 } else {
4758 colorMatrix = mClientColorMatrix * mDaltonizer();
4759 }
4760
4761 if (mCurrentState.colorMatrix != colorMatrix) {
4762 mCurrentState.colorMatrix = colorMatrix;
4763 mCurrentState.colorMatrixChanged = true;
4764 setTransactionFlags(eTransactionNeeded);
4765 }
4766}
4767
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004768status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004769#pragma clang diagnostic push
4770#pragma clang diagnostic error "-Wswitch-enum"
4771 switch (static_cast<ISurfaceComposerTag>(code)) {
4772 // These methods should at minimum make sure that the client requested
4773 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004774 case BOOT_FINISHED:
4775 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004776 case CREATE_CONNECTION:
4777 case CREATE_DISPLAY:
4778 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004779 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 case GET_ACTIVE_COLOR_MODE:
4781 case GET_ANIMATION_FRAME_STATS:
4782 case GET_HDR_CAPABILITIES:
4783 case SET_ACTIVE_CONFIG:
4784 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004785 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004787 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4788 IPCThreadState* ipc = IPCThreadState::self();
4789 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4790 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004791 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004792 }
Robert Carr1db73f62016-12-21 12:58:51 -08004793 return OK;
4794 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004796 IPCThreadState* ipc = IPCThreadState::self();
4797 const int pid = ipc->getCallingPid();
4798 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4800 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004801 return PERMISSION_DENIED;
4802 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004803 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 // Used by apps to hook Choreographer to SurfaceFlinger.
4806 case CREATE_DISPLAY_EVENT_CONNECTION:
4807 // The following calls are currently used by clients that do not
4808 // request necessary permissions. However, they do not expose any secret
4809 // information, so it is OK to pass them.
4810 case AUTHENTICATE_SURFACE:
4811 case GET_ACTIVE_CONFIG:
4812 case GET_BUILT_IN_DISPLAY:
4813 case GET_DISPLAY_COLOR_MODES:
4814 case GET_DISPLAY_CONFIGS:
4815 case GET_DISPLAY_STATS:
4816 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4817 // Calling setTransactionState is safe, because you need to have been
4818 // granted a reference to Client* and Handle* to do anything with it.
4819 case SET_TRANSACTION_STATE:
4820 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4821 case CREATE_SCOPED_CONNECTION: {
4822 return OK;
4823 }
4824 case CAPTURE_LAYERS:
4825 case CAPTURE_SCREEN: {
4826 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004827 IPCThreadState* ipc = IPCThreadState::self();
4828 const int pid = ipc->getCallingPid();
4829 const int uid = ipc->getCallingUid();
4830 if ((uid != AID_GRAPHICS) &&
4831 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4832 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4833 return PERMISSION_DENIED;
4834 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 return OK;
4836 }
4837 // The following codes are deprecated and should never be allowed to access SF.
4838 case CONNECT_DISPLAY_UNUSED:
4839 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4840 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4841 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004843 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844
4845 // These codes are used for the IBinder protocol to either interrogate the recipient
4846 // side of the transaction for its canonical interface descriptor or to dump its state.
4847 // We let them pass by default.
4848 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4849 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4850 code == IBinder::SYSPROPS_TRANSACTION) {
4851 return OK;
4852 }
4853 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4854 // in onTransact verifies that the user is root, and has access to use SF.
4855 if (code >= 1000 && code <= 1029) {
4856 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4857 return OK;
4858 }
4859 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4860 return PERMISSION_DENIED;
4861#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004862}
4863
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4865 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004866 status_t credentialCheck = CheckTransactCodeCredentials(code);
4867 if (credentialCheck != OK) {
4868 return credentialCheck;
4869 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004870
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004871 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4872 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004873 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004874 IPCThreadState* ipc = IPCThreadState::self();
4875 const int uid = ipc->getCallingUid();
4876 if (CC_UNLIKELY(uid != AID_SYSTEM
4877 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004878 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004879 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004880 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 return PERMISSION_DENIED;
4882 }
4883 int n;
4884 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004885 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004886 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return NO_ERROR;
4888 case 1002: // SHOW_UPDATES
4889 n = data.readInt32();
4890 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004891 invalidateHwcGeometry();
4892 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004894 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004895 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004897 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004898 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004899 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004900 setTransactionFlags(
4901 eTransactionNeeded|
4902 eDisplayTransactionNeeded|
4903 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004904 return NO_ERROR;
4905 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004906 case 1006:{ // send empty update
4907 signalRefresh();
4908 return NO_ERROR;
4909 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004910 case 1008: // toggle use of hw composer
4911 n = data.readInt32();
4912 mDebugDisableHWC = n ? 1 : 0;
4913 invalidateHwcGeometry();
4914 repaintEverything();
4915 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004916 case 1009: // toggle use of transform hint
4917 n = data.readInt32();
4918 mDebugDisableTransformHint = n ? 1 : 0;
4919 invalidateHwcGeometry();
4920 repaintEverything();
4921 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004923 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 reply->writeInt32(0);
4925 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004926 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004927 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 return NO_ERROR;
4929 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004930 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004931 if (!display) {
4932 return NAME_NOT_FOUND;
4933 }
4934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004935 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004936 return NO_ERROR;
4937 }
4938 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004939 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004940 // daltonize
4941 n = data.readInt32();
4942 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004943 case 1:
4944 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4945 break;
4946 case 2:
4947 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4948 break;
4949 case 3:
4950 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4951 break;
4952 default:
4953 mDaltonizer.setType(ColorBlindnessType::None);
4954 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004955 }
4956 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004958 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004959 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004960 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004961
4962 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004965 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004966 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 // apply a color matrix
4968 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004970 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004971 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004973 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004974 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004976 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004977 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004978 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004979
4980 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4981 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004982 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004983 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4984 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4985 }
4986
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 return NO_ERROR;
4989 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004990 // This is an experimental interface
4991 // Needs to be shifted to proper binder interface when we productize
4992 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004993 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004994 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004995 return NO_ERROR;
4996 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004997 case 1017: {
4998 n = data.readInt32();
4999 mForceFullDamage = static_cast<bool>(n);
5000 return NO_ERROR;
5001 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005002 case 1018: { // Modify Choreographer's phase offset
5003 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005004 if (mUseScheduler) {
5005 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5006 } else {
5007 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5008 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005009 return NO_ERROR;
5010 }
5011 case 1019: { // Modify SurfaceFlinger's phase offset
5012 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005013 if (mUseScheduler) {
5014 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5015 } else {
5016 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5017 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005018 return NO_ERROR;
5019 }
Irvel468051e2016-06-13 16:44:44 -07005020 case 1020: { // Layer updates interceptor
5021 n = data.readInt32();
5022 if (n) {
5023 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005024 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005025 }
5026 else{
5027 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005028 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005029 }
5030 return NO_ERROR;
5031 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005032 case 1021: { // Disable HWC virtual displays
5033 n = data.readInt32();
5034 mUseHwcVirtualDisplays = !n;
5035 return NO_ERROR;
5036 }
Romain Guy0147a172017-06-01 13:53:56 -07005037 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005039 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005040
Chia-I Wu28f320b2018-05-03 11:02:56 -07005041 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005042 return NO_ERROR;
5043 }
Romain Guy54f154a2017-10-24 21:40:32 +01005044 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005045 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005046 invalidateHwcGeometry();
5047 repaintEverything();
5048 return NO_ERROR;
5049 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005050 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5051 // deprecate 1024 if they can.
5052 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005053 reply->writeBool(hasWideColorDisplay);
5054 return NO_ERROR;
5055 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005056 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005057 n = data.readInt32();
5058 if (n) {
5059 ALOGV("LayerTracing enabled");
5060 mTracing.enable();
5061 doTracing("tracing.enable");
5062 reply->writeInt32(NO_ERROR);
5063 } else {
5064 ALOGV("LayerTracing disabled");
5065 status_t err = mTracing.disable();
5066 reply->writeInt32(err);
5067 }
5068 return NO_ERROR;
5069 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005070 case 1026: { // Get layer tracing status
5071 reply->writeBool(mTracing.isEnabled());
5072 return NO_ERROR;
5073 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005074 // Is a DisplayColorSetting supported?
5075 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005076 const auto display = getDefaultDisplayDevice();
5077 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005078 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005079 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005080
5081 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5082 switch (setting) {
5083 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005084 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005085 break;
5086 case DisplayColorSetting::UNMANAGED:
5087 reply->writeBool(true);
5088 break;
5089 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005090 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005091 break;
5092 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005093 reply->writeBool(
5094 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005095 break;
5096 }
5097 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005098 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005099 // Is VrFlinger active?
5100 case 1028: {
5101 Mutex::Autolock _l(mStateLock);
5102 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5103 return NO_ERROR;
5104 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005105 case 1029: {
5106 // Code 1029 is an experimental feature that allows applications to
5107 // simulate a high frequency panel by setting a multiplier and divisor
5108 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005109 // 0, then the code simply return the current multiplier and divisor.
5110 HWC2::Device::FrequencyScaler frequencyScaler;
5111 frequencyScaler.multiplier = data.readInt32();
5112 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005113
David Sodman44b5de02018-08-21 16:28:53 -07005114 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5115 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5116 reply->writeInt32(frequencyScaler.multiplier);
5117 reply->writeInt32(frequencyScaler.divisor);
5118 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005119 }
5120
David Sodman44b5de02018-08-21 16:28:53 -07005121 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005122 enableHardwareVsync();
5123 } else {
5124 disableHardwareVsync(true);
5125 }
David Sodman44b5de02018-08-21 16:28:53 -07005126 mPrimaryDispSync->scalePeriod(frequencyScaler);
5127 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005128
David Sodman44b5de02018-08-21 16:28:53 -07005129 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5130 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5131
5132 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5133 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5134
5135 onHotplugReceived(getBE().mComposerSequenceId,
5136 hwcDisplayId, HWC2::Connection::Disconnected);
5137 onHotplugReceived(getBE().mComposerSequenceId,
5138 hwcDisplayId, HWC2::Connection::Connected);
5139 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5140 reply->writeInt32(frequencyScaler.multiplier);
5141 reply->writeInt32(frequencyScaler.divisor);
5142
David Sodman6d46c1e2018-07-13 12:59:48 -07005143 return NO_ERROR;
5144 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005145 // Is device color managed?
5146 case 1030: {
5147 reply->writeBool(useColorManagement);
5148 return NO_ERROR;
5149 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005150 }
5151 }
5152 return err;
5153}
5154
Steven Thomas6d8110b2017-08-31 18:24:21 -07005155void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005156 android_atomic_or(1, &mRepaintEverything);
5157 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005158}
5159
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005160// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5161class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005162public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005163 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5164 ~WindowDisconnector() {
5165 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005166 }
5167
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005168private:
5169 ANativeWindow* mWindow;
5170 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005171};
5172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005173status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5174 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5175 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5176 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005177 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005178 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005179
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005180 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005181
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005182 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5183
Chia-I Wu20261cb2018-08-23 12:55:44 -07005184 sp<DisplayDevice> display;
5185 {
5186 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005187
Chia-I Wu20261cb2018-08-23 12:55:44 -07005188 display = getDisplayDeviceLocked(displayToken);
5189 if (!display) return BAD_VALUE;
5190
Chia-I Wu8730ba82018-08-29 09:25:59 -07005191 // ignore sourceCrop (i.e., use the projected logical display
5192 // viewport) until the framework is fixed
5193 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005194
5195 // set the requested width/height to the logical display viewport size
5196 // by default
5197 if (reqWidth == 0 || reqHeight == 0) {
5198 reqWidth = uint32_t(display->getViewport().width());
5199 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005200 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005201 }
5202
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005203 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005204
5205 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005207 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005208}
5209
5210status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005211 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005212 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005213 ATRACE_CALL();
5214
5215 class LayerRenderArea : public RenderArea {
5216 public:
Robert Carr578038f2018-03-09 12:25:24 -08005217 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5218 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005219 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005220 mLayer(layer),
5221 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005222 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005223 mFlinger(flinger),
5224 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005225 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005226 Rect getBounds() const override {
5227 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005228 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005229 }
Marissa Wall61c58622018-07-18 10:12:20 -07005230 int getHeight() const override {
5231 return mLayer->getActiveHeight(mLayer->getDrawingState());
5232 }
5233 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005234 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005235 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005236 Rect getSourceCrop() const override {
5237 if (mCrop.isEmpty()) {
5238 return getBounds();
5239 } else {
5240 return mCrop;
5241 }
5242 }
Robert Carr578038f2018-03-09 12:25:24 -08005243 class ReparentForDrawing {
5244 public:
5245 const sp<Layer>& oldParent;
5246 const sp<Layer>& newParent;
5247
5248 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5249 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005250 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005251 }
Robert Carr15eae092018-03-23 13:43:53 -07005252 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005253 };
5254
5255 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005256 const Rect sourceCrop = getSourceCrop();
5257 // no need to check rotation because there is none
5258 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5259 sourceCrop.height() != getReqHeight();
5260
Robert Carr578038f2018-03-09 12:25:24 -08005261 if (!mChildrenOnly) {
5262 mTransform = mLayer->getTransform().inverse();
5263 drawLayers();
5264 } else {
5265 Rect bounds = getBounds();
5266 screenshotParentLayer =
5267 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5268 bounds.getWidth(), bounds.getHeight(), 0);
5269
5270 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5271 drawLayers();
5272 }
5273 }
chaviwa76b2712017-09-20 12:02:26 -07005274
chaviwa76b2712017-09-20 12:02:26 -07005275 private:
chaviw7206d492017-11-10 16:16:12 -08005276 const sp<Layer> mLayer;
5277 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005278
5279 // In the "childrenOnly" case we reparent the children to a screenshot
5280 // layer which has no properties set and which does not draw.
5281 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005282 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005283 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005284
5285 SurfaceFlinger* mFlinger;
5286 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005287 };
5288
5289 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5290 auto parent = layerHandle->owner.promote();
5291
chaviw7206d492017-11-10 16:16:12 -08005292 if (parent == nullptr || parent->isPendingRemoval()) {
5293 ALOGE("captureLayers called with a removed parent");
5294 return NAME_NOT_FOUND;
5295 }
5296
Robert Carr578038f2018-03-09 12:25:24 -08005297 const int uid = IPCThreadState::self()->getCallingUid();
5298 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5299 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5300 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5301 return PERMISSION_DENIED;
5302 }
5303
chaviw7206d492017-11-10 16:16:12 -08005304 Rect crop(sourceCrop);
5305 if (sourceCrop.width() <= 0) {
5306 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005307 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005308 }
5309
5310 if (sourceCrop.height() <= 0) {
5311 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005312 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005313 }
5314
5315 int32_t reqWidth = crop.width() * frameScale;
5316 int32_t reqHeight = crop.height() * frameScale;
5317
Chia-I Wu20261cb2018-08-23 12:55:44 -07005318 // really small crop or frameScale
5319 if (reqWidth <= 0) {
5320 reqWidth = 1;
5321 }
5322 if (reqHeight <= 0) {
5323 reqHeight = 1;
5324 }
5325
Robert Carr578038f2018-03-09 12:25:24 -08005326 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005327
Robert Carr578038f2018-03-09 12:25:24 -08005328 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005329 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5330 if (!layer->isVisible()) {
5331 return;
Robert Carr578038f2018-03-09 12:25:24 -08005332 } else if (childrenOnly && layer == parent.get()) {
5333 return;
chaviwa76b2712017-09-20 12:02:26 -07005334 }
5335 visitor(layer);
5336 });
5337 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005338 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005339}
5340
5341status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5342 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005343 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005344 bool useIdentityTransform) {
5345 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005346
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005347 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5348 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5349 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5350 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005351
5352 // This mutex protects syncFd and captureResult for communication of the return values from the
5353 // main thread back to this Binder thread
5354 std::mutex captureMutex;
5355 std::condition_variable captureCondition;
5356 std::unique_lock<std::mutex> captureLock(captureMutex);
5357 int syncFd = -1;
5358 std::optional<status_t> captureResult;
5359
Robert Carr03480e22018-01-04 16:02:06 -08005360 const int uid = IPCThreadState::self()->getCallingUid();
5361 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5362
Dominik Laskowski8c001672018-05-30 16:52:06 -07005363 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364 // If there is a refresh pending, bug out early and tell the binder thread to try again
5365 // after the refresh.
5366 if (mRefreshPending) {
5367 ATRACE_NAME("Skipping screenshot for now");
5368 std::unique_lock<std::mutex> captureLock(captureMutex);
5369 captureResult = std::make_optional<status_t>(EAGAIN);
5370 captureCondition.notify_one();
5371 return;
5372 }
5373
5374 status_t result = NO_ERROR;
5375 int fd = -1;
5376 {
5377 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005378 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005379 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5380 useIdentityTransform, forSystem, &fd);
5381 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382 }
5383
5384 {
5385 std::unique_lock<std::mutex> captureLock(captureMutex);
5386 syncFd = fd;
5387 captureResult = std::make_optional<status_t>(result);
5388 captureCondition.notify_one();
5389 }
5390 });
5391
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005392 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005394 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395 while (*captureResult == EAGAIN) {
5396 captureResult.reset();
5397 result = postMessageAsync(message);
5398 if (result != NO_ERROR) {
5399 return result;
5400 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005401 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005402 }
5403 result = *captureResult;
5404 }
5405
5406 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005407 sync_wait(syncFd, -1);
5408 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005410
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005411 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005412}
5413
chaviwa76b2712017-09-20 12:02:26 -07005414void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005415 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005416 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005417 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005418
Lloyd Pique144e1162017-12-20 16:44:52 -08005419 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005420
chaviwa76b2712017-09-20 12:02:26 -07005421 const auto reqWidth = renderArea.getReqWidth();
5422 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005423 const auto sourceCrop = renderArea.getSourceCrop();
5424 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005425
Chia-I Wu36574d92018-05-16 10:54:36 -07005426 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5427 engine.setOutputDataSpace(Dataspace::SRGB);
5428 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005429
Mathias Agopian180f10d2013-04-10 22:55:41 -07005430 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005431 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005432
5433 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005434 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005435 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005436
chaviw50da5042018-04-09 13:49:37 -07005437 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005438 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005439 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005440
chaviwa76b2712017-09-20 12:02:26 -07005441 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005442 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005443 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005444}
5445
chaviwa76b2712017-09-20 12:02:26 -07005446status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5447 TraverseLayersFunction traverseLayers,
5448 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005449 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005450 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005451 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005452 ATRACE_CALL();
5453
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005454 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005455
5456 traverseLayers([&](Layer* layer) {
5457 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5458 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005459
Robert Carr03480e22018-01-04 16:02:06 -08005460 // We allow the system server to take screenshots of secure layers for
5461 // use in situations like the Screen-rotation animation and place
5462 // the impetus on WindowManager to not persist them.
5463 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005464 ALOGW("FB is protected: PERMISSION_DENIED");
5465 return PERMISSION_DENIED;
5466 }
5467
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005468 // this binds the given EGLImage as a framebuffer for the
5469 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005470 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005471 if (bufferBond.getStatus() != NO_ERROR) {
5472 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005473 return INVALID_OPERATION;
5474 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005475
Dan Stozaabcda352017-06-01 14:37:39 -07005476 // this will in fact render into our dequeued buffer
5477 // via an FBO, which means we didn't have to create
5478 // an EGLSurface and therefore we're not
5479 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005480 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005481
Dan Stozaabcda352017-06-01 14:37:39 -07005482 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005483 getRenderEngine().finish();
5484 *outSyncFd = -1;
5485
chaviwa76b2712017-09-20 12:02:26 -07005486 const auto reqWidth = renderArea.getReqWidth();
5487 const auto reqHeight = renderArea.getReqHeight();
5488
Dan Stozaabcda352017-06-01 14:37:39 -07005489 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5490 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005491 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005492 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005493 } else {
5494 base::unique_fd syncFd = getRenderEngine().flush();
5495 if (syncFd < 0) {
5496 getRenderEngine().finish();
5497 }
5498 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005499 }
5500
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005501 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005502}
5503
Mathias Agopiand5556842013-09-19 17:08:37 -07005504void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005505 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005506 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005507 for (size_t y = 0; y < h; y++) {
5508 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5509 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005510 if (p[x] != 0xFF000000) return;
5511 }
5512 }
chaviwa76b2712017-09-20 12:02:26 -07005513 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005514
Robert Carr2047fae2016-11-28 14:09:09 -08005515 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005516 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005517 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005518 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5519 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5520 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5521 static_cast<float>(state.color.a));
5522 i++;
5523 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005524 }
5525}
5526
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005527// ---------------------------------------------------------------------------
5528
Dan Stoza412903f2017-04-27 13:42:17 -07005529void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5530 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005531}
5532
Dan Stoza412903f2017-04-27 13:42:17 -07005533void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5534 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005535}
5536
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005537void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5538 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005539 const LayerVector::Visitor& visitor) {
5540 // We loop through the first level of layers without traversing,
5541 // as we need to interpret min/max layer Z in the top level Z space.
5542 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005543 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005544 continue;
5545 }
5546 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005547 // relative layers are traversed in Layer::traverseInZOrder
5548 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005549 continue;
5550 }
5551 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005552 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005553 return;
5554 }
chaviwa76b2712017-09-20 12:02:26 -07005555 if (!layer->isVisible()) {
5556 return;
5557 }
5558 visitor(layer);
5559 });
5560 }
5561}
5562
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005563}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005564
Lloyd Pique074e8122018-07-26 12:57:23 -07005565
Mathias Agopian3f844832013-08-07 21:24:32 -07005566#if defined(__gl_h_)
5567#error "don't include gl/gl.h in this file"
5568#endif
5569
5570#if defined(__gl2_h_)
5571#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005572#endif