blob: 4ef66d5db235539d55458097a14ebf0f7c9c67eb [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 Krulecfefcb582018-08-07 14:22:37 -070090
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
David Sodman7e4ae112018-02-09 15:02:28 -080093#include "android-base/stringprintf.h"
94
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080096#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070097#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090099#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100
chaviw1d044282017-09-27 12:19:28 -0700101#include <layerproto/LayerProtoParser.h>
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103#define DISPLAY_COUNT 1
104
Mathias Agopianfee2b462013-07-03 12:34:01 -0700105/*
106 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
107 * black pixels.
108 */
109#define DEBUG_SCREENSHOTS false
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112
Jaesoo Lee43518572017-01-23 19:03:16 +0900113using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700198
Kalle Raitaa099a242017-01-11 11:17:29 -0800199std::string getHwcServiceName() {
200 char value[PROPERTY_VALUE_MAX] = {};
201 property_get("debug.sf.hwc_service_name", value, "default");
202 ALOGI("Using HWComposer service: '%s'", value);
203 return std::string(value);
204}
205
206bool useTrebleTestingOverride() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.treble_testing_override", value, "false");
209 ALOGI("Treble testing override: '%s'", value);
210 return std::string(value) == "true";
211}
212
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800213std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
214 switch(displayColorSetting) {
215 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Enhanced");
221 default:
222 return std::string("Unknown ") +
223 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225}
226
Lloyd Pique99d3da52018-01-22 17:48:03 -0800227NativeWindowSurface::~NativeWindowSurface() = default;
228
229namespace impl {
230
231class NativeWindowSurface final : public android::NativeWindowSurface {
232public:
233 static std::unique_ptr<android::NativeWindowSurface> create(
234 const sp<IGraphicBufferProducer>& producer) {
235 return std::make_unique<NativeWindowSurface>(producer);
236 }
237
238 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
239 : surface(new Surface(producer, false)) {}
240
241 ~NativeWindowSurface() override = default;
242
243private:
244 sp<ANativeWindow> getNativeWindow() const override { return surface; }
245
246 void preallocateBuffers() override { surface->allocateBuffers(); }
247
248 sp<Surface> surface;
249};
250
251} // namespace impl
252
David Sodmanbc815282017-11-05 18:57:52 -0800253SurfaceFlingerBE::SurfaceFlingerBE()
254 : mHwcServiceName(getHwcServiceName()),
255 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800256 mFrameBuckets(),
257 mTotalTime(0),
258 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800259 mComposerSequenceId(0) {
260}
261
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800263 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700265 mTransactionPending(false),
266 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700267 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700268 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700269 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700271 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800273 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800274 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800275 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700277 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700278 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700279 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700280 mDebugInTransaction(0),
281 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700282 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700283 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700284 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800285 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800286 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800287 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700288 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800289 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800290 mCreateBufferQueue(&BufferQueue::createBufferQueue),
291 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800292
293SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800294 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800295
296 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
298
299 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
301
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800302 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
306 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
307
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700308 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
309 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
310
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800311 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
312 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
315 useVrFlinger = getBool< ISurfaceFlingerConfigs,
316 &ISurfaceFlingerConfigs::useVrFlinger>(false);
317
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
319 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
320
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600321 hasWideColorDisplay =
322 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700323 useColorManagement =
324 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
327 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
328 V1_1::DisplayOrientation::ORIENTATION_0);
329
330 switch (primaryDisplayOrientation) {
331 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
334 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
343 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800345
Lloyd Pique41be5d22018-06-21 13:11:48 -0700346 // Note: We create a local temporary with the real DispSync implementation
347 // type temporarily so we can initialize it with the configured values,
348 // before storing it for more generic use using the interface type.
349 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
350 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
351 SurfaceFlinger::dispSyncPresentTimeOffset);
352 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 DisplayDeviceState info;
492 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700493 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800496 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
509 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700510 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 mCurrentState.displays.removeItemsAt(idx);
516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700520 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
542
Steven Thomas050b2c82017-03-06 11:45:16 -0800543 if (mVrFlinger) {
544 mVrFlinger->OnBootFinished();
545 }
546
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700548 // formerly we would just kill the process, but we now ask it to exit so it
549 // can choose where to stop the animation.
550 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700551
552 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
553 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
554 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700555
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 postMessageAsync(new LambdaMessage([this] {
557 readPersistentProperties();
558 mBootStage = BootStage::FINISHED;
559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700584 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700585}
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
592
Thierry Strudel2924d012017-08-14 15:19:37 -0700593 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800598 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700599 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
600 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800601 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800603 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800604 "appEventThread");
605 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800607 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800608
Lloyd Pique24b0a482018-03-09 18:52:26 -0800609 mSFEventThread =
610 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800612 [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 },
615 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800616 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200617 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700620 int32_t renderEngineFeature = 0;
621 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800622 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700623 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800624 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800628 getBE().mHwc.reset(
629 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700630 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800631 // Process any initial hotplug and resulting display changes.
632 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 const auto display = getDefaultDisplayDeviceLocked();
634 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
635 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
636 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800637
Lloyd Piquefcd86612017-12-14 17:15:36 -0800638 // make the default display GLContext current so that we can create textures
639 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800641
Steven Thomas050b2c82017-03-06 11:45:16 -0800642 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700643 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700644 // This callback is called from the vr flinger dispatch thread. We
645 // need to call signalTransaction(), which requires holding
646 // mStateLock when we're not on the main thread. Acquiring
647 // mStateLock from the vr flinger dispatch thread might trigger a
648 // deadlock in surface flinger (see b/66916578), so post a message
649 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700650 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700651 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
652 mVrFlingerRequestsDisplay = requestDisplay;
653 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800655 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
657 getHwComposer()
658 .getHwcDisplayId(display->getId())
659 .value_or(0),
660 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 if (!mVrFlinger) {
662 ALOGE("Failed to start vrflinger");
663 }
664 }
665
Lloyd Pique379adc12018-01-22 17:31:47 -0800666 mEventControlThread = std::make_unique<impl::EventControlThread>(
667 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700668
Mathias Agopian92a979a2012-08-02 18:32:23 -0700669 // initialize our drawing state
670 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700671
Andy McFadden13a082e2012-08-24 10:16:42 -0700672 // set initial conditions (e.g. unblank default device)
673 initializeDisplays();
674
David Sodmanbc815282017-11-05 18:57:52 -0800675 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700676
Wei Wangf9b05ee2017-07-19 20:59:39 -0700677 // Inform native graphics APIs whether the present timestamp is supported:
678 if (getHwComposer().hasCapability(
679 HWC2::Capability::PresentFenceIsNotReliable)) {
680 mStartPropertySetThread = new StartPropertySetThread(false);
681 } else {
682 mStartPropertySetThread = new StartPropertySetThread(true);
683 }
684
685 if (mStartPropertySetThread->Start() != NO_ERROR) {
686 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688
Chia-I Wud49d6692018-06-27 07:17:41 +0800689 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
690 // is used to saturate legacy sRGB content. However, to make sure the same color under
691 // Display P3 will be saturated to the same color, we intentionally break the API spec
692 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
693 // such saturation matrix on Display P3 is understood fully, the API should always return
694 // identify matrix.
695 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
696 Dataspace::SRGB_LINEAR);
697
698 // we will apply this on Display P3.
699 if (mEnhancedSaturationMatrix != mat4()) {
700 ColorSpace srgb(ColorSpace::sRGB());
701 ColorSpace displayP3(ColorSpace::DisplayP3());
702 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
703 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
704 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
705 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800706
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700708}
709
Romain Guy11d63f42017-07-20 12:47:14 -0700710void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700711 Mutex::Autolock _l(mStateLock);
712
Romain Guy11d63f42017-07-20 12:47:14 -0700713 char value[PROPERTY_VALUE_MAX];
714
715 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800716 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700717 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100719
720 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700721 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700722}
723
Mathias Agopiana67e4182012-06-19 17:26:12 -0700724void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800725 // Start boot animation service by setting a property mailbox
726 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800728 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700729 if (mStartPropertySetThread->join() != NO_ERROR) {
730 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700732}
733
Mathias Agopian875d8e12013-06-07 15:35:48 -0700734size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800735 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700736}
737
Mathias Agopian875d8e12013-06-07 15:35:48 -0700738size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800739 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700740}
741
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800743
Jamie Gennis582270d2011-08-17 18:19:00 -0700744bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800745 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800746 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800747 return authenticateSurfaceTextureLocked(bufferProducer);
748}
749
750bool SurfaceFlinger::authenticateSurfaceTextureLocked(
751 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800752 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800753 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800754}
755
Brian Anderson6b376712017-04-04 10:51:39 -0700756status_t SurfaceFlinger::getSupportedFrameTimestamps(
757 std::vector<FrameEvent>* outSupported) const {
758 *outSupported = {
759 FrameEvent::REQUESTED_PRESENT,
760 FrameEvent::ACQUIRE,
761 FrameEvent::LATCH,
762 FrameEvent::FIRST_REFRESH_START,
763 FrameEvent::LAST_REFRESH_START,
764 FrameEvent::GPU_COMPOSITION_DONE,
765 FrameEvent::DEQUEUE_READY,
766 FrameEvent::RELEASE,
767 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700768 ConditionalLock _l(mStateLock,
769 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700770 if (!getHwComposer().hasCapability(
771 HWC2::Capability::PresentFenceIsNotReliable)) {
772 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
773 }
774 return NO_ERROR;
775}
776
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700777status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
778 Vector<DisplayInfo>* configs) {
779 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 return BAD_VALUE;
781 }
782
Jesse Hall692c7232012-11-08 15:41:56 -0800783 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700784 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
785 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700786 type = i;
787 break;
788 }
789 }
790
791 if (type < 0) {
792 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700793 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700794
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795 // TODO: Not sure if display density should handled by SF any longer
796 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700797 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700798 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700799 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800800 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700801 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802 }
803 return density;
804 }
805 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700806 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700808 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 return getDensityFromProperty("ro.sf.lcd_density"); }
810 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700811
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700813
Steven Thomas6d8110b2017-08-31 18:24:21 -0700814 ConditionalLock _l(mStateLock,
815 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 DisplayInfo info = DisplayInfo();
818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 float xdpi = hwConfig->getDpiX();
820 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700821
822 if (type == DisplayDevice::DISPLAY_PRIMARY) {
823 // The density of the device is provided by a build property
824 float density = Density::getBuildDensity() / 160.0f;
825 if (density == 0) {
826 // the build doesn't provide a density -- this is wrong!
827 // use xdpi instead
828 ALOGE("ro.sf.lcd_density must be defined as a build property");
829 density = xdpi / 160.0f;
830 }
831 if (Density::getEmuDensity()) {
832 // if "qemu.sf.lcd_density" is specified, it overrides everything
833 xdpi = ydpi = density = Density::getEmuDensity();
834 density /= 160.0f;
835 }
836 info.density = density;
837
838 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700839 const auto display = getDefaultDisplayDeviceLocked();
840 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 } else {
842 // TODO: where should this value come from?
843 static const int TV_DENSITY = 213;
844 info.density = TV_DENSITY / 160.0f;
845 info.orientation = 0;
846 }
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 info.w = hwConfig->getWidth();
849 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 info.xdpi = xdpi;
851 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900853 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854
Andy McFadden91b2ca82014-06-13 14:04:23 -0700855 // This is how far in advance a buffer must be queued for
856 // presentation at a given time. If you want a buffer to appear
857 // on the screen at time N, you must submit the buffer before
858 // (N - presentationDeadline).
859 //
860 // Normally it's one full refresh period (to give SF a chance to
861 // latch the buffer), but this can be reduced by configuring a
862 // DispSync offset. Any additional delays introduced by the hardware
863 // composer or panel must be accounted for here.
864 //
865 // We add an additional 1ms to allow for processing time and
866 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800868 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700869
870 // All non-virtual displays are currently considered secure.
871 info.secure = true;
872
Iris Chang7501ed62018-04-30 14:45:42 +0800873 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700874 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800875 std::swap(info.w, info.h);
876 }
877
Michael Wright28f24d02016-07-12 13:30:53 -0700878 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700879 }
880
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 return NO_ERROR;
882}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
885 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700886 return BAD_VALUE;
887 }
888
889 // FIXME for now we always return stats for the primary display
890 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700891 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
892 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700893 return NO_ERROR;
894}
895
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700896status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
897 if (outViewport == nullptr || display.get() == nullptr) {
898 return BAD_VALUE;
899 }
900
901 sp<const DisplayDevice> device(getDisplayDevice(display));
902 if (device == nullptr) {
903 return BAD_VALUE;
904 }
905
906 *outViewport = device->getViewport();
907
908 return NO_ERROR;
909}
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
912 const auto display = getDisplayDevice(displayToken);
913 if (!display) {
914 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800915 return BAD_VALUE;
916 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
922 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924 return;
925 }
926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 ALOGW("Trying to set config for virtual display");
929 return;
930 }
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 display->setActiveConfig(mode);
933 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934}
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700937 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 Vector<DisplayInfo> configs;
939 getDisplayConfigs(displayToken, &configs);
940 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
941 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
942 configs.size());
943 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 const auto display = getDisplayDevice(displayToken);
946 if (!display) {
947 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
948 displayToken.get());
949 } else if (display->isVirtual()) {
950 ALOGW("Attempt to set active config %d for virtual display", mode);
951 } else {
952 setActiveConfigInternal(display, mode);
953 }
954 }));
955
Mathias Agopian888c8222012-08-04 21:10:38 -0700956 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700957}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
959 Vector<ColorMode>* outColorModes) {
960 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700961 return BAD_VALUE;
962 }
963
Michael Wright28f24d02016-07-12 13:30:53 -0700964 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
966 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700967 type = i;
968 break;
969 }
970 }
971
972 if (type < 0) {
973 return type;
974 }
975
Peiyong Lina52f0292018-03-14 17:26:31 -0700976 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700977 {
978 ConditionalLock _l(mStateLock,
979 std::this_thread::get_id() != mMainThreadId);
980 modes = getHwComposer().getColorModes(type);
981 }
Michael Wright28f24d02016-07-12 13:30:53 -0700982 outColorModes->clear();
983 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
984
985 return NO_ERROR;
986}
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
989 if (const auto display = getDisplayDevice(displayToken)) {
990 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700991 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700993}
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
996 Dataspace dataSpace, RenderIntent renderIntent) {
997 ColorMode currentMode = display->getActiveColorMode();
998 Dataspace currentDataSpace = display->getCompositionDataSpace();
999 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001000
Peiyong Lin38e9a562018-04-10 16:24:20 -07001001 if (mode == currentMode && dataSpace == currentDataSpace &&
1002 renderIntent == currentRenderIntent) {
1003 return;
1004 }
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001007 ALOGW("Trying to set config for virtual display");
1008 return;
1009 }
1010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011 display->setActiveColorMode(mode);
1012 display->setCompositionDataSpace(dataSpace);
1013 display->setActiveRenderIntent(renderIntent);
1014 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001015
1016 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1018 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001022 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 Vector<ColorMode> modes;
1024 getDisplayColorModes(displayToken, &modes);
1025 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1026 if (mode < ColorMode::NATIVE || !exists) {
1027 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1028 decodeColorMode(mode).c_str(), mode, displayToken.get());
1029 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001030 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 const auto display = getDisplayDevice(displayToken);
1032 if (!display) {
1033 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1034 decodeColorMode(mode).c_str(), mode, displayToken.get());
1035 } else if (display->isVirtual()) {
1036 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1037 decodeColorMode(mode).c_str(), mode);
1038 } else {
1039 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1040 RenderIntent::COLORIMETRIC);
1041 }
1042 }));
1043
Michael Wright28f24d02016-07-12 13:30:53 -07001044 return NO_ERROR;
1045}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001046
Svetoslavd85084b2014-03-20 10:28:31 -07001047status_t SurfaceFlinger::clearAnimationFrameStats() {
1048 Mutex::Autolock _l(mStateLock);
1049 mAnimFrameTracker.clearStats();
1050 return NO_ERROR;
1051}
1052
1053status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1054 Mutex::Autolock _l(mStateLock);
1055 mAnimFrameTracker.getStats(outStats);
1056 return NO_ERROR;
1057}
1058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1060 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001061 Mutex::Autolock _l(mStateLock);
1062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDeviceLocked(displayToken);
1064 if (!display) {
1065 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001066 return BAD_VALUE;
1067 }
1068
Peiyong Linfb069302018-04-25 14:34:31 -07001069 // At this point the DisplayDeivce should already be set up,
1070 // meaning the luminance information is already queried from
1071 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001073 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1074 capabilities.getDesiredMaxLuminance(),
1075 capabilities.getDesiredMaxAverageLuminance(),
1076 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077
1078 return NO_ERROR;
1079}
1080
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001082 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 if (mInjectVSyncs == enable) {
1086 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001088
1089 if (enable) {
1090 ALOGV("VSync Injections enabled");
1091 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001092 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001093 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001094 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001095 impl::EventThread::InterceptVSyncsCallback(),
1096 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001098 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 } else {
1100 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001101 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102 }
1103
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001105 }));
1106
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001107 return NO_ERROR;
1108}
1109
1110status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 Mutex::Autolock _l(mStateLock);
1112
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001113 if (!mInjectVSyncs) {
1114 ALOGE("VSync Injections not enabled");
1115 return BAD_VALUE;
1116 }
1117 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1118 ALOGV("Injecting VSync inside SurfaceFlinger");
1119 mVSyncInjector->onInjectSyncEvent(when);
1120 }
1121 return NO_ERROR;
1122}
1123
Lloyd Pique755e3192018-01-31 16:46:15 -08001124status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1125 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001126 // Try to acquire a lock for 1s, fail gracefully
1127 const status_t err = mStateLock.timedLock(s2ns(1));
1128 const bool locked = (err == NO_ERROR);
1129 if (!locked) {
1130 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1131 return TIMED_OUT;
1132 }
1133
1134 outLayers->clear();
1135 mCurrentState.traverseInZOrder([&](Layer* layer) {
1136 outLayers->push_back(layer->getLayerDebugInfo());
1137 });
1138
1139 mStateLock.unlock();
1140 return NO_ERROR;
1141}
1142
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001143// ----------------------------------------------------------------------------
1144
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001145sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1146 ISurfaceComposer::VsyncSource vsyncSource) {
1147 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1148 return mSFEventThread->createEventConnection();
1149 } else {
1150 return mEventThread->createEventConnection();
1151 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001152}
1153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155
1156void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001157 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158}
1159
1160void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162}
1163
1164void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166}
1167
1168void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001169 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171}
1172
1173status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001174 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001175 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176}
1177
1178status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001179 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001180 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001181 if (res == NO_ERROR) {
1182 msg->wait();
1183 }
1184 return res;
1185}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001187void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001188 do {
1189 waitForEvent();
1190 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001191}
1192
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193void SurfaceFlinger::enableHardwareVsync() {
1194 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001196 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001197 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001199 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200}
1201
Jesse Hall948fe0c2013-10-14 12:56:09 -07001202void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 Mutex::Autolock _l(mHWVsyncLock);
1204
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 if (makeAvailable) {
1206 mHWVsyncAvailable = true;
1207 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001208 // Hardware vsync is not currently available, so abort the resync
1209 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001210 return;
1211 }
1212
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001213 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1214 if (!getHwComposer().isConnected(displayId)) {
1215 return;
1216 }
1217
1218 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220
Lloyd Pique41be5d22018-06-21 13:11:48 -07001221 mPrimaryDispSync->reset();
1222 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223
1224 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001225 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryHWVsyncEnabled = true;
1228 }
1229}
1230
Jesse Hall948fe0c2013-10-14 12:56:09 -07001231void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232 Mutex::Autolock _l(mHWVsyncLock);
1233 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001234 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001235 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001236 mPrimaryHWVsyncEnabled = false;
1237 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 if (makeUnavailable) {
1239 mHWVsyncAvailable = false;
1240 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241}
1242
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243void SurfaceFlinger::resyncWithRateLimit() {
1244 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001245
1246 // No explicit locking is needed here since EventThread holds a lock while calling this method
1247 static nsecs_t sLastResyncAttempted = 0;
1248 const nsecs_t now = systemTime();
1249 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001250 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001251 }
Dan Stoza57164302017-05-08 14:03:54 -07001252 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001253}
1254
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001255void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1256 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001257 ATRACE_NAME("SF onVsync");
1258
Steven Thomas3cfac282017-02-06 12:29:30 -08001259 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001260 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001261 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001262 return;
1263 }
1264
1265 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001266 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001267 return;
1268 }
1269
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001270 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1271 // For now, we don't do anything with external display vsyncs.
1272 return;
1273 }
1274
Jamie Gennisd1700752013-10-14 12:22:52 -07001275 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276
Jamie Gennisd1700752013-10-14 12:22:52 -07001277 { // Scope for the lock
1278 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001279 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001280 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001282 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001283
1284 if (needsHwVsync) {
1285 enableHardwareVsync();
1286 } else {
1287 disableHardwareVsync(false);
1288 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001289}
1290
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001291void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001292 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1293 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001294}
1295
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001296void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001297 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001298 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001299 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300
Lloyd Piqueba04e622017-12-14 17:11:26 -08001301 // Ignore events that do not have the right sequenceId.
1302 if (sequenceId != getBE().mComposerSequenceId) {
1303 return;
1304 }
1305
Steven Thomasb02664d2017-07-26 18:48:28 -07001306 // Only lock if we're not on the main thread. This function is normally
1307 // called on a hwbinder thread, but for the primary display it's called on
1308 // the main thread with the state lock already held, so don't attempt to
1309 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001310 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001311
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001312 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001313
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001314 if (std::this_thread::get_id() == mMainThreadId) {
1315 // Process all pending hot plug events immediately if we are on the main thread.
1316 processDisplayHotplugEventsLocked();
1317 }
1318
Lloyd Piqueba04e622017-12-14 17:11:26 -08001319 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001320}
1321
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001322void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001323 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001324 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001327 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001328}
1329
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 getHwComposer().setVsyncEnabled(disp,
1334 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001335}
1336
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001338void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 // Clear the drawing state so that the logic inside of
1341 // handleTransactionLocked will fire. It will determine the delta between
1342 // mCurrentState and mDrawingState and re-apply all changes when we make the
1343 // transition.
1344 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001345 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346 mDisplays.clear();
1347}
1348
Steven Thomas050b2c82017-03-06 11:45:16 -08001349void SurfaceFlinger::updateVrFlinger() {
1350 if (!mVrFlinger)
1351 return;
1352 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001353 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001354 return;
1355 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356
David Sodman105b7dc2017-11-04 20:28:14 -07001357 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 ALOGE("Vr flinger is only supported for remote hardware composer"
1359 " service connections. Ignoring request to transition to vr"
1360 " flinger.");
1361 mVrFlingerRequestsDisplay = false;
1362 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001363 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001364
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001366
Steven Thomas0123ac62018-07-12 11:32:34 -07001367 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001368 LOG_ALWAYS_FATAL_IF(!display);
1369 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001370 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1371 // called below. Clear the reference now so we don't accidentally use it
1372 // later.
1373 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001380 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001381 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1382 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001383 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384
David Sodman105b7dc2017-11-04 20:28:14 -07001385 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1386 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001387
1388 if (vrFlingerRequestsDisplay) {
1389 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391
1392 mVisibleRegionsDirty = true;
1393 invalidateHwcGeometry();
1394
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001395 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001396 display = getDefaultDisplayDeviceLocked();
1397 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001398 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001401 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 const nsecs_t period = activeConfig->getVsyncPeriod();
1403 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001404
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001405 // The present fences returned from vr_hwc are not an accurate
1406 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001407 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1408 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 // Use phase of 0 since phase is not known.
1411 // Use latency of 0, which will snap to the ideal latency.
1412 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001413
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001414 resyncToHardwareVsync(false);
1415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 android_atomic_or(1, &mRepaintEverything);
1417 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418}
1419
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001421 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001422 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001424 bool frameMissed = !mHadClientComposition &&
1425 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001426 (mPreviousPresentFence->getSignalTime() ==
1427 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001428 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001429 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001430 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001431 mTimeStats.incrementMissedFrames();
1432 if (mPropagateBackpressure) {
1433 signalLayerUpdate();
1434 break;
1435 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001436 }
Dan Stoza50182882016-07-08 12:02:20 -07001437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001446 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Mathias Agopian4fec8732012-06-29 14:12:52 -07001470void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001472
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001473 mRefreshPending = false;
1474
David Sodmanfa9b2af2017-12-24 13:28:59 -08001475 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001476 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001477 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001478 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001479
David Sodmanfa9b2af2017-12-24 13:28:59 -08001480 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001481 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001482 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001483 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1484 setUpHWComposer(compositionInfo);
1485 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001486 prepareFrame(display);
1487 doDebugFlashRegions(display, repaintEverything);
1488 doComposition(display, repaintEverything);
1489 }
1490
Adrian Roos1e1a1282017-11-01 19:05:31 +01001491 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001492 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001493
1494 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001495 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001496
Dan Stozabfbffeb2016-07-21 14:49:33 -07001497 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001498 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001499 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001500 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001501 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001502
Jorim Jaggi90535212018-05-23 23:44:06 +02001503 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001504
David Sodman7e4ae112018-02-09 15:02:28 -08001505 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001506 for (const auto& [token, display] : mDisplays) {
1507 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001508 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001509 compositionInfo.hwc.hwcLayer = nullptr;
1510 }
David Sodmanba340492018-08-05 21:51:33 -07001511 }
David Sodman7e4ae112018-02-09 15:02:28 -08001512
1513 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515
David Sodmanfa9b2af2017-12-24 13:28:59 -08001516
1517bool SurfaceFlinger::handleMessageInvalidate() {
1518 ATRACE_CALL();
1519 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520}
1521
David Sodman79bba0e2018-08-05 18:07:49 -07001522void SurfaceFlinger::calculateWorkingSet() {
1523 ATRACE_CALL();
1524 ALOGV(__FUNCTION__);
1525
David Sodman79bba0e2018-08-05 18:07:49 -07001526 // build the h/w work list
1527 if (CC_UNLIKELY(mGeometryInvalid)) {
1528 mGeometryInvalid = false;
1529 for (const auto& [token, display] : mDisplays) {
1530 const auto displayId = display->getId();
1531 if (displayId >= 0) {
1532 const Vector<sp<Layer>>& currentLayers(
1533 display->getVisibleLayersSortedByZ());
1534 for (size_t i = 0; i < currentLayers.size(); i++) {
1535 const auto& layer = currentLayers[i];
1536
1537 if (!layer->hasHwcLayer(displayId)) {
1538 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1539 layer->forceClientComposition(displayId);
1540 continue;
1541 }
1542 }
1543
1544 layer->setGeometry(display, i);
1545 if (mDebugDisableHWC || mDebugRegion) {
1546 layer->forceClientComposition(displayId);
1547 }
1548 }
1549 }
1550 }
1551 }
1552
1553 // Set the per-frame data
1554 for (const auto& [token, display] : mDisplays) {
1555 const auto displayId = display->getId();
1556 if (displayId < 0) {
1557 continue;
1558 }
1559
1560 if (mDrawingState.colorMatrixChanged) {
1561 display->setColorTransform(mDrawingState.colorMatrix);
1562 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1563 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1564 "display %d: %d", displayId, result);
1565 }
1566 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1567 if (layer->isHdrY410()) {
1568 layer->forceClientComposition(displayId);
1569 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1570 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1571 !display->hasHDR10Support()) {
1572 layer->forceClientComposition(displayId);
1573 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1574 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1575 !display->hasHLGSupport()) {
1576 layer->forceClientComposition(displayId);
1577 }
1578
1579 if (layer->getForceClientComposition(displayId)) {
1580 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1581 layer->setCompositionType(displayId, HWC2::Composition::Client);
1582 continue;
1583 }
1584
1585 layer->setPerFrameData(display);
1586 }
1587
Peiyong Lin13effd12018-07-24 17:01:47 -07001588 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001589 ColorMode colorMode;
1590 Dataspace dataSpace;
1591 RenderIntent renderIntent;
1592 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1593 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1594 }
1595 }
1596
1597 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001598
1599 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001600 const auto displayId = display->getId();
1601 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001602 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1603 auto displayId = display->getId();
1604 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1605 if (!layer->setHwcLayer(displayId)) {
1606 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1607 }
David Sodman15fb96e2018-01-07 10:23:24 -08001608 layer->getBE().compositionInfo.hwc.displayId = displayId;
1609 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001610 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1611 }
1612 }
David Sodman79bba0e2018-08-05 18:07:49 -07001613}
1614
David Sodmanfa9b2af2017-12-24 13:28:59 -08001615void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001617 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618 // is debugging enabled
1619 if (CC_LIKELY(!mDebugRegion))
1620 return;
1621
David Sodmanfa9b2af2017-12-24 13:28:59 -08001622 if (display->isPoweredOn()) {
1623 // transform the dirty region into this screen's coordinate space
1624 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1625 if (!dirtyRegion.isEmpty()) {
1626 // redraw the whole screen
1627 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628
David Sodmanfa9b2af2017-12-24 13:28:59 -08001629 // and draw the dirty region
1630 const int32_t height = display->getHeight();
1631 auto& engine(getRenderEngine());
1632 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001633
David Sodmanfa9b2af2017-12-24 13:28:59 -08001634 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 }
1636 }
1637
David Sodmanfa9b2af2017-12-24 13:28:59 -08001638 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001639
1640 if (mDebugRegion > 1) {
1641 usleep(mDebugRegion * 1000);
1642 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001643
David Sodmanfa9b2af2017-12-24 13:28:59 -08001644 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001645 status_t result = display->prepareFrame(
1646 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001647 ALOGE_IF(result != NO_ERROR,
1648 "prepareFrame for display %d failed:"
1649 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001650 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001651 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652}
1653
Adrian Roos1e1a1282017-11-01 19:05:31 +01001654void SurfaceFlinger::doTracing(const char* where) {
1655 ATRACE_CALL();
1656 ATRACE_NAME(where);
1657 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001658 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001659 }
1660}
1661
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001662void SurfaceFlinger::logLayerStats() {
1663 ATRACE_CALL();
1664 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001665 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001666 if (display->isPrimary()) {
1667 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001668 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001669 }
1670 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001671
1672 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001673 }
1674}
1675
David Sodman2b406362017-12-15 13:33:47 -08001676void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 ATRACE_CALL();
1679 ALOGV("preComposition");
1680
David Sodman2b406362017-12-15 13:33:47 -08001681 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1682
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001684 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001685 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686 needExtraInvalidate = true;
1687 }
Robert Carr2047fae2016-11-28 14:09:09 -08001688 });
1689
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690 if (needExtraInvalidate) {
1691 signalLayerUpdate();
1692 }
1693}
1694
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695void SurfaceFlinger::updateCompositorTiming(
1696 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1697 std::shared_ptr<FenceTime>& presentFenceTime) {
1698 // Update queue of past composite+present times and determine the
1699 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001700 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001702 while (!getBE().mCompositePresentTimes.empty()) {
1703 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704 // Cached values should have been updated before calling this method,
1705 // which helps avoid duplicate syscalls.
1706 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1707 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1708 break;
1709 }
1710 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001711 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712 }
1713
1714 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001715 while (getBE().mCompositePresentTimes.size() > 16) {
1716 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717 }
1718
Brian Andersond0010582017-03-07 13:20:31 -08001719 setCompositorTimingSnapped(
1720 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1721}
1722
1723void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1724 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 // Integer division and modulo round toward 0 not -inf, so we need to
1726 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001727 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001728 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1729 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1730
Brian Andersond0010582017-03-07 13:20:31 -08001731 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1732 if (idealLatency <= 0) {
1733 idealLatency = vsyncInterval;
1734 }
1735
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736 // Snap the latency to a value that removes scheduling jitter from the
1737 // composition and present times, which often have >1ms of jitter.
1738 // Reducing jitter is important if an app attempts to extrapolate
1739 // something (such as user input) to an accurate diasplay time.
1740 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1741 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001742 nsecs_t bias = vsyncInterval / 2;
1743 int64_t extraVsyncs =
1744 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1745 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1746 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001747
David Sodman99974d22017-11-28 12:04:33 -08001748 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1749 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1750 getBE().mCompositorTiming.interval = vsyncInterval;
1751 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752}
1753
David Sodman2b406362017-12-15 13:33:47 -08001754void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 ATRACE_CALL();
1757 ALOGV("postComposition");
1758
Brian Anderson3546a3f2016-07-14 11:51:14 -07001759 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001760 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001761 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001762 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001763 }
1764
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001765 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001766 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767
David Sodman73beded2017-11-15 11:56:06 -08001768 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001769 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001770 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001771 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001772 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001773 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774 } else {
1775 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1776 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001777
David Sodman73beded2017-11-15 11:56:06 -08001778 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001779 mPreviousPresentFence =
1780 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1781 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001782 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001783
Lloyd Pique41be5d22018-06-21 13:11:48 -07001784 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1785 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786
David Sodman2b406362017-12-15 13:33:47 -08001787 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 // when we started doing work for this frame, but that should be okay
1789 // since updateCompositorTiming has snapping logic.
1790 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001791 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001792 CompositorTiming compositorTiming;
1793 {
David Sodman99974d22017-11-28 12:04:33 -08001794 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1795 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001796 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797
Robert Carr2047fae2016-11-28 14:09:09 -08001798 mDrawingState.traverseInZOrder([&](Layer* layer) {
1799 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001800 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001801 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001802 recordBufferingStats(layer->getName().string(),
1803 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001804 }
Robert Carr2047fae2016-11-28 14:09:09 -08001805 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001806
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001807 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001808 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001809 enableHardwareVsync();
1810 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001811 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001812 }
1813 }
1814
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001815 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001816 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001817 enableHardwareVsync();
1818 }
1819 }
1820
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001821 if (mAnimCompositionPending) {
1822 mAnimCompositionPending = false;
1823
Brian Anderson4e606e32017-03-16 15:34:57 -07001824 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001825 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001826 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001827 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001828 // The HWC doesn't support present fences, so use the refresh
1829 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001831 mAnimFrameTracker.setActualPresentTime(presentTime);
1832 }
1833 mAnimFrameTracker.advanceFrame();
1834 }
Dan Stozab90cf072015-03-05 11:05:59 -08001835
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001836 mTimeStats.incrementTotalFrames();
1837 if (mHadClientComposition) {
1838 mTimeStats.incrementClientCompositionFrames();
1839 }
1840
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001841 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001842 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001843 return;
1844 }
1845
1846 nsecs_t currentTime = systemTime();
1847 if (mHasPoweredOff) {
1848 mHasPoweredOff = false;
1849 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001850 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001852 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1853 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001854 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001855 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001856 }
David Sodman4a36e932017-11-07 14:29:47 -08001857 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001858 }
David Sodman4a36e932017-11-07 14:29:47 -08001859 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001860
1861 {
1862 std::lock_guard lock(mTexturePoolMutex);
1863 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1864 if (refillCount > 0) {
1865 const size_t offset = mTexturePool.size();
1866 mTexturePool.resize(mTexturePoolSize);
1867 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1868 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1869 }
1870 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871}
1872
1873void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 ATRACE_CALL();
1875 ALOGV("rebuildLayerStacks");
1876
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001878 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001879 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001880 mVisibleRegionsDirty = false;
1881 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001882
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001883 for (const auto& pair : mDisplays) {
1884 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 Region opaqueRegion;
1886 Region dirtyRegion;
1887 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001888 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001889 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 const Rect bounds = display->getBounds();
1891 if (display->isPoweredOn()) {
1892 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001893
Jeff Sharkey76488112017-02-27 14:15:18 -07001894 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001895 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001897 Region drawRegion(tr.transform(
1898 layer->visibleNonTransparentRegion));
1899 drawRegion.andSelf(bounds);
1900 if (!drawRegion.isEmpty()) {
1901 layersSortedByZ.add(layer);
1902 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001903 // Clear out the HWC layer if this layer was
1904 // previously visible, but no longer is
1905 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001906 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001907 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001908 // WM changes display->layerStack upon sleep/awake.
1909 // Here we make sure we delete the HWC layers even if
1910 // WM changed their layer stack.
1911 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001912 }
1913
1914 // If a layer is not going to get a release fence because
1915 // it is invisible, but it is also going to release its
1916 // old buffer, add it to the list of layers needing
1917 // fences.
1918 if (hwcLayerDestroyed) {
1919 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1920 mLayersWithQueuedFrames.cend(), layer);
1921 if (found != mLayersWithQueuedFrames.cend()) {
1922 layersNeedingFences.add(layer);
1923 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001924 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001925 });
1926 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001927 display->setVisibleLayersSortedByZ(layersSortedByZ);
1928 display->setLayersNeedingFences(layersNeedingFences);
1929 display->undefinedRegion.set(bounds);
1930 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1931 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001932 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001933 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001935
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001936// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001938// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940// The returned HDR data space is one of
1941// - Dataspace::UNKNOWN
1942// - Dataspace::BT2020_HLG
1943// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001944Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1945 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001946 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001947 *outHdrDataSpace = Dataspace::UNKNOWN;
1948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001949 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001950 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001951 case Dataspace::V0_SCRGB:
1952 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001953 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001954 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956 case Dataspace::BT2020_PQ:
1957 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001958 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001959 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001960 case Dataspace::BT2020_HLG:
1961 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001962 // When there's mixed PQ content and HLG content, we set the HDR
1963 // data space to be BT2020_PQ and convert HLG to PQ.
1964 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1965 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001966 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001967 break;
1968 default:
1969 break;
1970 }
Romain Guy54f154a2017-10-24 21:40:32 +01001971 }
1972
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001973 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001974}
1975
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001977void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1978 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001979 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1980 *outMode = ColorMode::NATIVE;
1981 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001982 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001984 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001985
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001986 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001987 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001988
Peiyong Lindfde5112018-06-05 10:58:41 -07001989 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001990 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001991 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001992 if (isHdr) {
1993 bestDataSpace = hdrDataSpace;
1994 }
1995
Chia-I Wu0d711262018-05-21 15:19:35 -07001996 RenderIntent intent;
1997 switch (mDisplayColorSetting) {
1998 case DisplayColorSetting::MANAGED:
1999 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002000 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002001 break;
2002 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002003 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002004 break;
2005 default: // vendor display color setting
2006 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2007 break;
2008 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002010 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002011}
2012
David Sodman10a41ff2018-08-05 12:14:17 -07002013void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2014{
2015 HWC2::Error error;
2016 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2017 "CompositionType is sideband, but sideband stream is nullptr");
2018 error = (compositionInfo.hwc.hwcLayer)
2019 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2020 if (error != HWC2::Error::None) {
2021 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2022 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2023 static_cast<int32_t>(error));
2024 }
2025}
2026
2027void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2028{
2029 HWC2::Error error;
2030
2031 if (!compositionInfo.hwc.skipGeometry) {
2032 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2033 ALOGE_IF(error != HWC2::Error::None,
2034 "[SF] Failed to set blend mode %s:"
2035 " %s (%d)",
2036 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2037 static_cast<int32_t>(error));
2038
2039 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2040 ALOGE_IF(error != HWC2::Error::None,
2041 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2042 compositionInfo.hwc.displayFrame.left,
2043 compositionInfo.hwc.displayFrame.right,
2044 compositionInfo.hwc.displayFrame.top,
2045 compositionInfo.hwc.displayFrame.bottom,
2046 to_string(error).c_str(), static_cast<int32_t>(error));
2047
2048 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2049 ALOGE_IF(error != HWC2::Error::None,
2050 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2051 compositionInfo.hwc.sourceCrop.left,
2052 compositionInfo.hwc.sourceCrop.right,
2053 compositionInfo.hwc.sourceCrop.top,
2054 compositionInfo.hwc.sourceCrop.bottom,
2055 to_string(error).c_str(), static_cast<int32_t>(error));
2056
2057 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2058 ALOGE_IF(error != HWC2::Error::None,
2059 "[SF] Failed to set plane alpha %.3f: "
2060 "%s (%d)",
2061 compositionInfo.hwc.alpha,
2062 to_string(error).c_str(), static_cast<int32_t>(error));
2063
2064
2065 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2066 ALOGE_IF(error != HWC2::Error::None,
2067 "[SF] Failed to set Z %u: %s (%d)",
2068 compositionInfo.hwc.z,
2069 to_string(error).c_str(), static_cast<int32_t>(error));
2070
2071 error = (compositionInfo.hwc.hwcLayer)
2072 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2073 ALOGE_IF(error != HWC2::Error::None,
2074 "[SF] Failed to set info (%d)",
2075 static_cast<int32_t>(error));
2076
2077 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2078 ALOGE_IF(error != HWC2::Error::None,
2079 "[SF] Failed to set transform %s: "
2080 "%s (%d)",
2081 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2082 static_cast<int32_t>(error));
2083 }
2084
2085 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2086 ALOGE_IF(error != HWC2::Error::None,
2087 "[SF] Failed to set composition type: %s (%d)",
2088 to_string(error).c_str(), static_cast<int32_t>(error));
2089
2090 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2091 ALOGE_IF(error != HWC2::Error::None,
2092 "[SF] Failed to set dataspace: %s (%d)",
2093 to_string(error).c_str(), static_cast<int32_t>(error));
2094
2095 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2096 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2097 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2098 "[SF] Failed to set hdrMetadata: %s (%d)",
2099 to_string(error).c_str(), static_cast<int32_t>(error));
2100
2101 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2102 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2103 ALOGE_IF(error != HWC2::Error::None,
2104 "[SF] Failed to set color: %s (%d)",
2105 to_string(error).c_str(), static_cast<int32_t>(error));
2106 }
2107
2108 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2109 ALOGE_IF(error != HWC2::Error::None,
2110 "[SF] Failed to set visible region: %s (%d)",
2111 to_string(error).c_str(), static_cast<int32_t>(error));
2112
2113 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2114 ALOGE_IF(error != HWC2::Error::None,
2115 "[SF] Failed to set surface damage: %s (%d)",
2116 to_string(error).c_str(), static_cast<int32_t>(error));
2117}
2118
2119void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2120{
2121 HWC2::Error error;
2122
2123 if (compositionInfo.hwc.fence) {
2124 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2125 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2126 ALOGE_IF(error != HWC2::Error::None,
2127 "[SF] Failed to set buffer: %s (%d)",
2128 to_string(error).c_str(), static_cast<int32_t>(error));
2129 }
2130}
2131
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002133{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002134 bool dirty = !display->getDirtyRegion(false).isEmpty();
2135 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2136 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138 // If nothing has changed (!dirty), don't recompose.
2139 // If something changed, but we don't currently have any visible layers,
2140 // and didn't when we last did a composition, then skip it this time.
2141 // The second rule does two things:
2142 // - When all layers are removed from a display, we'll emit one black
2143 // frame, then nothing more until we get new layers.
2144 // - When a display is created with a private layer stack, we won't
2145 // emit any black frames until a layer is added to the layer stack.
2146 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002147
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002148 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2149 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002150 mustRecompose ? "doing" : "skipping",
2151 dirty ? "+" : "-",
2152 empty ? "+" : "-",
2153 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002154
David Sodmanfa9b2af2017-12-24 13:28:59 -08002155 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002156
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 if (mustRecompose) {
2158 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002159 }
2160}
2161
David Sodmanfa9b2af2017-12-24 13:28:59 -08002162void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002163{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002164 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165 if (!display->isPoweredOn()) {
2166 return;
David Sodman2b406362017-12-15 13:33:47 -08002167 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168
David Sodmanfb95bcc2017-12-22 15:45:30 -08002169 status_t result = display->prepareFrame(
2170 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002171 ALOGE_IF(result != NO_ERROR,
2172 "prepareFrame for display %d failed:"
2173 " %d (%s)",
2174 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002175}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002176
David Sodman10a41ff2018-08-05 12:14:17 -07002177void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2178 ATRACE_CALL();
2179 ALOGV("setUpHWComposer");
2180
2181 switch (compositionInfo.compositionType)
2182 {
2183 case HWC2::Composition::Invalid:
2184 case HWC2::Composition::Client:
2185 break;
2186
2187 case HWC2::Composition::Sideband:
2188 configureHwcCommonData(compositionInfo);
2189 configureSidebandComposition(compositionInfo);
2190 break;
2191
2192 case HWC2::Composition::SolidColor:
2193 configureHwcCommonData(compositionInfo);
2194 break;
2195
2196 case HWC2::Composition::Device:
2197 case HWC2::Composition::Cursor:
2198 configureHwcCommonData(compositionInfo);
2199 configureDeviceComposition(compositionInfo);
2200 break;
2201 }
2202}
2203
David Sodmanfa9b2af2017-12-24 13:28:59 -08002204void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 ALOGV("doComposition");
2207
David Sodmanfa9b2af2017-12-24 13:28:59 -08002208 if (display->isPoweredOn()) {
2209 // transform the dirty region into this screen's coordinate space
2210 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002211
David Sodmanfa9b2af2017-12-24 13:28:59 -08002212 // repaint the framebuffer (if needed)
2213 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002214
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215 display->dirtyRegion.clear();
2216 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002217 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002219}
2220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221void SurfaceFlinger::postFrame()
2222{
2223 // |mStateLock| not needed as we are on the main thread
2224 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2225 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2226 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2227 logFrameStats();
2228 }
2229 }
2230}
2231
2232void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233{
Mathias Agopian841cde52012-03-01 15:44:37 -08002234 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002236
David Sodmanfa9b2af2017-12-24 13:28:59 -08002237 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002238
David Sodmanfa9b2af2017-12-24 13:28:59 -08002239 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002240 const auto displayId = display->getId();
2241 if (displayId >= 0) {
2242 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002243 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002244 display->onSwapBuffersCompleted();
2245 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002246 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002247 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002248 // The layer buffer from the previous frame (if any) is released
2249 // by HWC only when the release fence from this frame (if any) is
2250 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002251 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2252 if ((displayId >= 0) && hwcLayer) {
2253 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002254 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002255
2256 // If the layer was client composited in the previous frame, we
2257 // need to merge with the previous client target acquire fence.
2258 // Since we do not track that, always merge with the current
2259 // client target acquire fence when it is available, even though
2260 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002261 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002262 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002263 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002264 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002265
David Sodman10a41ff2018-08-05 12:14:17 -07002266 if (compositionInfo.layer) {
2267 compositionInfo.layer->onLayerDisplayed(releaseFence);
2268 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 }
Chia-I Wu83806892017-11-16 10:50:20 -08002270
2271 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002273 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002275 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002277 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002278 }
2279 }
2280
Dominik Laskowski7e045462018-05-30 13:02:02 -07002281 if (displayId >= 0) {
2282 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002283 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285}
2286
Mathias Agopian87baae12012-07-31 12:38:26 -07002287void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288{
Mathias Agopian841cde52012-03-01 15:44:37 -08002289 ATRACE_CALL();
2290
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002291 // here we keep a copy of the drawing state (that is the state that's
2292 // going to be overwritten by handleTransactionLocked()) outside of
2293 // mStateLock so that the side-effects of the State assignment
2294 // don't happen with mStateLock held (which can cause deadlocks).
2295 State drawingState(mDrawingState);
2296
Mathias Agopianca4d3602011-05-19 15:38:14 -07002297 Mutex::Autolock _l(mStateLock);
2298 const nsecs_t now = systemTime();
2299 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300
Mathias Agopianca4d3602011-05-19 15:38:14 -07002301 // Here we're guaranteed that some transaction flags are set
2302 // so we can call handleTransactionLocked() unconditionally.
2303 // We call getTransactionFlags(), which will also clear the flags,
2304 // with mStateLock held to guarantee that mCurrentState won't change
2305 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002306
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002307 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002308 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002310
Mathias Agopianca4d3602011-05-19 15:38:14 -07002311 mLastTransactionTime = systemTime() - now;
2312 mDebugInTransaction = 0;
2313 invalidateHwcGeometry();
2314 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002315}
2316
Dominik Laskowski7e045462018-05-30 13:02:02 -07002317DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002319 // Figure out whether the event is for the primary display or an
2320 // external display by matching the Hwc display id against one for a
2321 // connected display. If we did not find a match, we then check what
2322 // displays are not already connected to determine the type. If we don't
2323 // have a connected primary display, we assume the new display is meant to
2324 // be the primary display, and then if we don't have an external display,
2325 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002326 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2327 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002328 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002329 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002330 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002331 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002332 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002333 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002334 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002335 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002336 return DisplayDevice::DISPLAY_EXTERNAL;
2337 }
2338
2339 return DisplayDevice::DISPLAY_ID_INVALID;
2340}
2341
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2343 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002344 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002345 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002346 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002347 continue;
2348 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002349
2350 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2351 ALOGE("External displays are not supported by the vr hardware composer.");
2352 continue;
2353 }
2354
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002355 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002356 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002357 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002358 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002359 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002360
2361 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002363 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002365 DisplayDeviceState info;
2366 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002367 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2368 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002369 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002371 mInterceptor->saveDisplayCreation(info);
2372 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002373 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002374 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002377 if (idx >= 0) {
2378 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002379 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002380 mCurrentState.displays.removeItemsAt(idx);
2381 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002383 }
2384
2385 processDisplayChangesLocked();
2386 }
2387
2388 mPendingHotplugEvents.clear();
2389}
2390
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002392 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002394 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002395 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002396 HdrCapabilities hdrCapabilities;
2397 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002398
Peiyong Lin13effd12018-07-24 17:01:47 -07002399 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002400 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002402 if (isWideColorMode(colorMode)) {
2403 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002405
Dominik Laskowski7e045462018-05-30 13:02:02 -07002406 std::vector<RenderIntent> renderIntents =
2407 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002408 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409 }
tangrobin6753a022018-08-10 10:58:54 +08002410 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411
tangrobin6753a022018-08-10 10:58:54 +08002412 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002413 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2414 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2415 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416
2417 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2418 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2419
2420 /*
2421 * Create our display's surface
2422 */
2423 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2424 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002425 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 renderSurface->setNativeWindow(nativeWindow.get());
2427 const int displayWidth = renderSurface->queryWidth();
2428 const int displayHeight = renderSurface->queryHeight();
2429
2430 // Make sure that composition can never be stalled by a virtual display
2431 // consumer that isn't processing buffers fast enough. We have to do this
2432 // in two places:
2433 // * Here, in case the display is composed entirely by HWC.
2434 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2435 // window's swap interval in eglMakeCurrent, so they'll override the
2436 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002437 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002438 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2439 }
2440
Chia-I Wua02871c2018-08-27 14:38:23 -07002441 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2442 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2443
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002445 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002448 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2449 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002450 displayHeight, displayInstallOrientation, hasWideColorGamut,
2451 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2452 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453
2454 if (maxFrameBufferAcquiredBuffers >= 3) {
2455 nativeWindowSurface->preallocateBuffers();
2456 }
2457
2458 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002459 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2460 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002462 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002465 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002466 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002468 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002469 display->setLayerStack(state.layerStack);
2470 display->setProjection(state.orientation, state.viewport, state.frame);
2471 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474}
2475
Lloyd Pique347200f2017-12-14 17:00:15 -08002476void SurfaceFlinger::processDisplayChangesLocked() {
2477 // here we take advantage of Vector's copy-on-write semantics to
2478 // improve performance by skipping the transaction entirely when
2479 // know that the lists are identical
2480 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2481 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2482 if (!curr.isIdenticalTo(draw)) {
2483 mVisibleRegionsDirty = true;
2484 const size_t cc = curr.size();
2485 size_t dc = draw.size();
2486
2487 // find the displays that were removed
2488 // (ie: in drawing state but not in current state)
2489 // also handle displays that changed
2490 // (ie: displays that are in both lists)
2491 for (size_t i = 0; i < dc;) {
2492 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2493 if (j < 0) {
2494 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002495 // Call makeCurrent() on the primary display so we can
2496 // be sure that nothing associated with this display
2497 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2499 defaultDisplay->makeCurrent();
2500 }
2501 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2502 display->disconnect(getHwComposer());
2503 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002504 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2505 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2506 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2507 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2508 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002509 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 } else {
2511 // this display is in both lists. see if something changed.
2512 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2515 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2516 if (state_binder != draw_binder) {
2517 // changing the surface is like destroying and
2518 // recreating the DisplayDevice, so we just remove it
2519 // from the drawing state, so that it get re-added
2520 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002521 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2522 display->disconnect(getHwComposer());
2523 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002524 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 mDrawingState.displays.removeItemsAt(i);
2526 dc--;
2527 // at this point we must loop to the next item
2528 continue;
2529 }
2530
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002531 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002532 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 }
2535 if ((state.orientation != draw[i].orientation) ||
2536 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 }
2539 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002540 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002541 }
2542 }
2543 }
2544 ++i;
2545 }
2546
2547 // find displays that were added
2548 // (ie: in current state but not in drawing state)
2549 for (size_t i = 0; i < cc; i++) {
2550 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2551 const DisplayDeviceState& state(curr[i]);
2552
2553 sp<DisplaySurface> dispSurface;
2554 sp<IGraphicBufferProducer> producer;
2555 sp<IGraphicBufferProducer> bqProducer;
2556 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002557 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002558
Dominik Laskowski7e045462018-05-30 13:02:02 -07002559 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002560 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002561 // Virtual displays without a surface are dormant:
2562 // they have external state (layer stack, projection,
2563 // etc.) but no internal state (i.e. a DisplayDevice).
2564 if (state.surface != nullptr) {
2565 // Allow VR composer to use virtual displays.
2566 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2567 int width = 0;
2568 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2569 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2570 int height = 0;
2571 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2572 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2573 int intFormat = 0;
2574 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2575 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002576 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002577
Dominik Laskowski7e045462018-05-30 13:02:02 -07002578 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2579 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 }
2581
2582 // TODO: Plumb requested format back up to consumer
2583
2584 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002585 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 bqProducer, bqConsumer,
2587 state.displayName);
2588
2589 dispSurface = vds;
2590 producer = vds;
2591 }
2592 } else {
2593 ALOGE_IF(state.surface != nullptr,
2594 "adding a supported display, but rendering "
2595 "surface is provided (%p), ignoring it",
2596 state.surface.get());
2597
Dominik Laskowski7e045462018-05-30 13:02:02 -07002598 displayId = state.type;
2599 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 producer = bqProducer;
2601 }
2602
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002603 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002606 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002608 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002609 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2610 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2611 true);
2612 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2613 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2614 true);
2615 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002616 }
2617 }
2618 }
2619 }
2620 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002621
2622 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002623}
2624
Mathias Agopian87baae12012-07-31 12:38:26 -07002625void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002626{
Dan Stoza7dde5992015-05-22 09:51:44 -07002627 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002628 mCurrentState.traverseInZOrder([](Layer* layer) {
2629 layer->notifyAvailableFrames();
2630 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 /*
2633 * Traversal of the children
2634 * (perform the transaction for each of them if needed)
2635 */
2636
Mathias Agopian3559b072012-08-15 13:46:03 -07002637 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002638 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002640 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641
2642 const uint32_t flags = layer->doTransaction(0);
2643 if (flags & Layer::eVisibleRegion)
2644 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002645 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 }
2647
2648 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002649 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 */
2651
Mathias Agopiane57f2922012-08-09 16:29:12 -07002652 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002654 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002657 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002658 // The transform hint might have changed for some layers
2659 // (either because a display has changed, or because a layer
2660 // as changed).
2661 //
2662 // Walk through all the layers in currentLayers,
2663 // and update their transform hint.
2664 //
2665 // If a layer is visible only on a single display, then that
2666 // display is used to calculate the hint, otherwise we use the
2667 // default display.
2668 //
2669 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2670 // the hint is set before we acquire a buffer from the surface texture.
2671 //
2672 // NOTE: layer transactions have taken place already, so we use their
2673 // drawing state. However, SurfaceFlinger's own transaction has not
2674 // happened yet, so we must use the current state layer list
2675 // (soon to become the drawing state list).
2676 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002677 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002678 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002679 bool first = true;
2680 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002681 // NOTE: we rely on the fact that layers are sorted by
2682 // layerStack first (so we don't have to traverse the list
2683 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002685 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002686 currentlayerStack = layerStack;
2687 // figure out if this layerstack is mirrored
2688 // (more than one display) if so, pick the default display,
2689 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 hintDisplay = nullptr;
2691 for (const auto& [token, display] : mDisplays) {
2692 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2693 if (hintDisplay) {
2694 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002698 }
2699 }
2700 }
2701 }
Chet Haase91d25932013-04-11 15:24:55 -07002702
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002703 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002704 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2705 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002706
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002707 // could be null when this layer is using a layerStack
2708 // that is not visible on any display. Also can occur at
2709 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002711 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002712
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002714 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 if (hintDisplay) {
2716 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002717 }
Robert Carr2047fae2016-11-28 14:09:09 -08002718
2719 first = false;
2720 });
Mathias Agopian84300952012-11-21 16:02:13 -08002721 }
2722
2723
Mathias Agopian3559b072012-08-15 13:46:03 -07002724 /*
2725 * Perform our own transaction if needed
2726 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727
2728 if (mLayersAdded) {
2729 mLayersAdded = false;
2730 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002731 mVisibleRegionsDirty = true;
2732 }
2733
2734 // some layers might have been removed, so
2735 // we need to update the regions they're exposing.
2736 if (mLayersRemoved) {
2737 mLayersRemoved = false;
2738 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002739 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 // this layer is not visible anymore
2742 // TODO: we could traverse the tree from front to back and
2743 // compute the actual visible region
2744 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745 Region visibleReg;
2746 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002747 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002748 }
Robert Carr2047fae2016-11-28 14:09:09 -08002749 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 }
2751
2752 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002753
2754 updateCursorAsync();
2755}
2756
2757void SurfaceFlinger::updateCursorAsync()
2758{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002759 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002760 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002761 continue;
2762 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2765 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002766 }
2767 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002768}
2769
2770void SurfaceFlinger::commitTransaction()
2771{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002772 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002773 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 for (const auto& l : mLayersPendingRemoval) {
2775 recordBufferingStats(l->getName().string(),
2776 l->getOccupancyHistory(true));
2777 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002778 }
2779 mLayersPendingRemoval.clear();
2780 }
2781
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002782 // If this transaction is part of a window animation then the next frame
2783 // we composite should be considered an animation as well.
2784 mAnimCompositionPending = mAnimTransactionPending;
2785
Mathias Agopian4fec8732012-06-29 14:12:52 -07002786 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002787 // clear the "changed" flags in current state
2788 mCurrentState.colorMatrixChanged = false;
2789
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 mDrawingState.traverseInZOrder([](Layer* layer) {
2791 layer->commitChildList();
2792 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002793 mTransactionPending = false;
2794 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796}
2797
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2799 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002800 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 Region aboveOpaqueLayers;
2804 Region aboveCoveredLayers;
2805 Region dirty;
2806
Mathias Agopian87baae12012-07-31 12:38:26 -07002807 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002811 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
Jesse Hall01e29052013-02-19 16:13:35 -08002813 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002814 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002815 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002817
Mathias Agopianab028732010-03-16 16:41:46 -07002818 /*
2819 * opaqueRegion: area of a surface that is fully opaque.
2820 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002822
2823 /*
2824 * visibleRegion: area of a surface that is visible on screen
2825 * and not fully transparent. This is essentially the layer's
2826 * footprint minus the opaque regions above it.
2827 * Areas covered by a translucent surface are considered visible.
2828 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002830
2831 /*
2832 * coveredRegion: area of a surface that is covered by all
2833 * visible regions above it (which includes the translucent areas).
2834 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002836
Jesse Halla8026d22012-09-25 13:25:04 -07002837 /*
2838 * transparentRegion: area of a surface that is hinted to be completely
2839 * transparent. This is only used to tell when the layer has no visible
2840 * non-transparent regions and can be removed from the layer list. It
2841 * does not affect the visibleRegion of this layer or any layers
2842 * beneath it. The hint may not be correct if apps don't respect the
2843 * SurfaceView restrictions (which, sadly, some don't).
2844 */
2845 Region transparentRegion;
2846
Mathias Agopianab028732010-03-16 16:41:46 -07002847
2848 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002849 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002850 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002853 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002854 if (!visibleRegion.isEmpty()) {
2855 // Remove the transparent area from the visible region
2856 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002857 if (tr.preserveRects()) {
2858 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002859 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002861 // transformation too complex, can't do the
2862 // transparent region optimization.
2863 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 }
Mathias Agopianab028732010-03-16 16:41:46 -07002865 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
Mathias Agopianab028732010-03-16 16:41:46 -07002867 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002869 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002870 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002871 // the opaque region is the layer's footprint
2872 opaqueRegion = visibleRegion;
2873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
2875 }
2876
Robert Carre5f4f692018-01-12 13:12:28 -08002877 if (visibleRegion.isEmpty()) {
2878 layer->clearVisibilityRegions();
2879 return;
2880 }
2881
Mathias Agopianab028732010-03-16 16:41:46 -07002882 // Clip the covered region to the visible region
2883 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2884
2885 // Update aboveCoveredLayers for next (lower) layer
2886 aboveCoveredLayers.orSelf(visibleRegion);
2887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 // subtract the opaque region covered by the layers above us
2889 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
2891 // compute this layer's dirty region
2892 if (layer->contentDirty) {
2893 // we need to invalidate the whole region
2894 dirty = visibleRegion;
2895 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 layer->contentDirty = false;
2898 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002899 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002900 * the exposed region consists of two components:
2901 * 1) what's VISIBLE now and was COVERED before
2902 * 2) what's EXPOSED now less what was EXPOSED before
2903 *
2904 * note that (1) is conservative, we start with the whole
2905 * visible region but only keep what used to be covered by
2906 * something -- which mean it may have been exposed.
2907 *
2908 * (2) handles areas that were not covered by anything but got
2909 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002910 */
Mathias Agopianab028732010-03-16 16:41:46 -07002911 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912 const Region oldVisibleRegion = layer->visibleRegion;
2913 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002914 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2915 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 }
2917 dirty.subtractSelf(aboveOpaqueLayers);
2918
2919 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002920 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921
Mathias Agopianab028732010-03-16 16:41:46 -07002922 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002924
Jesse Halla8026d22012-09-25 13:25:04 -07002925 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 layer->setVisibleRegion(visibleRegion);
2927 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002928 layer->setVisibleNonTransparentRegion(
2929 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002930 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931
Mathias Agopian87baae12012-07-31 12:38:26 -07002932 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933}
2934
Chia-I Wuab0c3192017-08-01 11:29:00 -07002935void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2938 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002939 }
2940 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002941}
2942
Dan Stoza6b9454d2014-11-07 16:00:59 -08002943bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 ALOGV("handlePageFlip");
2946
Brian Andersond6927fb2016-07-23 23:37:30 -07002947 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948
Mathias Agopian4fec8732012-06-29 14:12:52 -07002949 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002951 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002952
2953 // Store the set of layers that need updates. This set must not change as
2954 // buffers are being latched, as this could result in a deadlock.
2955 // Example: Two producers share the same command stream and:
2956 // 1.) Layer 0 is latched
2957 // 2.) Layer 0 gets a new frame
2958 // 2.) Layer 1 gets a new frame
2959 // 3.) Layer 1 is latched.
2960 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2961 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002963 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002964 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002965 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002966 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002967 } else {
2968 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002969 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002970 } else {
2971 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002972 }
Robert Carr2047fae2016-11-28 14:09:09 -08002973 });
2974
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002976 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002977 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002978 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002979 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002980 newDataLatched = true;
2981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002983
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002984 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002985
2986 // If we will need to wake up at some time in the future to deal with a
2987 // queued frame that shouldn't be displayed during this vsync period, wake
2988 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002989 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990 signalLayerUpdate();
2991 }
2992
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002993 // enter boot animation on first buffer latch
2994 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2995 ALOGI("Enter boot animation");
2996 mBootStage = BootStage::BOOTANIMATION;
2997 }
2998
Dan Stoza6b9454d2014-11-07 16:00:59 -08002999 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003000 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001}
3002
Mathias Agopianad456f92011-01-13 17:53:01 -08003003void SurfaceFlinger::invalidateHwcGeometry()
3004{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003006}
3007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003008void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3009 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003010 // We only need to actually compose the display if:
3011 // 1) It is being handled by hardware composer, which may need this to
3012 // keep its virtual display state machine in sync, or
3013 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003014 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003015 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003017 return;
3018 }
3019
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003022
3023 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025}
3026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 const Region bounds(display->bounds());
3031 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003032 const auto displayId = display->getId();
3033 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003034 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003035
Chia-I Wu8e50e692018-05-04 10:12:37 -07003036 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003037 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003038
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 if (hasClientComposition) {
3040 ALOGV("hasClientComposition");
3041
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003042 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 if (display->hasWideColorGamut()) {
3044 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003045 }
3046 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003047 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003049
Dominik Laskowski7e045462018-05-30 13:02:02 -07003050 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003051 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3052 HWC2::Capability::SkipClientColorTransform);
3053
Chia-I Wud49d6692018-06-27 07:17:41 +08003054 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003055 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3056 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003057 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003058 }
3059
Chia-I Wud49d6692018-06-27 07:17:41 +08003060 // The current enhanced saturation matrix is designed to enhance Display P3,
3061 // thus we only apply this matrix when the render intent is not colorimetric
3062 // and the output color space is Display P3.
3063 needsEnhancedColorMatrix =
3064 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3065 outputDataspace == Dataspace::DISPLAY_P3);
3066 if (needsEnhancedColorMatrix) {
3067 colorMatrix *= mEnhancedSaturationMatrix;
3068 }
3069
3070 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003072 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003073 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003074 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003075 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003076
3077 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003078 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3079 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3080 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003081 }
3082 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003083 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003084
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003085 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003086 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003087 // when using overlays, we assume a fully transparent framebuffer
3088 // NOTE: we could reduce how much we need to clear, for instance
3089 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003090 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003091 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003092 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003093 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003094 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003095 // we're left with the letterbox region
3096 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003097 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003098
3099 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003100 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003101
Mathias Agopianb9494d52012-04-18 02:28:45 -07003102 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003103 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003104 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003105 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003106 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003107 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003108
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003109 const Rect& bounds = display->getBounds();
3110 const Rect& scissor = display->getScissor();
3111 if (scissor != bounds) {
3112 // scissor doesn't match the screen's dimensions, so we
3113 // need to clear everything outside of it and enable
3114 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003115
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003116 // enable scissor for this frame
3117 const uint32_t height = display->getHeight();
3118 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3119 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003120 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003121 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003122
Mathias Agopian85d751c2012-08-29 16:59:24 -07003123 /*
3124 * and then, render the layers targeted at the framebuffer
3125 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003126
Dan Stoza9e56aa02015-11-02 13:00:03 -08003127 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003128 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003129 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003130 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3131 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003133 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3134 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003136 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003137 case HWC2::Composition::Cursor:
3138 case HWC2::Composition::Device:
3139 case HWC2::Composition::Sideband:
3140 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003141 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3142 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3143 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3144 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003145 // never clear the very first layer since we're
3146 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003147 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003148 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003149 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003150 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003151 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003152 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003153 break;
3154 }
3155 default:
3156 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003157 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003158 } else {
3159 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003160 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003161 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003162 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003163
Chia-I Wud49d6692018-06-27 07:17:41 +08003164 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003165 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003166 }
3167
Mathias Agopianf45c5102012-10-24 16:29:17 -07003168 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003169 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003170 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171}
3172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003173void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3174 const Region& region) const {
3175 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003176 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003177 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178}
3179
Dan Stoza7d89d062015-04-30 13:29:25 -07003180status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003181 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003182 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 const sp<Layer>& lbc,
3184 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003185{
Dan Stoza7d89d062015-04-30 13:29:25 -07003186 // add this layer to the current state list
3187 {
3188 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003190 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3191 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 return NO_MEMORY;
3193 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 if (parent == nullptr) {
3195 mCurrentState.layersSortedByZ.add(lbc);
3196 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003197 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003198 ALOGE("addClientLayer called with a removed parent");
3199 return NAME_NOT_FOUND;
3200 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 parent->addChild(lbc);
3202 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003203
Yiwei Zhang243b3782018-05-15 17:40:04 -07003204 if (gbc != nullptr) {
3205 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3206 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3207 mMaxGraphicBufferProducerListSize,
3208 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3209 mGraphicBufferProducerList.size(),
3210 mMaxGraphicBufferProducerListSize, mNumLayers);
3211 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003212 mLayersAdded = true;
3213 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003214 }
3215
Mathias Agopian96f08192010-06-02 23:28:45 -07003216 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003217 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003218
Dan Stoza7d89d062015-04-30 13:29:25 -07003219 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003220}
3221
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003222status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003223 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003224 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3225}
Robert Carr7f9b8992017-03-10 11:08:39 -08003226
chaviwca27f252018-02-06 16:46:39 -08003227status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3228 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003229 if (layer->isPendingRemoval()) {
3230 return NO_ERROR;
3231 }
3232
Robert Carr1f0a16a2016-10-24 16:27:39 -07003233 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003234 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003235 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003236 if (topLevelOnly) {
3237 return NO_ERROR;
3238 }
3239
Chia-I Wu98f1c102017-05-30 14:54:08 -07003240 sp<Layer> ancestor = p;
3241 while (ancestor->getParent() != nullptr) {
3242 ancestor = ancestor->getParent();
3243 }
3244 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3245 ALOGE("removeLayer called with a layer whose parent has been removed");
3246 return NAME_NOT_FOUND;
3247 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003248
3249 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003250 } else {
3251 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003252 }
3253
Robert Carr136e2f62017-02-08 17:54:29 -08003254 // As a matter of normal operation, the LayerCleaner will produce a second
3255 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3256 // so we will succeed in promoting it, but it's already been removed
3257 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3258 // otherwise something has gone wrong and we are leaking the layer.
3259 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003260 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3261 layer->getName().string(),
3262 (p != nullptr) ? p->getName().string() : "no-parent");
3263 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003264 } else if (index < 0) {
3265 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003266 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003267
Chia-I Wuc6657022017-08-15 11:18:17 -07003268 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003269 mLayersPendingRemoval.add(layer);
3270 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003271 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003272 setTransactionFlags(eTransactionNeeded);
3273 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274}
3275
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003276uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003277 return android_atomic_release_load(&mTransactionFlags);
3278}
3279
Mathias Agopian3f844832013-08-07 21:24:32 -07003280uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3282}
3283
Mathias Agopian3f844832013-08-07 21:24:32 -07003284uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003285 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3286}
3287
3288uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3289 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003291 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003293 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294 }
3295 return old;
3296}
3297
chaviwca27f252018-02-06 16:46:39 -08003298bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3299 for (const ComposerState& state : states) {
3300 // Here we need to check that the interface we're given is indeed
3301 // one of our own. A malicious client could give us a nullptr
3302 // IInterface, or one of its own or even one of our own but a
3303 // different type. All these situations would cause us to crash.
3304 if (state.client == nullptr) {
3305 return true;
3306 }
3307
3308 sp<IBinder> binder = IInterface::asBinder(state.client);
3309 if (binder == nullptr) {
3310 return true;
3311 }
3312
3313 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3314 return true;
3315 }
3316 }
3317 return false;
3318}
3319
Mathias Agopian8b33f032012-07-24 20:43:54 -07003320void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003321 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003322 const Vector<DisplayState>& displays,
3323 uint32_t flags)
3324{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003325 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003326 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003327 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003328
chaviwca27f252018-02-06 16:46:39 -08003329 if (containsAnyInvalidClientState(states)) {
3330 return;
3331 }
3332
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003333 if (flags & eAnimation) {
3334 // For window updates that are part of an animation we must wait for
3335 // previous animation "frames" to be handled.
3336 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003337 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 if (CC_UNLIKELY(err != NO_ERROR)) {
3339 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003340 // caller after a few seconds.
3341 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3342 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 mAnimTransactionPending = false;
3344 break;
3345 }
3346 }
3347 }
3348
chaviwca27f252018-02-06 16:46:39 -08003349 for (const DisplayState& display : displays) {
3350 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003351 }
3352
chaviwca27f252018-02-06 16:46:39 -08003353 for (const ComposerState& state : states) {
3354 transactionFlags |= setClientStateLocked(state);
3355 }
3356
3357 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3358 // as destroyed should only occur after setting all other states. This is to allow for a
3359 // child re-parent to happen before marking its original parent as destroyed (which would
3360 // then mark the child as destroyed).
3361 for (const ComposerState& state : states) {
3362 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003363 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003364
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003365 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3366 // anyway. This can be used as a flush mechanism for previous async transactions.
3367 // Empty animation transaction can be used to simulate back-pressure, so also force a
3368 // transaction for empty animation transactions.
3369 if (transactionFlags == 0 &&
3370 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003371 transactionFlags = eTransactionNeeded;
3372 }
3373
Mathias Agopian386aa982011-11-07 21:58:03 -08003374 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003375 if (mInterceptor->isEnabled()) {
3376 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003377 }
Irvel468051e2016-06-13 16:44:44 -07003378
Mathias Agopian386aa982011-11-07 21:58:03 -08003379 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003380 const auto start = (flags & eEarlyWakeup)
3381 ? VSyncModulator::TransactionStart::EARLY
3382 : VSyncModulator::TransactionStart::NORMAL;
3383 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003384
3385 // if this is a synchronous transaction, wait for it to take effect
3386 // before returning.
3387 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003388 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003389 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003390 if (flags & eAnimation) {
3391 mAnimTransactionPending = true;
3392 }
3393 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003394 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3395 if (CC_UNLIKELY(err != NO_ERROR)) {
3396 // just in case something goes wrong in SF, return to the
3397 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003398 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3399 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003400 break;
3401 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403 }
3404}
3405
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003406uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3407 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3408 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003409
Mathias Agopiane57f2922012-08-09 16:29:12 -07003410 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003411 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3412
3413 const uint32_t what = s.what;
3414 if (what & DisplayState::eSurfaceChanged) {
3415 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3416 state.surface = s.surface;
3417 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003418 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003420 if (what & DisplayState::eLayerStackChanged) {
3421 if (state.layerStack != s.layerStack) {
3422 state.layerStack = s.layerStack;
3423 flags |= eDisplayTransactionNeeded;
3424 }
3425 }
3426 if (what & DisplayState::eDisplayProjectionChanged) {
3427 if (state.orientation != s.orientation) {
3428 state.orientation = s.orientation;
3429 flags |= eDisplayTransactionNeeded;
3430 }
3431 if (state.frame != s.frame) {
3432 state.frame = s.frame;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 if (state.viewport != s.viewport) {
3436 state.viewport = s.viewport;
3437 flags |= eDisplayTransactionNeeded;
3438 }
3439 }
3440 if (what & DisplayState::eDisplaySizeChanged) {
3441 if (state.width != s.width) {
3442 state.width = s.width;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 if (state.height != s.height) {
3446 state.height = s.height;
3447 flags |= eDisplayTransactionNeeded;
3448 }
3449 }
3450
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 return flags;
3452}
3453
Robert Carrd4ae7f32018-06-07 16:10:57 -07003454bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3455 IPCThreadState* ipc = IPCThreadState::self();
3456 const int pid = ipc->getCallingPid();
3457 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003458 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003459 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003460 return false;
3461 }
3462 return true;
3463}
3464
chaviwca27f252018-02-06 16:46:39 -08003465uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3466 const layer_state_t& s = composerState.state;
3467 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3468
Mathias Agopian13127d82013-03-05 17:47:11 -08003469 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003470 if (layer == nullptr) {
3471 return 0;
3472 }
3473
3474 if (layer->isPendingRemoval()) {
3475 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3476 return 0;
3477 }
3478
3479 uint32_t flags = 0;
3480
3481 const uint32_t what = s.what;
3482 bool geometryAppliesWithResize =
3483 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003484
3485 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3486 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003487 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003488 layer->pushPendingState();
3489 }
3490
chaviw8b3871a2017-11-01 17:41:01 -07003491 if (what & layer_state_t::ePositionChanged) {
3492 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3493 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 }
chaviw8b3871a2017-11-01 17:41:01 -07003495 }
3496 if (what & layer_state_t::eLayerChanged) {
3497 // NOTE: index needs to be calculated before we update the state
3498 const auto& p = layer->getParent();
3499 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003500 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003501 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003502 mCurrentState.layersSortedByZ.removeAt(idx);
3503 mCurrentState.layersSortedByZ.add(layer);
3504 // we need traversal (state changed)
3505 // AND transaction (list changed)
3506 flags |= eTransactionNeeded|eTraversalNeeded;
3507 }
chaviw8b3871a2017-11-01 17:41:01 -07003508 } else {
3509 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003510 flags |= eTransactionNeeded|eTraversalNeeded;
3511 }
3512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 }
3514 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003515 // NOTE: index needs to be calculated before we update the state
3516 const auto& p = layer->getParent();
3517 if (p == nullptr) {
3518 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3519 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3520 mCurrentState.layersSortedByZ.removeAt(idx);
3521 mCurrentState.layersSortedByZ.add(layer);
3522 // we need traversal (state changed)
3523 // AND transaction (list changed)
3524 flags |= eTransactionNeeded|eTraversalNeeded;
3525 }
3526 } else {
3527 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3528 flags |= eTransactionNeeded|eTraversalNeeded;
3529 }
chaviw8b3871a2017-11-01 17:41:01 -07003530 }
3531 }
3532 if (what & layer_state_t::eSizeChanged) {
3533 if (layer->setSize(s.w, s.h)) {
3534 flags |= eTraversalNeeded;
3535 }
3536 }
3537 if (what & layer_state_t::eAlphaChanged) {
3538 if (layer->setAlpha(s.alpha))
3539 flags |= eTraversalNeeded;
3540 }
3541 if (what & layer_state_t::eColorChanged) {
3542 if (layer->setColor(s.color))
3543 flags |= eTraversalNeeded;
3544 }
3545 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003546 // TODO: b/109894387
3547 //
3548 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3549 // rotation. To see the problem observe that if we have a square parent, and a child
3550 // of the same size, then we rotate the child 45 degrees around it's center, the child
3551 // must now be cropped to a non rectangular 8 sided region.
3552 //
3553 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3554 // private API, and the WindowManager only uses rotation in one case, which is on a top
3555 // level layer in which cropping is not an issue.
3556 //
3557 // However given that abuse of rotation matrices could lead to surfaces extending outside
3558 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3559 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3560 // transformations.
3561 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003562 flags |= eTraversalNeeded;
3563 }
3564 if (what & layer_state_t::eTransparentRegionChanged) {
3565 if (layer->setTransparentRegionHint(s.transparentRegion))
3566 flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eFlagsChanged) {
3569 if (layer->setFlags(s.flags, s.mask))
3570 flags |= eTraversalNeeded;
3571 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003572 if (what & layer_state_t::eCropChanged_legacy) {
3573 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003574 flags |= eTraversalNeeded;
3575 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003576 if (what & layer_state_t::eFinalCropChanged_legacy) {
3577 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003578 flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eLayerStackChanged) {
3581 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3582 // We only allow setting layer stacks for top level layers,
3583 // everything else inherits layer stack from its parent.
3584 if (layer->hasParent()) {
3585 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3586 layer->getName().string());
3587 } else if (idx < 0) {
3588 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3589 "that also does not appear in the top level layer list. Something"
3590 " has gone wrong.", layer->getName().string());
3591 } else if (layer->setLayerStack(s.layerStack)) {
3592 mCurrentState.layersSortedByZ.removeAt(idx);
3593 mCurrentState.layersSortedByZ.add(layer);
3594 // we need traversal (state changed)
3595 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003596 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003597 }
3598 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003599 if (what & layer_state_t::eDeferTransaction_legacy) {
3600 if (s.barrierHandle_legacy != nullptr) {
3601 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3602 } else if (s.barrierGbp_legacy != nullptr) {
3603 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003604 if (authenticateSurfaceTextureLocked(gbp)) {
3605 const auto& otherLayer =
3606 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003607 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003608 } else {
3609 ALOGE("Attempt to defer transaction to to an"
3610 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003611 }
3612 }
chaviw8b3871a2017-11-01 17:41:01 -07003613 // We don't trigger a traversal here because if no other state is
3614 // changed, we don't want this to cause any more work
3615 }
3616 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003617 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003619 if (!hadParent) {
3620 mCurrentState.layersSortedByZ.remove(layer);
3621 }
chaviw8b3871a2017-11-01 17:41:01 -07003622 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 }
3625 if (what & layer_state_t::eReparentChildren) {
3626 if (layer->reparentChildren(s.reparentHandle)) {
3627 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003628 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (what & layer_state_t::eDetachChildren) {
3631 layer->detachChildren();
3632 }
3633 if (what & layer_state_t::eOverrideScalingModeChanged) {
3634 layer->setOverrideScalingMode(s.overrideScalingMode);
3635 // We don't trigger a traversal here because if no other state is
3636 // changed, we don't want this to cause any more work
3637 }
Marissa Wall61c58622018-07-18 10:12:20 -07003638 if (what & layer_state_t::eTransformChanged) {
3639 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3642 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3643 flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eCropChanged) {
3646 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3647 }
3648 if (what & layer_state_t::eBufferChanged) {
3649 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3650 }
3651 if (what & layer_state_t::eAcquireFenceChanged) {
3652 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3653 }
3654 if (what & layer_state_t::eDataspaceChanged) {
3655 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eHdrMetadataChanged) {
3658 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3661 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3662 }
3663 if (what & layer_state_t::eApiChanged) {
3664 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3665 }
3666 if (what & layer_state_t::eSidebandStreamChanged) {
3667 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3668 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003669 return flags;
3670}
3671
chaviwca27f252018-02-06 16:46:39 -08003672void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3673 const layer_state_t& state = composerState.state;
3674 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3675
3676 sp<Layer> layer(client->getLayerUser(state.surface));
3677 if (layer == nullptr) {
3678 return;
3679 }
3680
3681 if (layer->isPendingRemoval()) {
3682 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3683 return;
3684 }
3685
3686 if (state.what & layer_state_t::eDestroySurface) {
3687 removeLayerLocked(mStateLock, layer);
3688 }
3689}
3690
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003692 const String8& name,
3693 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003695 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003696 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003698 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003699 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003700 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003702 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003703
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003704 status_t result = NO_ERROR;
3705
3706 sp<Layer> layer;
3707
Cody Northropbc755282017-03-31 12:00:08 -06003708 String8 uniqueName = getUniqueLayerName(name);
3709
Mathias Agopian3165cc22012-08-08 19:42:09 -07003710 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003711 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003712 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3713 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003716 case ISurfaceComposerClient::eFXSurfaceBufferState:
3717 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3718 break;
chaviw13fdc492017-06-27 12:40:18 -07003719 case ISurfaceComposerClient::eFXSurfaceColor:
3720 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003721 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003722 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003723 break;
3724 default:
3725 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726 break;
3727 }
3728
Dan Stoza7d89d062015-04-30 13:29:25 -07003729 if (result != NO_ERROR) {
3730 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003732
Chia-I Wuab0c3192017-08-01 11:29:00 -07003733 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3734 // TODO b/64227542
3735 if (windowType == 441731) {
3736 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3737 layer->setPrimaryDisplayOnly();
3738 }
3739
Albert Chaulk479c60c2017-01-27 14:21:34 -05003740 layer->setInfo(windowType, ownerUid);
3741
Robert Carr1f0a16a2016-10-24 16:27:39 -07003742 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003743 if (result != NO_ERROR) {
3744 return result;
3745 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003746 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003747
3748 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003749 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003750}
3751
Cody Northropbc755282017-03-31 12:00:08 -06003752String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3753{
3754 bool matchFound = true;
3755 uint32_t dupeCounter = 0;
3756
3757 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3758 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3759
Dan Stoza436ccf32018-06-21 12:10:12 -07003760 // Grab the state lock since we're accessing mCurrentState
3761 Mutex::Autolock lock(mStateLock);
3762
Cody Northropbc755282017-03-31 12:00:08 -06003763 // Loop over layers until we're sure there is no matching name
3764 while (matchFound) {
3765 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003766 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003767 if (layer->getName() == uniqueName) {
3768 matchFound = true;
3769 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3770 }
3771 });
3772 }
3773
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003774 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3775 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003776
3777 return uniqueName;
3778}
3779
Marissa Wallfd668622018-05-10 10:21:13 -07003780status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3781 uint32_t w, uint32_t h, uint32_t flags,
3782 PixelFormat& format, sp<IBinder>* handle,
3783 sp<IGraphicBufferProducer>* gbp,
3784 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003786 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787 case PIXEL_FORMAT_TRANSPARENT:
3788 case PIXEL_FORMAT_TRANSLUCENT:
3789 format = PIXEL_FORMAT_RGBA_8888;
3790 break;
3791 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003792 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793 break;
3794 }
3795
Marissa Wallfd668622018-05-10 10:21:13 -07003796 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3797 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003799 *handle = layer->getHandle();
3800 *gbp = layer->getProducer();
3801 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003803
Marissa Wallfd668622018-05-10 10:21:13 -07003804 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806}
3807
Marissa Wall61c58622018-07-18 10:12:20 -07003808status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3809 uint32_t w, uint32_t h, uint32_t flags,
3810 sp<IBinder>* handle, sp<Layer>* outLayer) {
3811 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3812 *handle = layer->getHandle();
3813 *outLayer = layer;
3814
3815 return NO_ERROR;
3816}
3817
chaviw13fdc492017-06-27 12:40:18 -07003818status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003820 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821{
chaviw13fdc492017-06-27 12:40:18 -07003822 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003823 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003824 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003825}
3826
Mathias Agopianac9fa422013-02-11 16:40:36 -08003827status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828{
Robert Carr9524cb32017-02-13 11:32:32 -08003829 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003830 status_t err = NO_ERROR;
3831 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003832 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003833 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003834 err = removeLayer(l);
3835 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3836 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003837 }
3838 return err;
3839}
3840
Mathias Agopian13127d82013-03-05 17:47:11 -08003841status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003842{
Mathias Agopian67106042013-03-14 19:18:13 -07003843 // called by ~LayerCleaner() when all references to the IBinder (handle)
3844 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003845 sp<Layer> l = layer.promote();
3846 if (l == nullptr) {
3847 // The layer has already been removed, carry on
3848 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003849 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003850 // If we have a parent, then we can continue to live as long as it does.
3851 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852}
3853
Mathias Agopianb60314a2012-04-10 22:09:54 -07003854// ---------------------------------------------------------------------------
3855
Andy McFadden13a082e2012-08-24 10:16:42 -07003856void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003857 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3858 if (!displayToken) return;
3859
Jesse Hall01e29052013-02-19 16:13:35 -08003860 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003861 Vector<ComposerState> state;
3862 Vector<DisplayState> displays;
3863 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003864 d.what = DisplayState::eDisplayProjectionChanged |
3865 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003866 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003867 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003868 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003869 d.frame.makeInvalid();
3870 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003871 d.width = 0;
3872 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003873 displays.add(d);
3874 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003875
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003876 const auto display = getDisplayDevice(displayToken);
3877 if (!display) return;
3878
3879 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3880
3881 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003882 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003883 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003884
Brian Andersond0010582017-03-07 13:20:31 -08003885 // Use phase of 0 since phase is not known.
3886 // Use latency of 0, which will snap to the ideal latency.
3887 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003888}
3889
3890void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003891 // Async since we may be called from the main thread.
3892 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003893}
3894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3896 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003897 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003898 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003900 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003902 return;
3903 }
3904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003906 ALOGW("Trying to set power mode for virtual display");
3907 return;
3908 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003909
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003910 display->setPowerMode(mode);
3911
Lloyd Pique4dccc412018-01-22 17:21:36 -08003912 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003913 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003914 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003915 if (idx < 0) {
3916 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3917 return;
3918 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003919 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003920 }
3921
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003922 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003923 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003924 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003926 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003927 // FIXME: eventthread only knows about the main display right now
3928 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003929 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003932 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003933 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003934 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003935
3936 struct sched_param param = {0};
3937 param.sched_priority = 1;
3938 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3939 ALOGW("Couldn't set SCHED_FIFO on display on");
3940 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003941 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003942 // Turn off the display
3943 struct sched_param param = {0};
3944 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3945 ALOGW("Couldn't set SCHED_OTHER on display off");
3946 }
3947
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003948 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003949 disableHardwareVsync(true); // also cancels any in-progress resync
3950
Mathias Agopiancde87a32012-09-13 14:09:01 -07003951 // FIXME: eventthread only knows about the main display right now
3952 mEventThread->onScreenReleased();
3953 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003955 getHwComposer().setPowerMode(type, mode);
3956 mVisibleRegionsDirty = true;
3957 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003958 } else if (mode == HWC_POWER_MODE_DOZE ||
3959 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003960 // Update display while dozing
3961 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003962 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003963 // FIXME: eventthread only knows about the main display right now
3964 mEventThread->onScreenAcquired();
3965 resyncToHardwareVsync(true);
3966 }
3967 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3968 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003969 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003970 disableHardwareVsync(true); // also cancels any in-progress resync
3971 // FIXME: eventthread only knows about the main display right now
3972 mEventThread->onScreenReleased();
3973 }
3974 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003975 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003976 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003977 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003978 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979
3980 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003981}
3982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003983void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003984 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 const auto display = getDisplayDevice(displayToken);
3986 if (!display) {
3987 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3988 displayToken.get());
3989 } else if (display->isVirtual()) {
3990 ALOGW("Attempt to set power mode %d for virtual display", mode);
3991 } else {
3992 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003993 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003995}
3996
3997// ---------------------------------------------------------------------------
3998
Lloyd Pique755e3192018-01-31 16:46:15 -08003999status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4000 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004002
Mathias Agopianbd115332013-04-18 16:41:04 -07004003 IPCThreadState* ipc = IPCThreadState::self();
4004 const int pid = ipc->getCallingPid();
4005 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004006
Mathias Agopianbd115332013-04-18 16:41:04 -07004007 if ((uid != AID_SHELL) &&
4008 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004009 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004010 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004012 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004013 // (this would indicate SF is stuck, but we want to be able to
4014 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004015 status_t err = mStateLock.timedLock(s2ns(1));
4016 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004017 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004018 result.appendFormat(
4019 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4020 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004021 }
4022
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023 bool dumpAll = true;
4024 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004026
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028 if ((index < numArgs) &&
4029 (args[index] == String16("--list"))) {
4030 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004032 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033 }
4034
4035 if ((index < numArgs) &&
4036 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004038 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004039 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004041
4042 if ((index < numArgs) &&
4043 (args[index] == String16("--latency-clear"))) {
4044 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004045 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004046 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004048
4049 if ((index < numArgs) &&
4050 (args[index] == String16("--dispsync"))) {
4051 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004052 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004053 dumpAll = false;
4054 }
Dan Stozab90cf072015-03-05 11:05:59 -08004055
4056 if ((index < numArgs) &&
4057 (args[index] == String16("--static-screen"))) {
4058 index++;
4059 dumpStaticScreenStats(result);
4060 dumpAll = false;
4061 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004062
4063 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004064 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004065 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004066 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004067 dumpAll = false;
4068 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004069
4070 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4071 index++;
4072 dumpWideColorInfo(result);
4073 dumpAll = false;
4074 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004075
4076 if ((index < numArgs) &&
4077 (args[index] == String16("--enable-layer-stats"))) {
4078 index++;
4079 mLayerStats.enable();
4080 dumpAll = false;
4081 }
4082
4083 if ((index < numArgs) &&
4084 (args[index] == String16("--disable-layer-stats"))) {
4085 index++;
4086 mLayerStats.disable();
4087 dumpAll = false;
4088 }
4089
4090 if ((index < numArgs) &&
4091 (args[index] == String16("--clear-layer-stats"))) {
4092 index++;
4093 mLayerStats.clear();
4094 dumpAll = false;
4095 }
4096
4097 if ((index < numArgs) &&
4098 (args[index] == String16("--dump-layer-stats"))) {
4099 index++;
4100 mLayerStats.dump(result);
4101 dumpAll = false;
4102 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004103
4104 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004105 (args[index] == String16("--frame-composition"))) {
4106 index++;
4107 dumpFrameCompositionInfo(result);
4108 dumpAll = false;
4109 }
4110
4111 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004112 (args[index] == String16("--display-identification"))) {
4113 index++;
4114 dumpDisplayIdentificationData(result);
4115 dumpAll = false;
4116 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004117
4118 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4119 index++;
4120 mTimeStats.parseArgs(asProto, args, index, result);
4121 dumpAll = false;
4122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004124
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004125 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004126 if (asProto) {
4127 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4128 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4129 } else {
4130 dumpAllLocked(args, index, result);
4131 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004132 }
4133
Mathias Agopian9795c422009-08-26 16:36:26 -07004134 if (locked) {
4135 mStateLock.unlock();
4136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 }
4138 write(fd, result.string(), result.size());
4139 return NO_ERROR;
4140}
4141
Dan Stozac7014012014-02-14 15:03:43 -08004142void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4143 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144{
Robert Carr2047fae2016-11-28 14:09:09 -08004145 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004146 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004147 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004148}
4149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004151 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004152{
4153 String8 name;
4154 if (index < args.size()) {
4155 name = String8(args[index]);
4156 index++;
4157 }
4158
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004159 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4160 getHwComposer().isConnected(displayId)) {
4161 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4162 const nsecs_t period = activeConfig->getVsyncPeriod();
4163 result.appendFormat("%" PRId64 "\n", period);
4164 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004165
4166 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004167 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004168 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004169 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004170 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004171 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004172 }
Robert Carr2047fae2016-11-28 14:09:09 -08004173 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174 }
4175}
4176
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004177void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004178 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004179{
4180 String8 name;
4181 if (index < args.size()) {
4182 name = String8(args[index]);
4183 index++;
4184 }
4185
Robert Carr2047fae2016-11-28 14:09:09 -08004186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004187 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004188 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189 }
Robert Carr2047fae2016-11-28 14:09:09 -08004190 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004191
Svetoslavd85084b2014-03-20 10:28:31 -07004192 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004193}
4194
Jamie Gennis6547ff42013-07-16 20:12:42 -07004195// This should only be called from the main thread. Otherwise it would need
4196// the lock and should use mCurrentState rather than mDrawingState.
4197void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004198 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004199 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004200 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004201
4202 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4203}
4204
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004205void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004206{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004207 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004208
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004209 if (isLayerTripleBufferingDisabled())
4210 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004211
4212 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004213 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004214 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004215 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004216 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4217 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004218 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004219}
4220
Dan Stozab90cf072015-03-05 11:05:59 -08004221void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4222{
4223 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004224 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4225 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004226 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004227 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004228 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4229 b + 1, bucketTimeSec, percent);
4230 }
David Sodman4a36e932017-11-07 14:29:47 -08004231 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004232 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004233 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004234 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004235 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004236}
4237
Dan Stozae77c7662016-05-13 11:37:28 -07004238void SurfaceFlinger::recordBufferingStats(const char* layerName,
4239 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004240 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4241 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004242 for (const auto& segment : history) {
4243 if (!segment.usedThirdBuffer) {
4244 stats.twoBufferTime += segment.totalTime;
4245 }
4246 if (segment.occupancyAverage < 1.0f) {
4247 stats.doubleBufferedTime += segment.totalTime;
4248 } else if (segment.occupancyAverage < 2.0f) {
4249 stats.tripleBufferedTime += segment.totalTime;
4250 }
4251 ++stats.numSegments;
4252 stats.totalTime += segment.totalTime;
4253 }
4254}
4255
Brian Andersond6927fb2016-07-23 23:37:30 -07004256void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4257 result.appendFormat("Layer frame timestamps:\n");
4258
4259 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4260 const size_t count = currentLayers.size();
4261 for (size_t i=0 ; i<count ; i++) {
4262 currentLayers[i]->dumpFrameEvents(result);
4263 }
4264}
4265
Dan Stozae77c7662016-05-13 11:37:28 -07004266void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4267 result.append("Buffering stats:\n");
4268 result.append(" [Layer name] <Active time> <Two buffer> "
4269 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004270 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004271 typedef std::tuple<std::string, float, float, float> BufferTuple;
4272 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004273 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004274 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004275 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004276 if (stats.numSegments == 0) {
4277 continue;
4278 }
4279 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4280 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4281 stats.totalTime;
4282 float doubleBufferRatio = static_cast<float>(
4283 stats.doubleBufferedTime) / stats.totalTime;
4284 float tripleBufferRatio = static_cast<float>(
4285 stats.tripleBufferedTime) / stats.totalTime;
4286 sorted.insert({activeTime, {name, twoBufferRatio,
4287 doubleBufferRatio, tripleBufferRatio}});
4288 }
4289 for (const auto& sortedPair : sorted) {
4290 float activeTime = sortedPair.first;
4291 const BufferTuple& values = sortedPair.second;
4292 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4293 std::get<0>(values).c_str(), activeTime,
4294 std::get<1>(values), std::get<2>(values),
4295 std::get<3>(values));
4296 }
4297 result.append("\n");
4298}
4299
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004300void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004301 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004302 const int32_t displayId = display->getId();
4303 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4304 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004305 continue;
4306 }
4307
Dominik Laskowski7e045462018-05-30 13:02:02 -07004308 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309 uint8_t port;
4310 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004311 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004312 result.append("no identification data\n");
4313 continue;
4314 }
4315
4316 if (!isEdid(data)) {
4317 result.append("unknown identification data: ");
4318 for (uint8_t byte : data) {
4319 result.appendFormat("%x ", byte);
4320 }
4321 result.append("\n");
4322 continue;
4323 }
4324
4325 const auto edid = parseEdid(data);
4326 if (!edid) {
4327 result.append("invalid EDID: ");
4328 for (uint8_t byte : data) {
4329 result.appendFormat("%x ", byte);
4330 }
4331 result.append("\n");
4332 continue;
4333 }
4334
4335 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4336 result.append(edid->displayName.data(), edid->displayName.length());
4337 result.append("\"\n");
4338 }
4339 result.append("\n");
4340}
4341
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004342void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004343 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4344 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004345 result.appendFormat("DisplayColorSetting: %s\n",
4346 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004347
4348 // TODO: print out if wide-color mode is active or not
4349
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004350 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 const int32_t displayId = display->getId();
4352 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004353 continue;
4354 }
4355
Dominik Laskowski7e045462018-05-30 13:02:02 -07004356 result.appendFormat("Display %d color modes:\n", displayId);
4357 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004358 for (auto&& mode : modes) {
4359 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4360 }
4361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004363 result.appendFormat(" Current color mode: %s (%d)\n",
4364 decodeColorMode(currentMode).c_str(), currentMode);
4365 }
4366 result.append("\n");
4367}
4368
David Sodman7e4ae112018-02-09 15:02:28 -08004369void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4370 std::string stringResult;
4371
4372 for (const auto& [token, display] : mDisplays) {
4373 const auto displayId = display->getId();
4374 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4375 continue;
4376 }
4377
4378 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4379 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4380 break;
4381 }
4382 const auto& compositionInfoList = compositionInfoIt->second;
4383 stringResult += base::StringPrintf("Display: %d\n", displayId);
4384 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4385 for (const auto& compositionInfo : compositionInfoList) {
4386 compositionInfo.dump(stringResult, nullptr);
4387 stringResult += base::StringPrintf("\n");
4388 }
4389 }
4390
4391 result.append(stringResult.c_str());
4392}
4393
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004394LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004395 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004396 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4397 const State& state = useDrawing ? mDrawingState : mCurrentState;
4398 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004399 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004400 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004401 });
4402
4403 return layersProto;
4404}
4405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004406LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004407 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004408
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410 resolution->set_w(display.getWidth());
4411 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004412
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004413 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4414 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4415 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004416
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004419 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004420 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004421 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004422 }
4423 });
4424
4425 return layersProto;
4426}
4427
Mathias Agopian74d211a2013-04-22 16:55:35 +02004428void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4429 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004431 bool colorize = false;
4432 if (index < args.size()
4433 && (args[index] == String16("--color"))) {
4434 colorize = true;
4435 index++;
4436 }
4437
4438 Colorizer colorizer(colorize);
4439
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004440 // figure out if we're stuck somewhere
4441 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4444
4445 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004446 * Dump library configuration.
4447 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448
4449 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004450 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004451 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004452 appendSfConfigString(result);
4453 appendUiConfigString(result);
4454 appendGuiConfigString(result);
4455 result.append("\n");
4456
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004457 result.append("\nDisplay identification data:\n");
4458 dumpDisplayIdentificationData(result);
4459
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004460 result.append("\nWide-Color information:\n");
4461 dumpWideColorInfo(result);
4462
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004464 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004466 result.append(SyncFeatures::getInstance().toString());
4467 result.append("\n");
4468
Andy McFadden41d67d72014-04-25 16:58:34 -07004469 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004471 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004472
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004473 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4474 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004475 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4476 getHwComposer().isConnected(displayId)) {
4477 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004478 result.appendFormat("Display %d: "
4479 "app phase %" PRId64 " ns, "
4480 "sf phase %" PRId64 " ns, "
4481 "early app phase %" PRId64 " ns, "
4482 "early sf phase %" PRId64 " ns, "
4483 "early app gl phase %" PRId64 " ns, "
4484 "early sf gl phase %" PRId64 " ns, "
4485 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4486 displayId,
4487 vsyncPhaseOffsetNs,
4488 sfVsyncPhaseOffsetNs,
4489 appEarlyOffset,
4490 sfEarlyOffset,
4491 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004492 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004493 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004494 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004495 result.append("\n");
4496
Dan Stozab90cf072015-03-05 11:05:59 -08004497 // Dump static screen stats
4498 result.append("\n");
4499 dumpStaticScreenStats(result);
4500 result.append("\n");
4501
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004502 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4503
Dan Stozae77c7662016-05-13 11:37:28 -07004504 dumpBufferingStats(result);
4505
Andy McFadden4803b742012-09-24 19:07:20 -07004506 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507 * Dump the visible layer list
4508 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004509 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004510 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004511 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4512 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004513 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004514
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004515 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004516 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004517 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004518 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004519
David Sodman7e4ae112018-02-09 15:02:28 -08004520 result.append("\nFrame-Composition information:\n");
4521 dumpFrameCompositionInfo(result);
4522 result.append("\n");
4523
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004525 * Dump Display state
4526 */
4527
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004528 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004529 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004530 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004531 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004532 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004533 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004534 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004535
4536 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537 * Dump SurfaceFlinger global state
4538 */
4539
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004540 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004541 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004542 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004543
Mathias Agopian888c8222012-08-04 21:10:38 -07004544 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004546
David Sodmanbc815282017-11-05 18:57:52 -08004547 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004549 if (display) {
4550 display->undefinedRegion.dump(result, "undefinedRegion");
4551 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4552 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004553 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004554 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004555 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004556 mTransactionFlags, !mGpuToCpuSupported);
4557
4558 if (display) {
4559 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4560 result.appendFormat(" refresh-rate : %f fps\n"
4561 " x-dpi : %f\n"
4562 " y-dpi : %f\n",
4563 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4564 activeConfig->getDpiY());
4565 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566
Mathias Agopian74d211a2013-04-22 16:55:35 +02004567 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004568 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569
4570 /*
4571 * VSYNC state
4572 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004573 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004574 result.append("\n");
4575
4576 /*
4577 * HWC layer minidump
4578 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004579 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004580 const int32_t displayId = display->getId();
4581 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004582 continue;
4583 }
4584
Dominik Laskowski7e045462018-05-30 13:02:02 -07004585 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004586 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004587 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004588 result.append("\n");
4589 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590
4591 /*
4592 * Dump HWComposer state
4593 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004594 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004595 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004597 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004598 result.appendFormat(" h/w composer %s\n",
4599 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004600 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004601
4602 /*
4603 * Dump gralloc state
4604 */
4605 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4606 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004607
4608 /*
4609 * Dump VrFlinger state if in use.
4610 */
4611 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4612 result.append("VrFlinger state:\n");
4613 result.append(mVrFlinger->Dump().c_str());
4614 result.append("\n");
4615 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616}
4617
Dominik Laskowski7e045462018-05-30 13:02:02 -07004618const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004619 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004620 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004621 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004622 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004623 }
4624 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004625
4626 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4627 static const Vector<sp<Layer>> empty;
4628 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004629}
4630
Keun young Park63f165f2012-08-31 10:53:36 -07004631bool SurfaceFlinger::startDdmConnection()
4632{
4633 void* libddmconnection_dso =
4634 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4635 if (!libddmconnection_dso) {
4636 return false;
4637 }
4638 void (*DdmConnection_start)(const char* name);
4639 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004640 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004641 if (!DdmConnection_start) {
4642 dlclose(libddmconnection_dso);
4643 return false;
4644 }
4645 (*DdmConnection_start)(getServiceName());
4646 return true;
4647}
4648
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649void SurfaceFlinger::updateColorMatrixLocked() {
4650 mat4 colorMatrix;
4651 if (mGlobalSaturationFactor != 1.0f) {
4652 // Rec.709 luma coefficients
4653 float3 luminance{0.213f, 0.715f, 0.072f};
4654 luminance *= 1.0f - mGlobalSaturationFactor;
4655 mat4 saturationMatrix = mat4(
4656 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4657 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4658 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4659 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4660 );
4661 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4662 } else {
4663 colorMatrix = mClientColorMatrix * mDaltonizer();
4664 }
4665
4666 if (mCurrentState.colorMatrix != colorMatrix) {
4667 mCurrentState.colorMatrix = colorMatrix;
4668 mCurrentState.colorMatrixChanged = true;
4669 setTransactionFlags(eTransactionNeeded);
4670 }
4671}
4672
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004673status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004674#pragma clang diagnostic push
4675#pragma clang diagnostic error "-Wswitch-enum"
4676 switch (static_cast<ISurfaceComposerTag>(code)) {
4677 // These methods should at minimum make sure that the client requested
4678 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004679 case BOOT_FINISHED:
4680 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004681 case CREATE_CONNECTION:
4682 case CREATE_DISPLAY:
4683 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004684 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 case GET_ACTIVE_COLOR_MODE:
4686 case GET_ANIMATION_FRAME_STATS:
4687 case GET_HDR_CAPABILITIES:
4688 case SET_ACTIVE_CONFIG:
4689 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004690 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004691 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004692 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4693 IPCThreadState* ipc = IPCThreadState::self();
4694 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4695 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004696 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004697 }
Robert Carr1db73f62016-12-21 12:58:51 -08004698 return OK;
4699 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004701 IPCThreadState* ipc = IPCThreadState::self();
4702 const int pid = ipc->getCallingPid();
4703 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4705 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004706 return PERMISSION_DENIED;
4707 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004708 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004709 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004710 // Used by apps to hook Choreographer to SurfaceFlinger.
4711 case CREATE_DISPLAY_EVENT_CONNECTION:
4712 // The following calls are currently used by clients that do not
4713 // request necessary permissions. However, they do not expose any secret
4714 // information, so it is OK to pass them.
4715 case AUTHENTICATE_SURFACE:
4716 case GET_ACTIVE_CONFIG:
4717 case GET_BUILT_IN_DISPLAY:
4718 case GET_DISPLAY_COLOR_MODES:
4719 case GET_DISPLAY_CONFIGS:
4720 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004721 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4723 // Calling setTransactionState is safe, because you need to have been
4724 // granted a reference to Client* and Handle* to do anything with it.
4725 case SET_TRANSACTION_STATE:
4726 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4727 case CREATE_SCOPED_CONNECTION: {
4728 return OK;
4729 }
4730 case CAPTURE_LAYERS:
4731 case CAPTURE_SCREEN: {
4732 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004733 IPCThreadState* ipc = IPCThreadState::self();
4734 const int pid = ipc->getCallingPid();
4735 const int uid = ipc->getCallingUid();
4736 if ((uid != AID_GRAPHICS) &&
4737 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4738 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4739 return PERMISSION_DENIED;
4740 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741 return OK;
4742 }
4743 // The following codes are deprecated and should never be allowed to access SF.
4744 case CONNECT_DISPLAY_UNUSED:
4745 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4746 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4747 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004748 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004749 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004750
4751 // These codes are used for the IBinder protocol to either interrogate the recipient
4752 // side of the transaction for its canonical interface descriptor or to dump its state.
4753 // We let them pass by default.
4754 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4755 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4756 code == IBinder::SYSPROPS_TRANSACTION) {
4757 return OK;
4758 }
4759 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4760 // in onTransact verifies that the user is root, and has access to use SF.
4761 if (code >= 1000 && code <= 1029) {
4762 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4763 return OK;
4764 }
4765 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4766 return PERMISSION_DENIED;
4767#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004768}
4769
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4771 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004772 status_t credentialCheck = CheckTransactCodeCredentials(code);
4773 if (credentialCheck != OK) {
4774 return credentialCheck;
4775 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004777 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4778 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004779 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004780 IPCThreadState* ipc = IPCThreadState::self();
4781 const int uid = ipc->getCallingUid();
4782 if (CC_UNLIKELY(uid != AID_SYSTEM
4783 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004784 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004785 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004786 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 return PERMISSION_DENIED;
4788 }
4789 int n;
4790 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004791 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004792 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 return NO_ERROR;
4794 case 1002: // SHOW_UPDATES
4795 n = data.readInt32();
4796 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004797 invalidateHwcGeometry();
4798 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004800 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004801 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004802 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004804 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004805 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004806 setTransactionFlags(
4807 eTransactionNeeded|
4808 eDisplayTransactionNeeded|
4809 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004810 return NO_ERROR;
4811 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004812 case 1006:{ // send empty update
4813 signalRefresh();
4814 return NO_ERROR;
4815 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004816 case 1008: // toggle use of hw composer
4817 n = data.readInt32();
4818 mDebugDisableHWC = n ? 1 : 0;
4819 invalidateHwcGeometry();
4820 repaintEverything();
4821 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004822 case 1009: // toggle use of transform hint
4823 n = data.readInt32();
4824 mDebugDisableTransformHint = n ? 1 : 0;
4825 invalidateHwcGeometry();
4826 repaintEverything();
4827 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004829 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 reply->writeInt32(0);
4831 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004832 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004833 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004834 return NO_ERROR;
4835 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004836 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004837 if (!display) {
4838 return NAME_NOT_FOUND;
4839 }
4840
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004841 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004842 return NO_ERROR;
4843 }
4844 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004845 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004846 // daltonize
4847 n = data.readInt32();
4848 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004849 case 1:
4850 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4851 break;
4852 case 2:
4853 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4854 break;
4855 case 3:
4856 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4857 break;
4858 default:
4859 mDaltonizer.setType(ColorBlindnessType::None);
4860 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004861 }
4862 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004863 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004864 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004865 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004866 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004867
4868 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004869 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004871 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004872 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004873 // apply a color matrix
4874 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004876 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004877 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004878 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004879 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004880 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004881 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004882 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004884 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004885
4886 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4887 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004888 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004889 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4890 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4891 }
4892
Chia-I Wu28f320b2018-05-03 11:02:56 -07004893 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 return NO_ERROR;
4895 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004896 // This is an experimental interface
4897 // Needs to be shifted to proper binder interface when we productize
4898 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004899 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004900 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004901 return NO_ERROR;
4902 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004903 case 1017: {
4904 n = data.readInt32();
4905 mForceFullDamage = static_cast<bool>(n);
4906 return NO_ERROR;
4907 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004908 case 1018: { // Modify Choreographer's phase offset
4909 n = data.readInt32();
4910 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4911 return NO_ERROR;
4912 }
4913 case 1019: { // Modify SurfaceFlinger's phase offset
4914 n = data.readInt32();
4915 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4916 return NO_ERROR;
4917 }
Irvel468051e2016-06-13 16:44:44 -07004918 case 1020: { // Layer updates interceptor
4919 n = data.readInt32();
4920 if (n) {
4921 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004922 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004923 }
4924 else{
4925 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004926 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004927 }
4928 return NO_ERROR;
4929 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004930 case 1021: { // Disable HWC virtual displays
4931 n = data.readInt32();
4932 mUseHwcVirtualDisplays = !n;
4933 return NO_ERROR;
4934 }
Romain Guy0147a172017-06-01 13:53:56 -07004935 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004936 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004937 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004938
Chia-I Wu28f320b2018-05-03 11:02:56 -07004939 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004940 return NO_ERROR;
4941 }
Romain Guy54f154a2017-10-24 21:40:32 +01004942 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004943 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004944 invalidateHwcGeometry();
4945 repaintEverything();
4946 return NO_ERROR;
4947 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004948 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4949 // deprecate 1024 if they can.
4950 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004951 reply->writeBool(hasWideColorDisplay);
4952 return NO_ERROR;
4953 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004954 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004955 n = data.readInt32();
4956 if (n) {
4957 ALOGV("LayerTracing enabled");
4958 mTracing.enable();
4959 doTracing("tracing.enable");
4960 reply->writeInt32(NO_ERROR);
4961 } else {
4962 ALOGV("LayerTracing disabled");
4963 status_t err = mTracing.disable();
4964 reply->writeInt32(err);
4965 }
4966 return NO_ERROR;
4967 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004968 case 1026: { // Get layer tracing status
4969 reply->writeBool(mTracing.isEnabled());
4970 return NO_ERROR;
4971 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004972 // Is a DisplayColorSetting supported?
4973 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004974 const auto display = getDefaultDisplayDevice();
4975 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004976 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004977 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004978
4979 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4980 switch (setting) {
4981 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004982 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004983 break;
4984 case DisplayColorSetting::UNMANAGED:
4985 reply->writeBool(true);
4986 break;
4987 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004988 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004989 break;
4990 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 reply->writeBool(
4992 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004993 break;
4994 }
4995 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004996 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004997 // Is VrFlinger active?
4998 case 1028: {
4999 Mutex::Autolock _l(mStateLock);
5000 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5001 return NO_ERROR;
5002 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005003 case 1029: {
5004 // Code 1029 is an experimental feature that allows applications to
5005 // simulate a high frequency panel by setting a multiplier and divisor
5006 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005007 // 0, then the code simply return the current multiplier and divisor.
5008 HWC2::Device::FrequencyScaler frequencyScaler;
5009 frequencyScaler.multiplier = data.readInt32();
5010 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005011
David Sodman44b5de02018-08-21 16:28:53 -07005012 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5013 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5014 reply->writeInt32(frequencyScaler.multiplier);
5015 reply->writeInt32(frequencyScaler.divisor);
5016 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005017 }
5018
David Sodman44b5de02018-08-21 16:28:53 -07005019 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005020 enableHardwareVsync();
5021 } else {
5022 disableHardwareVsync(true);
5023 }
David Sodman44b5de02018-08-21 16:28:53 -07005024 mPrimaryDispSync->scalePeriod(frequencyScaler);
5025 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005026
David Sodman44b5de02018-08-21 16:28:53 -07005027 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5028 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5029
5030 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5031 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5032
5033 onHotplugReceived(getBE().mComposerSequenceId,
5034 hwcDisplayId, HWC2::Connection::Disconnected);
5035 onHotplugReceived(getBE().mComposerSequenceId,
5036 hwcDisplayId, HWC2::Connection::Connected);
5037 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5038 reply->writeInt32(frequencyScaler.multiplier);
5039 reply->writeInt32(frequencyScaler.divisor);
5040
David Sodman6d46c1e2018-07-13 12:59:48 -07005041 return NO_ERROR;
5042 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005043 // Is device color managed?
5044 case 1030: {
5045 reply->writeBool(useColorManagement);
5046 return NO_ERROR;
5047 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005048 }
5049 }
5050 return err;
5051}
5052
Steven Thomas6d8110b2017-08-31 18:24:21 -07005053void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005054 android_atomic_or(1, &mRepaintEverything);
5055 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005056}
5057
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005058// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5059class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005060public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005061 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5062 ~WindowDisconnector() {
5063 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005064 }
5065
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005066private:
5067 ANativeWindow* mWindow;
5068 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005069};
5070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005071status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5072 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5073 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5074 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005075 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005076 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005079
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005080 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5081
Chia-I Wu20261cb2018-08-23 12:55:44 -07005082 sp<DisplayDevice> display;
5083 {
5084 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005085
Chia-I Wu20261cb2018-08-23 12:55:44 -07005086 display = getDisplayDeviceLocked(displayToken);
5087 if (!display) return BAD_VALUE;
5088
Chia-I Wucb023152018-08-28 12:57:23 -07005089 // set the source crop to the (projected) logical display viewport
5090 // unconditionally until the framework is fixed
5091 sourceCrop.set(display->getScissor());
5092
5093 // set the requested width/height to the logical display viewport size
5094 // by default
5095 if (reqWidth == 0 || reqHeight == 0) {
5096 reqWidth = uint32_t(display->getViewport().width());
5097 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005098 }
5099
Chia-I Wua02871c2018-08-27 14:38:23 -07005100 // XXX display->getInstallOrientation() is ignored
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005101 }
5102
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005103 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005104
5105 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005106 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005107 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005108}
5109
5110status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005111 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005112 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005113 ATRACE_CALL();
5114
5115 class LayerRenderArea : public RenderArea {
5116 public:
Robert Carr578038f2018-03-09 12:25:24 -08005117 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5118 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005119 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005120 mLayer(layer),
5121 mCrop(crop),
5122 mFlinger(flinger),
5123 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005124 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005125 Rect getBounds() const override {
5126 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005127 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005128 }
Marissa Wall61c58622018-07-18 10:12:20 -07005129 int getHeight() const override {
5130 return mLayer->getActiveHeight(mLayer->getDrawingState());
5131 }
5132 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005133 bool isSecure() const override { return false; }
5134 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005135 Rect getSourceCrop() const override {
5136 if (mCrop.isEmpty()) {
5137 return getBounds();
5138 } else {
5139 return mCrop;
5140 }
5141 }
Robert Carr578038f2018-03-09 12:25:24 -08005142 class ReparentForDrawing {
5143 public:
5144 const sp<Layer>& oldParent;
5145 const sp<Layer>& newParent;
5146
5147 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5148 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005149 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005150 }
Robert Carr15eae092018-03-23 13:43:53 -07005151 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005152 };
5153
5154 void render(std::function<void()> drawLayers) override {
5155 if (!mChildrenOnly) {
5156 mTransform = mLayer->getTransform().inverse();
5157 drawLayers();
5158 } else {
5159 Rect bounds = getBounds();
5160 screenshotParentLayer =
5161 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5162 bounds.getWidth(), bounds.getHeight(), 0);
5163
5164 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5165 drawLayers();
5166 }
5167 }
chaviwa76b2712017-09-20 12:02:26 -07005168
chaviwa76b2712017-09-20 12:02:26 -07005169 private:
chaviw7206d492017-11-10 16:16:12 -08005170 const sp<Layer> mLayer;
5171 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005172
5173 // In the "childrenOnly" case we reparent the children to a screenshot
5174 // layer which has no properties set and which does not draw.
5175 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005176 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08005177
5178 SurfaceFlinger* mFlinger;
5179 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005180 };
5181
5182 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5183 auto parent = layerHandle->owner.promote();
5184
chaviw7206d492017-11-10 16:16:12 -08005185 if (parent == nullptr || parent->isPendingRemoval()) {
5186 ALOGE("captureLayers called with a removed parent");
5187 return NAME_NOT_FOUND;
5188 }
5189
Robert Carr578038f2018-03-09 12:25:24 -08005190 const int uid = IPCThreadState::self()->getCallingUid();
5191 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5192 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5193 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5194 return PERMISSION_DENIED;
5195 }
5196
chaviw7206d492017-11-10 16:16:12 -08005197 Rect crop(sourceCrop);
5198 if (sourceCrop.width() <= 0) {
5199 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005200 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005201 }
5202
5203 if (sourceCrop.height() <= 0) {
5204 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005205 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005206 }
5207
5208 int32_t reqWidth = crop.width() * frameScale;
5209 int32_t reqHeight = crop.height() * frameScale;
5210
Chia-I Wu20261cb2018-08-23 12:55:44 -07005211 // really small crop or frameScale
5212 if (reqWidth <= 0) {
5213 reqWidth = 1;
5214 }
5215 if (reqHeight <= 0) {
5216 reqHeight = 1;
5217 }
5218
Robert Carr578038f2018-03-09 12:25:24 -08005219 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005220
Robert Carr578038f2018-03-09 12:25:24 -08005221 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005222 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5223 if (!layer->isVisible()) {
5224 return;
Robert Carr578038f2018-03-09 12:25:24 -08005225 } else if (childrenOnly && layer == parent.get()) {
5226 return;
chaviwa76b2712017-09-20 12:02:26 -07005227 }
5228 visitor(layer);
5229 });
5230 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005231 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005232}
5233
5234status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5235 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005236 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005237 bool useIdentityTransform) {
5238 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005239
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005240 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5241 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5242 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5243 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244
5245 // This mutex protects syncFd and captureResult for communication of the return values from the
5246 // main thread back to this Binder thread
5247 std::mutex captureMutex;
5248 std::condition_variable captureCondition;
5249 std::unique_lock<std::mutex> captureLock(captureMutex);
5250 int syncFd = -1;
5251 std::optional<status_t> captureResult;
5252
Robert Carr03480e22018-01-04 16:02:06 -08005253 const int uid = IPCThreadState::self()->getCallingUid();
5254 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5255
Dominik Laskowski8c001672018-05-30 16:52:06 -07005256 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005257 // If there is a refresh pending, bug out early and tell the binder thread to try again
5258 // after the refresh.
5259 if (mRefreshPending) {
5260 ATRACE_NAME("Skipping screenshot for now");
5261 std::unique_lock<std::mutex> captureLock(captureMutex);
5262 captureResult = std::make_optional<status_t>(EAGAIN);
5263 captureCondition.notify_one();
5264 return;
5265 }
5266
5267 status_t result = NO_ERROR;
5268 int fd = -1;
5269 {
5270 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005271 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005272 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5273 useIdentityTransform, forSystem, &fd);
5274 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005275 }
5276
5277 {
5278 std::unique_lock<std::mutex> captureLock(captureMutex);
5279 syncFd = fd;
5280 captureResult = std::make_optional<status_t>(result);
5281 captureCondition.notify_one();
5282 }
5283 });
5284
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005285 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005287 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 while (*captureResult == EAGAIN) {
5289 captureResult.reset();
5290 result = postMessageAsync(message);
5291 if (result != NO_ERROR) {
5292 return result;
5293 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005294 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005295 }
5296 result = *captureResult;
5297 }
5298
5299 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005300 sync_wait(syncFd, -1);
5301 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005302 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005303
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005304 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005305}
5306
chaviwa76b2712017-09-20 12:02:26 -07005307void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5308 TraverseLayersFunction traverseLayers, bool yswap,
5309 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005310 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005311
Lloyd Pique144e1162017-12-20 16:44:52 -08005312 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005313
5314 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005315 const auto raWidth = renderArea.getWidth();
5316 const auto raHeight = renderArea.getHeight();
5317
5318 const auto reqWidth = renderArea.getReqWidth();
5319 const auto reqHeight = renderArea.getReqHeight();
5320 Rect sourceCrop = renderArea.getSourceCrop();
5321
Iris Chang7501ed62018-04-30 14:45:42 +08005322 bool filtering = false;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005323 if (primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +08005324 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5325 static_cast<int32_t>(reqHeight) != raWidth;
5326 } else {
5327 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5328 static_cast<int32_t>(reqHeight) != raHeight;
5329 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005330
Dan Stozac1879002014-05-22 15:59:05 -07005331 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005332 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005333 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005334 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005335 } else if (primaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005336 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005337 uint32_t flags = 0x00;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005338 switch (primaryDisplayOrientation) {
Iris Chang7501ed62018-04-30 14:45:42 +08005339 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005340 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005341 break;
5342 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005343 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005344 break;
5345 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005346 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005347 break;
5348 }
5349 tr.set(flags, raWidth, raHeight);
5350 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005351 }
5352
Chia-I Wu36574d92018-05-16 10:54:36 -07005353 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5354 engine.setOutputDataSpace(Dataspace::SRGB);
5355 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005356
Mathias Agopian180f10d2013-04-10 22:55:41 -07005357 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005358 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005359
Peiyong Linefefaac2018-08-17 12:27:51 -07005360 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005361 if (primaryDisplayOrientation != DisplayState::eOrientationDefault) {
Iris Chang7501ed62018-04-30 14:45:42 +08005362 // convert hw orientation into flag presentation
5363 // here inverse transform needed
5364 uint8_t hw_rot_90 = 0x00;
5365 uint8_t hw_flip_hv = 0x00;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005366 switch (primaryDisplayOrientation) {
Iris Chang7501ed62018-04-30 14:45:42 +08005367 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005368 hw_rot_90 = ui::Transform::ROT_90;
5369 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005370 break;
5371 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005372 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005373 break;
5374 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005375 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005376 break;
5377 }
5378
5379 // transform flags operation
5380 // 1) flip H V if both have ROT_90 flag
5381 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005382 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5383 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005384 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005385 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005386 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005387 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005388 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5389 }
5390
Mathias Agopian180f10d2013-04-10 22:55:41 -07005391 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005392 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005393 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005394 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005395
chaviw50da5042018-04-09 13:49:37 -07005396 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005397 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005398 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005399
chaviwa76b2712017-09-20 12:02:26 -07005400 traverseLayers([&](Layer* layer) {
5401 if (filtering) layer->setFiltering(true);
David Sodmanfb95bcc2017-12-22 15:45:30 -08005402 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005403 if (filtering) layer->setFiltering(false);
5404 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005405}
5406
chaviwa76b2712017-09-20 12:02:26 -07005407status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5408 TraverseLayersFunction traverseLayers,
5409 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005410 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005411 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005412 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005413 ATRACE_CALL();
5414
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005415 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005416
5417 traverseLayers([&](Layer* layer) {
5418 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5419 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005420
Robert Carr03480e22018-01-04 16:02:06 -08005421 // We allow the system server to take screenshots of secure layers for
5422 // use in situations like the Screen-rotation animation and place
5423 // the impetus on WindowManager to not persist them.
5424 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005425 ALOGW("FB is protected: PERMISSION_DENIED");
5426 return PERMISSION_DENIED;
5427 }
5428
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005429 // this binds the given EGLImage as a framebuffer for the
5430 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005431 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005432 if (bufferBond.getStatus() != NO_ERROR) {
5433 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005434 return INVALID_OPERATION;
5435 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005436
Dan Stozaabcda352017-06-01 14:37:39 -07005437 // this will in fact render into our dequeued buffer
5438 // via an FBO, which means we didn't have to create
5439 // an EGLSurface and therefore we're not
5440 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005441 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005442
Dan Stozaabcda352017-06-01 14:37:39 -07005443 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005444 getRenderEngine().finish();
5445 *outSyncFd = -1;
5446
chaviwa76b2712017-09-20 12:02:26 -07005447 const auto reqWidth = renderArea.getReqWidth();
5448 const auto reqHeight = renderArea.getReqHeight();
5449
Dan Stozaabcda352017-06-01 14:37:39 -07005450 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5451 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005452 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005453 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005454 } else {
5455 base::unique_fd syncFd = getRenderEngine().flush();
5456 if (syncFd < 0) {
5457 getRenderEngine().finish();
5458 }
5459 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005460 }
5461
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005462 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005463}
5464
Mathias Agopiand5556842013-09-19 17:08:37 -07005465void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005466 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005467 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005468 for (size_t y = 0; y < h; y++) {
5469 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5470 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005471 if (p[x] != 0xFF000000) return;
5472 }
5473 }
chaviwa76b2712017-09-20 12:02:26 -07005474 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005475
Robert Carr2047fae2016-11-28 14:09:09 -08005476 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005477 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005478 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005479 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5480 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5481 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5482 static_cast<float>(state.color.a));
5483 i++;
5484 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005485 }
5486}
5487
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005488// ---------------------------------------------------------------------------
5489
Dan Stoza412903f2017-04-27 13:42:17 -07005490void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5491 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005492}
5493
Dan Stoza412903f2017-04-27 13:42:17 -07005494void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5495 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005496}
5497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005498void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5499 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005500 const LayerVector::Visitor& visitor) {
5501 // We loop through the first level of layers without traversing,
5502 // as we need to interpret min/max layer Z in the top level Z space.
5503 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005504 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005505 continue;
5506 }
5507 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005508 // relative layers are traversed in Layer::traverseInZOrder
5509 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005510 continue;
5511 }
5512 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005513 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005514 return;
5515 }
chaviwa76b2712017-09-20 12:02:26 -07005516 if (!layer->isVisible()) {
5517 return;
5518 }
5519 visitor(layer);
5520 });
5521 }
5522}
5523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005524}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005525
Lloyd Pique074e8122018-07-26 12:57:23 -07005526
Mathias Agopian3f844832013-08-07 21:24:32 -07005527#if defined(__gl_h_)
5528#error "don't include gl/gl.h in this file"
5529#endif
5530
5531#if defined(__gl2_h_)
5532#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005533#endif