blob: 328724bd31fc7d3d59b945fcbd78c74924001b9f [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
2441 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002442 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002445 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2446 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2447 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002448 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002449
2450 if (maxFrameBufferAcquiredBuffers >= 3) {
2451 nativeWindowSurface->preallocateBuffers();
2452 }
2453
2454 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002455 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2456 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002458 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002459 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002461 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002462 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002463 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002464 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 display->setLayerStack(state.layerStack);
2466 display->setProjection(state.orientation, state.viewport, state.frame);
2467 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002468
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002469 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470}
2471
Lloyd Pique347200f2017-12-14 17:00:15 -08002472void SurfaceFlinger::processDisplayChangesLocked() {
2473 // here we take advantage of Vector's copy-on-write semantics to
2474 // improve performance by skipping the transaction entirely when
2475 // know that the lists are identical
2476 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2477 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2478 if (!curr.isIdenticalTo(draw)) {
2479 mVisibleRegionsDirty = true;
2480 const size_t cc = curr.size();
2481 size_t dc = draw.size();
2482
2483 // find the displays that were removed
2484 // (ie: in drawing state but not in current state)
2485 // also handle displays that changed
2486 // (ie: displays that are in both lists)
2487 for (size_t i = 0; i < dc;) {
2488 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2489 if (j < 0) {
2490 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002491 // Call makeCurrent() on the primary display so we can
2492 // be sure that nothing associated with this display
2493 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2495 defaultDisplay->makeCurrent();
2496 }
2497 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2498 display->disconnect(getHwComposer());
2499 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002500 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2501 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2502 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2503 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2504 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 } else {
2507 // this display is in both lists. see if something changed.
2508 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2511 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2512 if (state_binder != draw_binder) {
2513 // changing the surface is like destroying and
2514 // recreating the DisplayDevice, so we just remove it
2515 // from the drawing state, so that it get re-added
2516 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002517 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2518 display->disconnect(getHwComposer());
2519 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 mDrawingState.displays.removeItemsAt(i);
2522 dc--;
2523 // at this point we must loop to the next item
2524 continue;
2525 }
2526
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002528 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002529 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002530 }
2531 if ((state.orientation != draw[i].orientation) ||
2532 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 }
2535 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002537 }
2538 }
2539 }
2540 ++i;
2541 }
2542
2543 // find displays that were added
2544 // (ie: in current state but not in drawing state)
2545 for (size_t i = 0; i < cc; i++) {
2546 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2547 const DisplayDeviceState& state(curr[i]);
2548
2549 sp<DisplaySurface> dispSurface;
2550 sp<IGraphicBufferProducer> producer;
2551 sp<IGraphicBufferProducer> bqProducer;
2552 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002553 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002554
Dominik Laskowski7e045462018-05-30 13:02:02 -07002555 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002556 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 // Virtual displays without a surface are dormant:
2558 // they have external state (layer stack, projection,
2559 // etc.) but no internal state (i.e. a DisplayDevice).
2560 if (state.surface != nullptr) {
2561 // Allow VR composer to use virtual displays.
2562 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2563 int width = 0;
2564 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2565 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2566 int height = 0;
2567 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2568 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2569 int intFormat = 0;
2570 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2571 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002572 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002573
Dominik Laskowski7e045462018-05-30 13:02:02 -07002574 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2575 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002576 }
2577
2578 // TODO: Plumb requested format back up to consumer
2579
2580 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002581 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002582 bqProducer, bqConsumer,
2583 state.displayName);
2584
2585 dispSurface = vds;
2586 producer = vds;
2587 }
2588 } else {
2589 ALOGE_IF(state.surface != nullptr,
2590 "adding a supported display, but rendering "
2591 "surface is provided (%p), ignoring it",
2592 state.surface.get());
2593
Dominik Laskowski7e045462018-05-30 13:02:02 -07002594 displayId = state.type;
2595 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002596 producer = bqProducer;
2597 }
2598
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002599 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002601 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002602 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002603 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002604 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002605 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2606 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2607 true);
2608 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2609 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2610 true);
2611 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 }
2613 }
2614 }
2615 }
2616 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002617
2618 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002619}
2620
Mathias Agopian87baae12012-07-31 12:38:26 -07002621void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002622{
Dan Stoza7dde5992015-05-22 09:51:44 -07002623 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002624 mCurrentState.traverseInZOrder([](Layer* layer) {
2625 layer->notifyAvailableFrames();
2626 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002627
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 /*
2629 * Traversal of the children
2630 * (perform the transaction for each of them if needed)
2631 */
2632
Mathias Agopian3559b072012-08-15 13:46:03 -07002633 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002634 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002636 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
2638 const uint32_t flags = layer->doTransaction(0);
2639 if (flags & Layer::eVisibleRegion)
2640 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002641 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 }
2643
2644 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002645 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 */
2647
Mathias Agopiane57f2922012-08-09 16:29:12 -07002648 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002650 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002651 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002653 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002654 // The transform hint might have changed for some layers
2655 // (either because a display has changed, or because a layer
2656 // as changed).
2657 //
2658 // Walk through all the layers in currentLayers,
2659 // and update their transform hint.
2660 //
2661 // If a layer is visible only on a single display, then that
2662 // display is used to calculate the hint, otherwise we use the
2663 // default display.
2664 //
2665 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2666 // the hint is set before we acquire a buffer from the surface texture.
2667 //
2668 // NOTE: layer transactions have taken place already, so we use their
2669 // drawing state. However, SurfaceFlinger's own transaction has not
2670 // happened yet, so we must use the current state layer list
2671 // (soon to become the drawing state list).
2672 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002673 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002674 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002675 bool first = true;
2676 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002677 // NOTE: we rely on the fact that layers are sorted by
2678 // layerStack first (so we don't have to traverse the list
2679 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002681 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002682 currentlayerStack = layerStack;
2683 // figure out if this layerstack is mirrored
2684 // (more than one display) if so, pick the default display,
2685 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 hintDisplay = nullptr;
2687 for (const auto& [token, display] : mDisplays) {
2688 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2689 if (hintDisplay) {
2690 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002691 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002693 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002694 }
2695 }
2696 }
2697 }
Chet Haase91d25932013-04-11 15:24:55 -07002698
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002700 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2701 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002702
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002703 // could be null when this layer is using a layerStack
2704 // that is not visible on any display. Also can occur at
2705 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002707 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002708
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002711 if (hintDisplay) {
2712 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002713 }
Robert Carr2047fae2016-11-28 14:09:09 -08002714
2715 first = false;
2716 });
Mathias Agopian84300952012-11-21 16:02:13 -08002717 }
2718
2719
Mathias Agopian3559b072012-08-15 13:46:03 -07002720 /*
2721 * Perform our own transaction if needed
2722 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723
2724 if (mLayersAdded) {
2725 mLayersAdded = false;
2726 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002727 mVisibleRegionsDirty = true;
2728 }
2729
2730 // some layers might have been removed, so
2731 // we need to update the regions they're exposing.
2732 if (mLayersRemoved) {
2733 mLayersRemoved = false;
2734 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002735 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002737 // this layer is not visible anymore
2738 // TODO: we could traverse the tree from front to back and
2739 // compute the actual visible region
2740 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 Region visibleReg;
2742 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002743 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002744 }
Robert Carr2047fae2016-11-28 14:09:09 -08002745 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 }
2747
2748 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002749
2750 updateCursorAsync();
2751}
2752
2753void SurfaceFlinger::updateCursorAsync()
2754{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002756 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002757 continue;
2758 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2761 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002762 }
2763 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002764}
2765
2766void SurfaceFlinger::commitTransaction()
2767{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002768 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002769 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 for (const auto& l : mLayersPendingRemoval) {
2771 recordBufferingStats(l->getName().string(),
2772 l->getOccupancyHistory(true));
2773 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774 }
2775 mLayersPendingRemoval.clear();
2776 }
2777
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002778 // If this transaction is part of a window animation then the next frame
2779 // we composite should be considered an animation as well.
2780 mAnimCompositionPending = mAnimTransactionPending;
2781
Mathias Agopian4fec8732012-06-29 14:12:52 -07002782 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002783 // clear the "changed" flags in current state
2784 mCurrentState.colorMatrixChanged = false;
2785
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 mDrawingState.traverseInZOrder([](Layer* layer) {
2787 layer->commitChildList();
2788 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002789 mTransactionPending = false;
2790 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002791 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792}
2793
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002794void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2795 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002796 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002798
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 Region aboveOpaqueLayers;
2800 Region aboveCoveredLayers;
2801 Region dirty;
2802
Mathias Agopian87baae12012-07-31 12:38:26 -07002803 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804
Robert Carr2047fae2016-11-28 14:09:09 -08002805 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002807 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808
Jesse Hall01e29052013-02-19 16:13:35 -08002809 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002810 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002811 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002812 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002813
Mathias Agopianab028732010-03-16 16:41:46 -07002814 /*
2815 * opaqueRegion: area of a surface that is fully opaque.
2816 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002818
2819 /*
2820 * visibleRegion: area of a surface that is visible on screen
2821 * and not fully transparent. This is essentially the layer's
2822 * footprint minus the opaque regions above it.
2823 * Areas covered by a translucent surface are considered visible.
2824 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002826
2827 /*
2828 * coveredRegion: area of a surface that is covered by all
2829 * visible regions above it (which includes the translucent areas).
2830 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002832
Jesse Halla8026d22012-09-25 13:25:04 -07002833 /*
2834 * transparentRegion: area of a surface that is hinted to be completely
2835 * transparent. This is only used to tell when the layer has no visible
2836 * non-transparent regions and can be removed from the layer list. It
2837 * does not affect the visibleRegion of this layer or any layers
2838 * beneath it. The hint may not be correct if apps don't respect the
2839 * SurfaceView restrictions (which, sadly, some don't).
2840 */
2841 Region transparentRegion;
2842
Mathias Agopianab028732010-03-16 16:41:46 -07002843
2844 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002845 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002846 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002847 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002849 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002850 if (!visibleRegion.isEmpty()) {
2851 // Remove the transparent area from the visible region
2852 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002853 if (tr.preserveRects()) {
2854 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002855 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002856 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002857 // transformation too complex, can't do the
2858 // transparent region optimization.
2859 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 }
Mathias Agopianab028732010-03-16 16:41:46 -07002861 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862
Mathias Agopianab028732010-03-16 16:41:46 -07002863 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002865 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002866 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002867 // the opaque region is the layer's footprint
2868 opaqueRegion = visibleRegion;
2869 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 }
2871 }
2872
Robert Carre5f4f692018-01-12 13:12:28 -08002873 if (visibleRegion.isEmpty()) {
2874 layer->clearVisibilityRegions();
2875 return;
2876 }
2877
Mathias Agopianab028732010-03-16 16:41:46 -07002878 // Clip the covered region to the visible region
2879 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2880
2881 // Update aboveCoveredLayers for next (lower) layer
2882 aboveCoveredLayers.orSelf(visibleRegion);
2883
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 // subtract the opaque region covered by the layers above us
2885 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886
2887 // compute this layer's dirty region
2888 if (layer->contentDirty) {
2889 // we need to invalidate the whole region
2890 dirty = visibleRegion;
2891 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 layer->contentDirty = false;
2894 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002895 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002896 * the exposed region consists of two components:
2897 * 1) what's VISIBLE now and was COVERED before
2898 * 2) what's EXPOSED now less what was EXPOSED before
2899 *
2900 * note that (1) is conservative, we start with the whole
2901 * visible region but only keep what used to be covered by
2902 * something -- which mean it may have been exposed.
2903 *
2904 * (2) handles areas that were not covered by anything but got
2905 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002906 */
Mathias Agopianab028732010-03-16 16:41:46 -07002907 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908 const Region oldVisibleRegion = layer->visibleRegion;
2909 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002910 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2911 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 }
2913 dirty.subtractSelf(aboveOpaqueLayers);
2914
2915 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002916 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917
Mathias Agopianab028732010-03-16 16:41:46 -07002918 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002920
Jesse Halla8026d22012-09-25 13:25:04 -07002921 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 layer->setVisibleRegion(visibleRegion);
2923 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002924 layer->setVisibleNonTransparentRegion(
2925 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002926 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927
Mathias Agopian87baae12012-07-31 12:38:26 -07002928 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929}
2930
Chia-I Wuab0c3192017-08-01 11:29:00 -07002931void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2934 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002935 }
2936 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002937}
2938
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 ALOGV("handlePageFlip");
2942
Brian Andersond6927fb2016-07-23 23:37:30 -07002943 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002946 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002947 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002948
2949 // Store the set of layers that need updates. This set must not change as
2950 // buffers are being latched, as this could result in a deadlock.
2951 // Example: Two producers share the same command stream and:
2952 // 1.) Layer 0 is latched
2953 // 2.) Layer 0 gets a new frame
2954 // 2.) Layer 1 gets a new frame
2955 // 3.) Layer 1 is latched.
2956 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2957 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002958 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002959 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002961 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002963 } else {
2964 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002965 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002966 } else {
2967 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002968 }
Robert Carr2047fae2016-11-28 14:09:09 -08002969 });
2970
Dan Stoza9e56aa02015-11-02 13:00:03 -08002971 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002972 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002973 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002974 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002975 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002976 newDataLatched = true;
2977 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002978 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002979
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002980 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002981
2982 // If we will need to wake up at some time in the future to deal with a
2983 // queued frame that shouldn't be displayed during this vsync period, wake
2984 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002985 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002986 signalLayerUpdate();
2987 }
2988
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002989 // enter boot animation on first buffer latch
2990 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2991 ALOGI("Enter boot animation");
2992 mBootStage = BootStage::BOOTANIMATION;
2993 }
2994
Dan Stoza6b9454d2014-11-07 16:00:59 -08002995 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002996 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Mathias Agopianad456f92011-01-13 17:53:01 -08002999void SurfaceFlinger::invalidateHwcGeometry()
3000{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003002}
3003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003004void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3005 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003006 // We only need to actually compose the display if:
3007 // 1) It is being handled by hardware composer, which may need this to
3008 // keep its virtual display state machine in sync, or
3009 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003010 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003011 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003013 return;
3014 }
3015
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003017 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003018
3019 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021}
3022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003023bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 const Region bounds(display->bounds());
3027 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003028 const auto displayId = display->getId();
3029 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003030 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003031
Chia-I Wu8e50e692018-05-04 10:12:37 -07003032 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003033 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003034
Dan Stoza9e56aa02015-11-02 13:00:03 -08003035 if (hasClientComposition) {
3036 ALOGV("hasClientComposition");
3037
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003038 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003039 if (display->hasWideColorGamut()) {
3040 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003041 }
3042 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003043 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003045
Dominik Laskowski7e045462018-05-30 13:02:02 -07003046 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003047 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3048 HWC2::Capability::SkipClientColorTransform);
3049
Chia-I Wud49d6692018-06-27 07:17:41 +08003050 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003051 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3052 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003053 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003054 }
3055
Chia-I Wud49d6692018-06-27 07:17:41 +08003056 // The current enhanced saturation matrix is designed to enhance Display P3,
3057 // thus we only apply this matrix when the render intent is not colorimetric
3058 // and the output color space is Display P3.
3059 needsEnhancedColorMatrix =
3060 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3061 outputDataspace == Dataspace::DISPLAY_P3);
3062 if (needsEnhancedColorMatrix) {
3063 colorMatrix *= mEnhancedSaturationMatrix;
3064 }
3065
3066 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003068 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003069 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003070 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003071 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003072
3073 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003074 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3075 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3076 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003077 }
3078 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003079 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003080
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003081 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003083 // when using overlays, we assume a fully transparent framebuffer
3084 // NOTE: we could reduce how much we need to clear, for instance
3085 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003086 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003087 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003088 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003089 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003090 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003091 // we're left with the letterbox region
3092 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003094
3095 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003096 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003097
Mathias Agopianb9494d52012-04-18 02:28:45 -07003098 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003099 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003100 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003101 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003102 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003103 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003104
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003105 const Rect& bounds = display->getBounds();
3106 const Rect& scissor = display->getScissor();
3107 if (scissor != bounds) {
3108 // scissor doesn't match the screen's dimensions, so we
3109 // need to clear everything outside of it and enable
3110 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003111
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003112 // enable scissor for this frame
3113 const uint32_t height = display->getHeight();
3114 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3115 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003116 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003117 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003118
Mathias Agopian85d751c2012-08-29 16:59:24 -07003119 /*
3120 * and then, render the layers targeted at the framebuffer
3121 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003122
Dan Stoza9e56aa02015-11-02 13:00:03 -08003123 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003124 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003126 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3127 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003128 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003129 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3130 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003131 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003132 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003133 case HWC2::Composition::Cursor:
3134 case HWC2::Composition::Device:
3135 case HWC2::Composition::Sideband:
3136 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003137 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3138 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3139 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3140 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003141 // never clear the very first layer since we're
3142 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003143 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003144 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003145 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003146 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003147 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003148 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003149 break;
3150 }
3151 default:
3152 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003153 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003154 } else {
3155 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003156 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003157 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003158 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003159
Chia-I Wud49d6692018-06-27 07:17:41 +08003160 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003161 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003162 }
3163
Mathias Agopianf45c5102012-10-24 16:29:17 -07003164 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003165 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003166 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167}
3168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003169void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3170 const Region& region) const {
3171 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003172 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003173 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174}
3175
Dan Stoza7d89d062015-04-30 13:29:25 -07003176status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003177 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003178 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 const sp<Layer>& lbc,
3180 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003181{
Dan Stoza7d89d062015-04-30 13:29:25 -07003182 // add this layer to the current state list
3183 {
3184 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003186 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3187 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003188 return NO_MEMORY;
3189 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 if (parent == nullptr) {
3191 mCurrentState.layersSortedByZ.add(lbc);
3192 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003193 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003194 ALOGE("addClientLayer called with a removed parent");
3195 return NAME_NOT_FOUND;
3196 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003197 parent->addChild(lbc);
3198 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199
Yiwei Zhang243b3782018-05-15 17:40:04 -07003200 if (gbc != nullptr) {
3201 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3202 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3203 mMaxGraphicBufferProducerListSize,
3204 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3205 mGraphicBufferProducerList.size(),
3206 mMaxGraphicBufferProducerListSize, mNumLayers);
3207 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003208 mLayersAdded = true;
3209 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003210 }
3211
Mathias Agopian96f08192010-06-02 23:28:45 -07003212 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003213 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003214
Dan Stoza7d89d062015-04-30 13:29:25 -07003215 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003216}
3217
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003218status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003219 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003220 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3221}
Robert Carr7f9b8992017-03-10 11:08:39 -08003222
chaviwca27f252018-02-06 16:46:39 -08003223status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3224 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003225 if (layer->isPendingRemoval()) {
3226 return NO_ERROR;
3227 }
3228
Robert Carr1f0a16a2016-10-24 16:27:39 -07003229 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003230 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003231 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003232 if (topLevelOnly) {
3233 return NO_ERROR;
3234 }
3235
Chia-I Wu98f1c102017-05-30 14:54:08 -07003236 sp<Layer> ancestor = p;
3237 while (ancestor->getParent() != nullptr) {
3238 ancestor = ancestor->getParent();
3239 }
3240 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3241 ALOGE("removeLayer called with a layer whose parent has been removed");
3242 return NAME_NOT_FOUND;
3243 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003244
3245 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003246 } else {
3247 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003248 }
3249
Robert Carr136e2f62017-02-08 17:54:29 -08003250 // As a matter of normal operation, the LayerCleaner will produce a second
3251 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3252 // so we will succeed in promoting it, but it's already been removed
3253 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3254 // otherwise something has gone wrong and we are leaking the layer.
3255 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003256 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3257 layer->getName().string(),
3258 (p != nullptr) ? p->getName().string() : "no-parent");
3259 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003260 } else if (index < 0) {
3261 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003262 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003263
Chia-I Wuc6657022017-08-15 11:18:17 -07003264 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003265 mLayersPendingRemoval.add(layer);
3266 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003267 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 setTransactionFlags(eTransactionNeeded);
3269 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270}
3271
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003272uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003273 return android_atomic_release_load(&mTransactionFlags);
3274}
3275
Mathias Agopian3f844832013-08-07 21:24:32 -07003276uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3278}
3279
Mathias Agopian3f844832013-08-07 21:24:32 -07003280uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003281 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3282}
3283
3284uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3285 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003287 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003289 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 }
3291 return old;
3292}
3293
chaviwca27f252018-02-06 16:46:39 -08003294bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3295 for (const ComposerState& state : states) {
3296 // Here we need to check that the interface we're given is indeed
3297 // one of our own. A malicious client could give us a nullptr
3298 // IInterface, or one of its own or even one of our own but a
3299 // different type. All these situations would cause us to crash.
3300 if (state.client == nullptr) {
3301 return true;
3302 }
3303
3304 sp<IBinder> binder = IInterface::asBinder(state.client);
3305 if (binder == nullptr) {
3306 return true;
3307 }
3308
3309 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3310 return true;
3311 }
3312 }
3313 return false;
3314}
3315
Mathias Agopian8b33f032012-07-24 20:43:54 -07003316void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003317 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003318 const Vector<DisplayState>& displays,
3319 uint32_t flags)
3320{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003321 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003322 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003323 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324
chaviwca27f252018-02-06 16:46:39 -08003325 if (containsAnyInvalidClientState(states)) {
3326 return;
3327 }
3328
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003329 if (flags & eAnimation) {
3330 // For window updates that are part of an animation we must wait for
3331 // previous animation "frames" to be handled.
3332 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003333 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003334 if (CC_UNLIKELY(err != NO_ERROR)) {
3335 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003336 // caller after a few seconds.
3337 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3338 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003339 mAnimTransactionPending = false;
3340 break;
3341 }
3342 }
3343 }
3344
chaviwca27f252018-02-06 16:46:39 -08003345 for (const DisplayState& display : displays) {
3346 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003347 }
3348
chaviwca27f252018-02-06 16:46:39 -08003349 for (const ComposerState& state : states) {
3350 transactionFlags |= setClientStateLocked(state);
3351 }
3352
3353 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3354 // as destroyed should only occur after setting all other states. This is to allow for a
3355 // child re-parent to happen before marking its original parent as destroyed (which would
3356 // then mark the child as destroyed).
3357 for (const ComposerState& state : states) {
3358 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003359 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003360
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003361 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3362 // anyway. This can be used as a flush mechanism for previous async transactions.
3363 // Empty animation transaction can be used to simulate back-pressure, so also force a
3364 // transaction for empty animation transactions.
3365 if (transactionFlags == 0 &&
3366 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003367 transactionFlags = eTransactionNeeded;
3368 }
3369
Mathias Agopian386aa982011-11-07 21:58:03 -08003370 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003371 if (mInterceptor->isEnabled()) {
3372 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003373 }
Irvel468051e2016-06-13 16:44:44 -07003374
Mathias Agopian386aa982011-11-07 21:58:03 -08003375 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003376 const auto start = (flags & eEarlyWakeup)
3377 ? VSyncModulator::TransactionStart::EARLY
3378 : VSyncModulator::TransactionStart::NORMAL;
3379 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003380
3381 // if this is a synchronous transaction, wait for it to take effect
3382 // before returning.
3383 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003384 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003385 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003386 if (flags & eAnimation) {
3387 mAnimTransactionPending = true;
3388 }
3389 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003390 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3391 if (CC_UNLIKELY(err != NO_ERROR)) {
3392 // just in case something goes wrong in SF, return to the
3393 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003394 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3395 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003396 break;
3397 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003398 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003399 }
3400}
3401
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003402uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3403 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3404 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003405
Mathias Agopiane57f2922012-08-09 16:29:12 -07003406 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003407 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3408
3409 const uint32_t what = s.what;
3410 if (what & DisplayState::eSurfaceChanged) {
3411 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3412 state.surface = s.surface;
3413 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003414 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003415 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003416 if (what & DisplayState::eLayerStackChanged) {
3417 if (state.layerStack != s.layerStack) {
3418 state.layerStack = s.layerStack;
3419 flags |= eDisplayTransactionNeeded;
3420 }
3421 }
3422 if (what & DisplayState::eDisplayProjectionChanged) {
3423 if (state.orientation != s.orientation) {
3424 state.orientation = s.orientation;
3425 flags |= eDisplayTransactionNeeded;
3426 }
3427 if (state.frame != s.frame) {
3428 state.frame = s.frame;
3429 flags |= eDisplayTransactionNeeded;
3430 }
3431 if (state.viewport != s.viewport) {
3432 state.viewport = s.viewport;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 }
3436 if (what & DisplayState::eDisplaySizeChanged) {
3437 if (state.width != s.width) {
3438 state.width = s.width;
3439 flags |= eDisplayTransactionNeeded;
3440 }
3441 if (state.height != s.height) {
3442 state.height = s.height;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 }
3446
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447 return flags;
3448}
3449
Robert Carrd4ae7f32018-06-07 16:10:57 -07003450bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3451 IPCThreadState* ipc = IPCThreadState::self();
3452 const int pid = ipc->getCallingPid();
3453 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003454 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003455 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003456 return false;
3457 }
3458 return true;
3459}
3460
chaviwca27f252018-02-06 16:46:39 -08003461uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3462 const layer_state_t& s = composerState.state;
3463 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3464
Mathias Agopian13127d82013-03-05 17:47:11 -08003465 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003466 if (layer == nullptr) {
3467 return 0;
3468 }
3469
3470 if (layer->isPendingRemoval()) {
3471 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3472 return 0;
3473 }
3474
3475 uint32_t flags = 0;
3476
3477 const uint32_t what = s.what;
3478 bool geometryAppliesWithResize =
3479 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003480
3481 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3482 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003483 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003484 layer->pushPendingState();
3485 }
3486
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (what & layer_state_t::ePositionChanged) {
3488 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3489 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003490 }
chaviw8b3871a2017-11-01 17:41:01 -07003491 }
3492 if (what & layer_state_t::eLayerChanged) {
3493 // NOTE: index needs to be calculated before we update the state
3494 const auto& p = layer->getParent();
3495 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003496 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003497 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003498 mCurrentState.layersSortedByZ.removeAt(idx);
3499 mCurrentState.layersSortedByZ.add(layer);
3500 // we need traversal (state changed)
3501 // AND transaction (list changed)
3502 flags |= eTransactionNeeded|eTraversalNeeded;
3503 }
chaviw8b3871a2017-11-01 17:41:01 -07003504 } else {
3505 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003506 flags |= eTransactionNeeded|eTraversalNeeded;
3507 }
3508 }
chaviw8b3871a2017-11-01 17:41:01 -07003509 }
3510 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003511 // NOTE: index needs to be calculated before we update the state
3512 const auto& p = layer->getParent();
3513 if (p == nullptr) {
3514 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3515 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3516 mCurrentState.layersSortedByZ.removeAt(idx);
3517 mCurrentState.layersSortedByZ.add(layer);
3518 // we need traversal (state changed)
3519 // AND transaction (list changed)
3520 flags |= eTransactionNeeded|eTraversalNeeded;
3521 }
3522 } else {
3523 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3524 flags |= eTransactionNeeded|eTraversalNeeded;
3525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 }
3527 }
3528 if (what & layer_state_t::eSizeChanged) {
3529 if (layer->setSize(s.w, s.h)) {
3530 flags |= eTraversalNeeded;
3531 }
3532 }
3533 if (what & layer_state_t::eAlphaChanged) {
3534 if (layer->setAlpha(s.alpha))
3535 flags |= eTraversalNeeded;
3536 }
3537 if (what & layer_state_t::eColorChanged) {
3538 if (layer->setColor(s.color))
3539 flags |= eTraversalNeeded;
3540 }
3541 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003542 // TODO: b/109894387
3543 //
3544 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3545 // rotation. To see the problem observe that if we have a square parent, and a child
3546 // of the same size, then we rotate the child 45 degrees around it's center, the child
3547 // must now be cropped to a non rectangular 8 sided region.
3548 //
3549 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3550 // private API, and the WindowManager only uses rotation in one case, which is on a top
3551 // level layer in which cropping is not an issue.
3552 //
3553 // However given that abuse of rotation matrices could lead to surfaces extending outside
3554 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3555 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3556 // transformations.
3557 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003558 flags |= eTraversalNeeded;
3559 }
3560 if (what & layer_state_t::eTransparentRegionChanged) {
3561 if (layer->setTransparentRegionHint(s.transparentRegion))
3562 flags |= eTraversalNeeded;
3563 }
3564 if (what & layer_state_t::eFlagsChanged) {
3565 if (layer->setFlags(s.flags, s.mask))
3566 flags |= eTraversalNeeded;
3567 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003568 if (what & layer_state_t::eCropChanged_legacy) {
3569 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003570 flags |= eTraversalNeeded;
3571 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003572 if (what & layer_state_t::eFinalCropChanged_legacy) {
3573 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003574 flags |= eTraversalNeeded;
3575 }
3576 if (what & layer_state_t::eLayerStackChanged) {
3577 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3578 // We only allow setting layer stacks for top level layers,
3579 // everything else inherits layer stack from its parent.
3580 if (layer->hasParent()) {
3581 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3582 layer->getName().string());
3583 } else if (idx < 0) {
3584 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3585 "that also does not appear in the top level layer list. Something"
3586 " has gone wrong.", layer->getName().string());
3587 } else if (layer->setLayerStack(s.layerStack)) {
3588 mCurrentState.layersSortedByZ.removeAt(idx);
3589 mCurrentState.layersSortedByZ.add(layer);
3590 // we need traversal (state changed)
3591 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003592 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003593 }
3594 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003595 if (what & layer_state_t::eDeferTransaction_legacy) {
3596 if (s.barrierHandle_legacy != nullptr) {
3597 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3598 } else if (s.barrierGbp_legacy != nullptr) {
3599 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003600 if (authenticateSurfaceTextureLocked(gbp)) {
3601 const auto& otherLayer =
3602 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003603 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003604 } else {
3605 ALOGE("Attempt to defer transaction to to an"
3606 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003607 }
3608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 // We don't trigger a traversal here because if no other state is
3610 // changed, we don't want this to cause any more work
3611 }
3612 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003613 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003614 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003615 if (!hadParent) {
3616 mCurrentState.layersSortedByZ.remove(layer);
3617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003619 }
chaviw8b3871a2017-11-01 17:41:01 -07003620 }
3621 if (what & layer_state_t::eReparentChildren) {
3622 if (layer->reparentChildren(s.reparentHandle)) {
3623 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003624 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 if (what & layer_state_t::eDetachChildren) {
3627 layer->detachChildren();
3628 }
3629 if (what & layer_state_t::eOverrideScalingModeChanged) {
3630 layer->setOverrideScalingMode(s.overrideScalingMode);
3631 // We don't trigger a traversal here because if no other state is
3632 // changed, we don't want this to cause any more work
3633 }
Marissa Wall61c58622018-07-18 10:12:20 -07003634 if (what & layer_state_t::eTransformChanged) {
3635 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3638 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3639 flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eCropChanged) {
3642 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3643 }
3644 if (what & layer_state_t::eBufferChanged) {
3645 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eAcquireFenceChanged) {
3648 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eDataspaceChanged) {
3651 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eHdrMetadataChanged) {
3654 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3657 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eApiChanged) {
3660 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3661 }
3662 if (what & layer_state_t::eSidebandStreamChanged) {
3663 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3664 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003665 return flags;
3666}
3667
chaviwca27f252018-02-06 16:46:39 -08003668void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3669 const layer_state_t& state = composerState.state;
3670 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3671
3672 sp<Layer> layer(client->getLayerUser(state.surface));
3673 if (layer == nullptr) {
3674 return;
3675 }
3676
3677 if (layer->isPendingRemoval()) {
3678 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3679 return;
3680 }
3681
3682 if (state.what & layer_state_t::eDestroySurface) {
3683 removeLayerLocked(mStateLock, layer);
3684 }
3685}
3686
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003688 const String8& name,
3689 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003691 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003692 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003694 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003695 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003696 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003697 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003698 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003699
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003700 status_t result = NO_ERROR;
3701
3702 sp<Layer> layer;
3703
Cody Northropbc755282017-03-31 12:00:08 -06003704 String8 uniqueName = getUniqueLayerName(name);
3705
Mathias Agopian3165cc22012-08-08 19:42:09 -07003706 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003707 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003708 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3709 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003712 case ISurfaceComposerClient::eFXSurfaceBufferState:
3713 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3714 break;
chaviw13fdc492017-06-27 12:40:18 -07003715 case ISurfaceComposerClient::eFXSurfaceColor:
3716 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003717 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003718 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 break;
3720 default:
3721 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003722 break;
3723 }
3724
Dan Stoza7d89d062015-04-30 13:29:25 -07003725 if (result != NO_ERROR) {
3726 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003728
Chia-I Wuab0c3192017-08-01 11:29:00 -07003729 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3730 // TODO b/64227542
3731 if (windowType == 441731) {
3732 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3733 layer->setPrimaryDisplayOnly();
3734 }
3735
Albert Chaulk479c60c2017-01-27 14:21:34 -05003736 layer->setInfo(windowType, ownerUid);
3737
Robert Carr1f0a16a2016-10-24 16:27:39 -07003738 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003739 if (result != NO_ERROR) {
3740 return result;
3741 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003742 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003743
3744 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746}
3747
Cody Northropbc755282017-03-31 12:00:08 -06003748String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3749{
3750 bool matchFound = true;
3751 uint32_t dupeCounter = 0;
3752
3753 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3754 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3755
Dan Stoza436ccf32018-06-21 12:10:12 -07003756 // Grab the state lock since we're accessing mCurrentState
3757 Mutex::Autolock lock(mStateLock);
3758
Cody Northropbc755282017-03-31 12:00:08 -06003759 // Loop over layers until we're sure there is no matching name
3760 while (matchFound) {
3761 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003762 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003763 if (layer->getName() == uniqueName) {
3764 matchFound = true;
3765 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3766 }
3767 });
3768 }
3769
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003770 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3771 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003772
3773 return uniqueName;
3774}
3775
Marissa Wallfd668622018-05-10 10:21:13 -07003776status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3777 uint32_t w, uint32_t h, uint32_t flags,
3778 PixelFormat& format, sp<IBinder>* handle,
3779 sp<IGraphicBufferProducer>* gbp,
3780 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003782 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 case PIXEL_FORMAT_TRANSPARENT:
3784 case PIXEL_FORMAT_TRANSLUCENT:
3785 format = PIXEL_FORMAT_RGBA_8888;
3786 break;
3787 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003788 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003789 break;
3790 }
3791
Marissa Wallfd668622018-05-10 10:21:13 -07003792 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3793 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003794 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003795 *handle = layer->getHandle();
3796 *gbp = layer->getProducer();
3797 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003799
Marissa Wallfd668622018-05-10 10:21:13 -07003800 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003801 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802}
3803
Marissa Wall61c58622018-07-18 10:12:20 -07003804status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3805 uint32_t w, uint32_t h, uint32_t flags,
3806 sp<IBinder>* handle, sp<Layer>* outLayer) {
3807 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3808 *handle = layer->getHandle();
3809 *outLayer = layer;
3810
3811 return NO_ERROR;
3812}
3813
chaviw13fdc492017-06-27 12:40:18 -07003814status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003815 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003816 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817{
chaviw13fdc492017-06-27 12:40:18 -07003818 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003820 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003821}
3822
Mathias Agopianac9fa422013-02-11 16:40:36 -08003823status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824{
Robert Carr9524cb32017-02-13 11:32:32 -08003825 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003826 status_t err = NO_ERROR;
3827 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003828 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003829 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003830 err = removeLayer(l);
3831 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3832 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003833 }
3834 return err;
3835}
3836
Mathias Agopian13127d82013-03-05 17:47:11 -08003837status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003838{
Mathias Agopian67106042013-03-14 19:18:13 -07003839 // called by ~LayerCleaner() when all references to the IBinder (handle)
3840 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003841 sp<Layer> l = layer.promote();
3842 if (l == nullptr) {
3843 // The layer has already been removed, carry on
3844 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003845 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003846 // If we have a parent, then we can continue to live as long as it does.
3847 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848}
3849
Mathias Agopianb60314a2012-04-10 22:09:54 -07003850// ---------------------------------------------------------------------------
3851
Andy McFadden13a082e2012-08-24 10:16:42 -07003852void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003853 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3854 if (!displayToken) return;
3855
Jesse Hall01e29052013-02-19 16:13:35 -08003856 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003857 Vector<ComposerState> state;
3858 Vector<DisplayState> displays;
3859 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003860 d.what = DisplayState::eDisplayProjectionChanged |
3861 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003862 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003863 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003864 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003865 d.frame.makeInvalid();
3866 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003867 d.width = 0;
3868 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003869 displays.add(d);
3870 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003871
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003872 const auto display = getDisplayDevice(displayToken);
3873 if (!display) return;
3874
3875 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3876
3877 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003878 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003879 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003880
Brian Andersond0010582017-03-07 13:20:31 -08003881 // Use phase of 0 since phase is not known.
3882 // Use latency of 0, which will snap to the ideal latency.
3883 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003884}
3885
3886void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003887 // Async since we may be called from the main thread.
3888 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003889}
3890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003891void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3892 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003893 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003895
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003896 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003898 return;
3899 }
3900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003901 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003902 ALOGW("Trying to set power mode for virtual display");
3903 return;
3904 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 display->setPowerMode(mode);
3907
Lloyd Pique4dccc412018-01-22 17:21:36 -08003908 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003909 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003910 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003911 if (idx < 0) {
3912 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3913 return;
3914 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003915 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003916 }
3917
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003918 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003919 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003920 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003921 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003922 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003923 // FIXME: eventthread only knows about the main display right now
3924 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003925 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003926 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003928 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003929 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003930 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003931
3932 struct sched_param param = {0};
3933 param.sched_priority = 1;
3934 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3935 ALOGW("Couldn't set SCHED_FIFO on display on");
3936 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003938 // Turn off the display
3939 struct sched_param param = {0};
3940 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3941 ALOGW("Couldn't set SCHED_OTHER on display off");
3942 }
3943
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003944 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003945 disableHardwareVsync(true); // also cancels any in-progress resync
3946
Mathias Agopiancde87a32012-09-13 14:09:01 -07003947 // FIXME: eventthread only knows about the main display right now
3948 mEventThread->onScreenReleased();
3949 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003951 getHwComposer().setPowerMode(type, mode);
3952 mVisibleRegionsDirty = true;
3953 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003954 } else if (mode == HWC_POWER_MODE_DOZE ||
3955 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003956 // Update display while dozing
3957 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003958 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003959 // FIXME: eventthread only knows about the main display right now
3960 mEventThread->onScreenAcquired();
3961 resyncToHardwareVsync(true);
3962 }
3963 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3964 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003965 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003966 disableHardwareVsync(true); // also cancels any in-progress resync
3967 // FIXME: eventthread only knows about the main display right now
3968 mEventThread->onScreenReleased();
3969 }
3970 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003971 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003972 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003973 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003975
3976 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003977}
3978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003980 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981 const auto display = getDisplayDevice(displayToken);
3982 if (!display) {
3983 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3984 displayToken.get());
3985 } else if (display->isVirtual()) {
3986 ALOGW("Attempt to set power mode %d for virtual display", mode);
3987 } else {
3988 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003989 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003991}
3992
3993// ---------------------------------------------------------------------------
3994
Lloyd Pique755e3192018-01-31 16:46:15 -08003995status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3996 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003998
Mathias Agopianbd115332013-04-18 16:41:04 -07003999 IPCThreadState* ipc = IPCThreadState::self();
4000 const int pid = ipc->getCallingPid();
4001 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004002
Mathias Agopianbd115332013-04-18 16:41:04 -07004003 if ((uid != AID_SHELL) &&
4004 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004005 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004006 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004008 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004009 // (this would indicate SF is stuck, but we want to be able to
4010 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004011 status_t err = mStateLock.timedLock(s2ns(1));
4012 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004013 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004014 result.appendFormat(
4015 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4016 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004017 }
4018
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004019 bool dumpAll = true;
4020 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004021 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004022
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004024 if ((index < numArgs) &&
4025 (args[index] == String16("--list"))) {
4026 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004027 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004028 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004029 }
4030
4031 if ((index < numArgs) &&
4032 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004033 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004034 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004035 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004036 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004037
4038 if ((index < numArgs) &&
4039 (args[index] == String16("--latency-clear"))) {
4040 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004041 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004042 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004043 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004044
4045 if ((index < numArgs) &&
4046 (args[index] == String16("--dispsync"))) {
4047 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004048 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004049 dumpAll = false;
4050 }
Dan Stozab90cf072015-03-05 11:05:59 -08004051
4052 if ((index < numArgs) &&
4053 (args[index] == String16("--static-screen"))) {
4054 index++;
4055 dumpStaticScreenStats(result);
4056 dumpAll = false;
4057 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004058
4059 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004060 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004061 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004062 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004063 dumpAll = false;
4064 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004065
4066 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4067 index++;
4068 dumpWideColorInfo(result);
4069 dumpAll = false;
4070 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004071
4072 if ((index < numArgs) &&
4073 (args[index] == String16("--enable-layer-stats"))) {
4074 index++;
4075 mLayerStats.enable();
4076 dumpAll = false;
4077 }
4078
4079 if ((index < numArgs) &&
4080 (args[index] == String16("--disable-layer-stats"))) {
4081 index++;
4082 mLayerStats.disable();
4083 dumpAll = false;
4084 }
4085
4086 if ((index < numArgs) &&
4087 (args[index] == String16("--clear-layer-stats"))) {
4088 index++;
4089 mLayerStats.clear();
4090 dumpAll = false;
4091 }
4092
4093 if ((index < numArgs) &&
4094 (args[index] == String16("--dump-layer-stats"))) {
4095 index++;
4096 mLayerStats.dump(result);
4097 dumpAll = false;
4098 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004099
4100 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004101 (args[index] == String16("--frame-composition"))) {
4102 index++;
4103 dumpFrameCompositionInfo(result);
4104 dumpAll = false;
4105 }
4106
4107 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004108 (args[index] == String16("--display-identification"))) {
4109 index++;
4110 dumpDisplayIdentificationData(result);
4111 dumpAll = false;
4112 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004113
4114 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4115 index++;
4116 mTimeStats.parseArgs(asProto, args, index, result);
4117 dumpAll = false;
4118 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004120
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004121 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004122 if (asProto) {
4123 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4124 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4125 } else {
4126 dumpAllLocked(args, index, result);
4127 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004128 }
4129
Mathias Agopian9795c422009-08-26 16:36:26 -07004130 if (locked) {
4131 mStateLock.unlock();
4132 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004133 }
4134 write(fd, result.string(), result.size());
4135 return NO_ERROR;
4136}
4137
Dan Stozac7014012014-02-14 15:03:43 -08004138void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4139 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004140{
Robert Carr2047fae2016-11-28 14:09:09 -08004141 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004142 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004143 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144}
4145
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004147 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148{
4149 String8 name;
4150 if (index < args.size()) {
4151 name = String8(args[index]);
4152 index++;
4153 }
4154
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004155 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4156 getHwComposer().isConnected(displayId)) {
4157 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4158 const nsecs_t period = activeConfig->getVsyncPeriod();
4159 result.appendFormat("%" PRId64 "\n", period);
4160 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004161
4162 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004163 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004164 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004166 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004167 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004168 }
Robert Carr2047fae2016-11-28 14:09:09 -08004169 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004170 }
4171}
4172
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004173void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004174 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004175{
4176 String8 name;
4177 if (index < args.size()) {
4178 name = String8(args[index]);
4179 index++;
4180 }
4181
Robert Carr2047fae2016-11-28 14:09:09 -08004182 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004183 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004184 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004185 }
Robert Carr2047fae2016-11-28 14:09:09 -08004186 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004187
Svetoslavd85084b2014-03-20 10:28:31 -07004188 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189}
4190
Jamie Gennis6547ff42013-07-16 20:12:42 -07004191// This should only be called from the main thread. Otherwise it would need
4192// the lock and should use mCurrentState rather than mDrawingState.
4193void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004195 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004196 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004197
4198 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4199}
4200
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004201void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004202{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004203 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004204
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004205 if (isLayerTripleBufferingDisabled())
4206 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004207
4208 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004209 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004210 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004211 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004212 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4213 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004214 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004215}
4216
Dan Stozab90cf072015-03-05 11:05:59 -08004217void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4218{
4219 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004220 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4221 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004222 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004223 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004224 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4225 b + 1, bucketTimeSec, percent);
4226 }
David Sodman4a36e932017-11-07 14:29:47 -08004227 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004228 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004229 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004230 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004231 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004232}
4233
Dan Stozae77c7662016-05-13 11:37:28 -07004234void SurfaceFlinger::recordBufferingStats(const char* layerName,
4235 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004236 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4237 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004238 for (const auto& segment : history) {
4239 if (!segment.usedThirdBuffer) {
4240 stats.twoBufferTime += segment.totalTime;
4241 }
4242 if (segment.occupancyAverage < 1.0f) {
4243 stats.doubleBufferedTime += segment.totalTime;
4244 } else if (segment.occupancyAverage < 2.0f) {
4245 stats.tripleBufferedTime += segment.totalTime;
4246 }
4247 ++stats.numSegments;
4248 stats.totalTime += segment.totalTime;
4249 }
4250}
4251
Brian Andersond6927fb2016-07-23 23:37:30 -07004252void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4253 result.appendFormat("Layer frame timestamps:\n");
4254
4255 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4256 const size_t count = currentLayers.size();
4257 for (size_t i=0 ; i<count ; i++) {
4258 currentLayers[i]->dumpFrameEvents(result);
4259 }
4260}
4261
Dan Stozae77c7662016-05-13 11:37:28 -07004262void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4263 result.append("Buffering stats:\n");
4264 result.append(" [Layer name] <Active time> <Two buffer> "
4265 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004266 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004267 typedef std::tuple<std::string, float, float, float> BufferTuple;
4268 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004269 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004270 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004271 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004272 if (stats.numSegments == 0) {
4273 continue;
4274 }
4275 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4276 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4277 stats.totalTime;
4278 float doubleBufferRatio = static_cast<float>(
4279 stats.doubleBufferedTime) / stats.totalTime;
4280 float tripleBufferRatio = static_cast<float>(
4281 stats.tripleBufferedTime) / stats.totalTime;
4282 sorted.insert({activeTime, {name, twoBufferRatio,
4283 doubleBufferRatio, tripleBufferRatio}});
4284 }
4285 for (const auto& sortedPair : sorted) {
4286 float activeTime = sortedPair.first;
4287 const BufferTuple& values = sortedPair.second;
4288 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4289 std::get<0>(values).c_str(), activeTime,
4290 std::get<1>(values), std::get<2>(values),
4291 std::get<3>(values));
4292 }
4293 result.append("\n");
4294}
4295
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004296void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004297 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004298 const int32_t displayId = display->getId();
4299 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4300 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004301 continue;
4302 }
4303
Dominik Laskowski7e045462018-05-30 13:02:02 -07004304 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004305 uint8_t port;
4306 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004307 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004308 result.append("no identification data\n");
4309 continue;
4310 }
4311
4312 if (!isEdid(data)) {
4313 result.append("unknown identification data: ");
4314 for (uint8_t byte : data) {
4315 result.appendFormat("%x ", byte);
4316 }
4317 result.append("\n");
4318 continue;
4319 }
4320
4321 const auto edid = parseEdid(data);
4322 if (!edid) {
4323 result.append("invalid EDID: ");
4324 for (uint8_t byte : data) {
4325 result.appendFormat("%x ", byte);
4326 }
4327 result.append("\n");
4328 continue;
4329 }
4330
4331 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4332 result.append(edid->displayName.data(), edid->displayName.length());
4333 result.append("\"\n");
4334 }
4335 result.append("\n");
4336}
4337
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004338void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004339 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4340 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004341 result.appendFormat("DisplayColorSetting: %s\n",
4342 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004343
4344 // TODO: print out if wide-color mode is active or not
4345
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004346 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004347 const int32_t displayId = display->getId();
4348 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004349 continue;
4350 }
4351
Dominik Laskowski7e045462018-05-30 13:02:02 -07004352 result.appendFormat("Display %d color modes:\n", displayId);
4353 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354 for (auto&& mode : modes) {
4355 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4356 }
4357
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004358 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359 result.appendFormat(" Current color mode: %s (%d)\n",
4360 decodeColorMode(currentMode).c_str(), currentMode);
4361 }
4362 result.append("\n");
4363}
4364
David Sodman7e4ae112018-02-09 15:02:28 -08004365void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4366 std::string stringResult;
4367
4368 for (const auto& [token, display] : mDisplays) {
4369 const auto displayId = display->getId();
4370 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4371 continue;
4372 }
4373
4374 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4375 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4376 break;
4377 }
4378 const auto& compositionInfoList = compositionInfoIt->second;
4379 stringResult += base::StringPrintf("Display: %d\n", displayId);
4380 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4381 for (const auto& compositionInfo : compositionInfoList) {
4382 compositionInfo.dump(stringResult, nullptr);
4383 stringResult += base::StringPrintf("\n");
4384 }
4385 }
4386
4387 result.append(stringResult.c_str());
4388}
4389
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004390LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004391 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004392 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4393 const State& state = useDrawing ? mDrawingState : mCurrentState;
4394 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004395 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004396 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004397 });
4398
4399 return layersProto;
4400}
4401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004402LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004403 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004404
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004405 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004406 resolution->set_w(display.getWidth());
4407 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004409 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4410 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4411 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004412
Dominik Laskowski7e045462018-05-30 13:02:02 -07004413 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004414 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004415 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 }
4419 });
4420
4421 return layersProto;
4422}
4423
Mathias Agopian74d211a2013-04-22 16:55:35 +02004424void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4425 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004427 bool colorize = false;
4428 if (index < args.size()
4429 && (args[index] == String16("--color"))) {
4430 colorize = true;
4431 index++;
4432 }
4433
4434 Colorizer colorizer(colorize);
4435
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004436 // figure out if we're stuck somewhere
4437 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4440
4441 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004442 * Dump library configuration.
4443 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444
4445 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004446 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004447 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004448 appendSfConfigString(result);
4449 appendUiConfigString(result);
4450 appendGuiConfigString(result);
4451 result.append("\n");
4452
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004453 result.append("\nDisplay identification data:\n");
4454 dumpDisplayIdentificationData(result);
4455
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004456 result.append("\nWide-Color information:\n");
4457 dumpWideColorInfo(result);
4458
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004459 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004460 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004461 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004462 result.append(SyncFeatures::getInstance().toString());
4463 result.append("\n");
4464
Andy McFadden41d67d72014-04-25 16:58:34 -07004465 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004466 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004467 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004468
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004469 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4470 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004471 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4472 getHwComposer().isConnected(displayId)) {
4473 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004474 result.appendFormat("Display %d: "
4475 "app phase %" PRId64 " ns, "
4476 "sf phase %" PRId64 " ns, "
4477 "early app phase %" PRId64 " ns, "
4478 "early sf phase %" PRId64 " ns, "
4479 "early app gl phase %" PRId64 " ns, "
4480 "early sf gl phase %" PRId64 " ns, "
4481 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4482 displayId,
4483 vsyncPhaseOffsetNs,
4484 sfVsyncPhaseOffsetNs,
4485 appEarlyOffset,
4486 sfEarlyOffset,
4487 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004488 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004489 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004490 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004491 result.append("\n");
4492
Dan Stozab90cf072015-03-05 11:05:59 -08004493 // Dump static screen stats
4494 result.append("\n");
4495 dumpStaticScreenStats(result);
4496 result.append("\n");
4497
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004498 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4499
Dan Stozae77c7662016-05-13 11:37:28 -07004500 dumpBufferingStats(result);
4501
Andy McFadden4803b742012-09-24 19:07:20 -07004502 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503 * Dump the visible layer list
4504 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004505 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004506 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004507 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4508 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004509 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004510
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004511 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004512 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004513 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004514 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004515
David Sodman7e4ae112018-02-09 15:02:28 -08004516 result.append("\nFrame-Composition information:\n");
4517 dumpFrameCompositionInfo(result);
4518 result.append("\n");
4519
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004520 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004521 * Dump Display state
4522 */
4523
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004525 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004527 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004529 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004530 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004531
4532 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 * Dump SurfaceFlinger global state
4534 */
4535
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004537 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004539
Mathias Agopian888c8222012-08-04 21:10:38 -07004540 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004541 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004542
David Sodmanbc815282017-11-05 18:57:52 -08004543 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 if (display) {
4546 display->undefinedRegion.dump(result, "undefinedRegion");
4547 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4548 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004549 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004550 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004551 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004552 mTransactionFlags, !mGpuToCpuSupported);
4553
4554 if (display) {
4555 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4556 result.appendFormat(" refresh-rate : %f fps\n"
4557 " x-dpi : %f\n"
4558 " y-dpi : %f\n",
4559 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4560 activeConfig->getDpiY());
4561 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004562
Mathias Agopian74d211a2013-04-22 16:55:35 +02004563 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004564 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565
4566 /*
4567 * VSYNC state
4568 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004569 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004570 result.append("\n");
4571
4572 /*
4573 * HWC layer minidump
4574 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004575 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004576 const int32_t displayId = display->getId();
4577 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004578 continue;
4579 }
4580
Dominik Laskowski7e045462018-05-30 13:02:02 -07004581 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004582 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004584 result.append("\n");
4585 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586
4587 /*
4588 * Dump HWComposer state
4589 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004590 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004591 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004592 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004593 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004594 result.appendFormat(" h/w composer %s\n",
4595 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004596 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597
4598 /*
4599 * Dump gralloc state
4600 */
4601 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4602 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004603
4604 /*
4605 * Dump VrFlinger state if in use.
4606 */
4607 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4608 result.append("VrFlinger state:\n");
4609 result.append(mVrFlinger->Dump().c_str());
4610 result.append("\n");
4611 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612}
4613
Dominik Laskowski7e045462018-05-30 13:02:02 -07004614const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004615 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004616 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004617 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004618 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004619 }
4620 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004621
4622 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4623 static const Vector<sp<Layer>> empty;
4624 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004625}
4626
Keun young Park63f165f2012-08-31 10:53:36 -07004627bool SurfaceFlinger::startDdmConnection()
4628{
4629 void* libddmconnection_dso =
4630 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4631 if (!libddmconnection_dso) {
4632 return false;
4633 }
4634 void (*DdmConnection_start)(const char* name);
4635 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004636 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004637 if (!DdmConnection_start) {
4638 dlclose(libddmconnection_dso);
4639 return false;
4640 }
4641 (*DdmConnection_start)(getServiceName());
4642 return true;
4643}
4644
Chia-I Wu28f320b2018-05-03 11:02:56 -07004645void SurfaceFlinger::updateColorMatrixLocked() {
4646 mat4 colorMatrix;
4647 if (mGlobalSaturationFactor != 1.0f) {
4648 // Rec.709 luma coefficients
4649 float3 luminance{0.213f, 0.715f, 0.072f};
4650 luminance *= 1.0f - mGlobalSaturationFactor;
4651 mat4 saturationMatrix = mat4(
4652 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4653 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4654 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4655 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4656 );
4657 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4658 } else {
4659 colorMatrix = mClientColorMatrix * mDaltonizer();
4660 }
4661
4662 if (mCurrentState.colorMatrix != colorMatrix) {
4663 mCurrentState.colorMatrix = colorMatrix;
4664 mCurrentState.colorMatrixChanged = true;
4665 setTransactionFlags(eTransactionNeeded);
4666 }
4667}
4668
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004669status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670#pragma clang diagnostic push
4671#pragma clang diagnostic error "-Wswitch-enum"
4672 switch (static_cast<ISurfaceComposerTag>(code)) {
4673 // These methods should at minimum make sure that the client requested
4674 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004675 case BOOT_FINISHED:
4676 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677 case CREATE_CONNECTION:
4678 case CREATE_DISPLAY:
4679 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004680 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004681 case GET_ACTIVE_COLOR_MODE:
4682 case GET_ANIMATION_FRAME_STATS:
4683 case GET_HDR_CAPABILITIES:
4684 case SET_ACTIVE_CONFIG:
4685 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004686 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004687 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004688 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4689 IPCThreadState* ipc = IPCThreadState::self();
4690 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4691 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004692 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 }
Robert Carr1db73f62016-12-21 12:58:51 -08004694 return OK;
4695 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004697 IPCThreadState* ipc = IPCThreadState::self();
4698 const int pid = ipc->getCallingPid();
4699 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4701 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004702 return PERMISSION_DENIED;
4703 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004706 // Used by apps to hook Choreographer to SurfaceFlinger.
4707 case CREATE_DISPLAY_EVENT_CONNECTION:
4708 // The following calls are currently used by clients that do not
4709 // request necessary permissions. However, they do not expose any secret
4710 // information, so it is OK to pass them.
4711 case AUTHENTICATE_SURFACE:
4712 case GET_ACTIVE_CONFIG:
4713 case GET_BUILT_IN_DISPLAY:
4714 case GET_DISPLAY_COLOR_MODES:
4715 case GET_DISPLAY_CONFIGS:
4716 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004717 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4719 // Calling setTransactionState is safe, because you need to have been
4720 // granted a reference to Client* and Handle* to do anything with it.
4721 case SET_TRANSACTION_STATE:
4722 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4723 case CREATE_SCOPED_CONNECTION: {
4724 return OK;
4725 }
4726 case CAPTURE_LAYERS:
4727 case CAPTURE_SCREEN: {
4728 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004729 IPCThreadState* ipc = IPCThreadState::self();
4730 const int pid = ipc->getCallingPid();
4731 const int uid = ipc->getCallingUid();
4732 if ((uid != AID_GRAPHICS) &&
4733 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4734 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4735 return PERMISSION_DENIED;
4736 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 return OK;
4738 }
4739 // The following codes are deprecated and should never be allowed to access SF.
4740 case CONNECT_DISPLAY_UNUSED:
4741 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4742 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4743 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004745 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004746
4747 // These codes are used for the IBinder protocol to either interrogate the recipient
4748 // side of the transaction for its canonical interface descriptor or to dump its state.
4749 // We let them pass by default.
4750 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4751 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4752 code == IBinder::SYSPROPS_TRANSACTION) {
4753 return OK;
4754 }
4755 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4756 // in onTransact verifies that the user is root, and has access to use SF.
4757 if (code >= 1000 && code <= 1029) {
4758 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4759 return OK;
4760 }
4761 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4762 return PERMISSION_DENIED;
4763#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004764}
4765
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4767 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004768 status_t credentialCheck = CheckTransactCodeCredentials(code);
4769 if (credentialCheck != OK) {
4770 return credentialCheck;
4771 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4774 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004775 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004776 IPCThreadState* ipc = IPCThreadState::self();
4777 const int uid = ipc->getCallingUid();
4778 if (CC_UNLIKELY(uid != AID_SYSTEM
4779 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004780 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004781 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004782 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 return PERMISSION_DENIED;
4784 }
4785 int n;
4786 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004787 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004788 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 return NO_ERROR;
4790 case 1002: // SHOW_UPDATES
4791 n = data.readInt32();
4792 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004793 invalidateHwcGeometry();
4794 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004797 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004798 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004800 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004801 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004802 setTransactionFlags(
4803 eTransactionNeeded|
4804 eDisplayTransactionNeeded|
4805 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004806 return NO_ERROR;
4807 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004808 case 1006:{ // send empty update
4809 signalRefresh();
4810 return NO_ERROR;
4811 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004812 case 1008: // toggle use of hw composer
4813 n = data.readInt32();
4814 mDebugDisableHWC = n ? 1 : 0;
4815 invalidateHwcGeometry();
4816 repaintEverything();
4817 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004818 case 1009: // toggle use of transform hint
4819 n = data.readInt32();
4820 mDebugDisableTransformHint = n ? 1 : 0;
4821 invalidateHwcGeometry();
4822 repaintEverything();
4823 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004825 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004826 reply->writeInt32(0);
4827 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004828 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004829 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 return NO_ERROR;
4831 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004832 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004833 if (!display) {
4834 return NAME_NOT_FOUND;
4835 }
4836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004838 return NO_ERROR;
4839 }
4840 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004841 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004842 // daltonize
4843 n = data.readInt32();
4844 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004845 case 1:
4846 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4847 break;
4848 case 2:
4849 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4850 break;
4851 case 3:
4852 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4853 break;
4854 default:
4855 mDaltonizer.setType(ColorBlindnessType::None);
4856 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004857 }
4858 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004859 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004860 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004861 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004862 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004863
4864 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004867 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004868 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004869 // apply a color matrix
4870 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004871 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004872 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004873 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004875 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004876 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004878 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004879 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004880 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004881
4882 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4883 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004884 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004885 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4886 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4887 }
4888
Chia-I Wu28f320b2018-05-03 11:02:56 -07004889 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004890 return NO_ERROR;
4891 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004892 // This is an experimental interface
4893 // Needs to be shifted to proper binder interface when we productize
4894 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004895 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004896 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004897 return NO_ERROR;
4898 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004899 case 1017: {
4900 n = data.readInt32();
4901 mForceFullDamage = static_cast<bool>(n);
4902 return NO_ERROR;
4903 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004904 case 1018: { // Modify Choreographer's phase offset
4905 n = data.readInt32();
4906 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4907 return NO_ERROR;
4908 }
4909 case 1019: { // Modify SurfaceFlinger's phase offset
4910 n = data.readInt32();
4911 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4912 return NO_ERROR;
4913 }
Irvel468051e2016-06-13 16:44:44 -07004914 case 1020: { // Layer updates interceptor
4915 n = data.readInt32();
4916 if (n) {
4917 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004918 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004919 }
4920 else{
4921 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004922 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004923 }
4924 return NO_ERROR;
4925 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004926 case 1021: { // Disable HWC virtual displays
4927 n = data.readInt32();
4928 mUseHwcVirtualDisplays = !n;
4929 return NO_ERROR;
4930 }
Romain Guy0147a172017-06-01 13:53:56 -07004931 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004932 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004933 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004934
Chia-I Wu28f320b2018-05-03 11:02:56 -07004935 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004936 return NO_ERROR;
4937 }
Romain Guy54f154a2017-10-24 21:40:32 +01004938 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004939 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004940 invalidateHwcGeometry();
4941 repaintEverything();
4942 return NO_ERROR;
4943 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004944 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4945 // deprecate 1024 if they can.
4946 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004947 reply->writeBool(hasWideColorDisplay);
4948 return NO_ERROR;
4949 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004950 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004951 n = data.readInt32();
4952 if (n) {
4953 ALOGV("LayerTracing enabled");
4954 mTracing.enable();
4955 doTracing("tracing.enable");
4956 reply->writeInt32(NO_ERROR);
4957 } else {
4958 ALOGV("LayerTracing disabled");
4959 status_t err = mTracing.disable();
4960 reply->writeInt32(err);
4961 }
4962 return NO_ERROR;
4963 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004964 case 1026: { // Get layer tracing status
4965 reply->writeBool(mTracing.isEnabled());
4966 return NO_ERROR;
4967 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004968 // Is a DisplayColorSetting supported?
4969 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004970 const auto display = getDefaultDisplayDevice();
4971 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004972 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004973 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004974
4975 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4976 switch (setting) {
4977 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004978 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004979 break;
4980 case DisplayColorSetting::UNMANAGED:
4981 reply->writeBool(true);
4982 break;
4983 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004984 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004985 break;
4986 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004987 reply->writeBool(
4988 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004989 break;
4990 }
4991 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004992 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004993 // Is VrFlinger active?
4994 case 1028: {
4995 Mutex::Autolock _l(mStateLock);
4996 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4997 return NO_ERROR;
4998 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004999 case 1029: {
5000 // Code 1029 is an experimental feature that allows applications to
5001 // simulate a high frequency panel by setting a multiplier and divisor
5002 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005003 // 0, then the code simply return the current multiplier and divisor.
5004 HWC2::Device::FrequencyScaler frequencyScaler;
5005 frequencyScaler.multiplier = data.readInt32();
5006 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005007
David Sodman44b5de02018-08-21 16:28:53 -07005008 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5009 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5010 reply->writeInt32(frequencyScaler.multiplier);
5011 reply->writeInt32(frequencyScaler.divisor);
5012 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005013 }
5014
David Sodman44b5de02018-08-21 16:28:53 -07005015 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005016 enableHardwareVsync();
5017 } else {
5018 disableHardwareVsync(true);
5019 }
David Sodman44b5de02018-08-21 16:28:53 -07005020 mPrimaryDispSync->scalePeriod(frequencyScaler);
5021 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005022
David Sodman44b5de02018-08-21 16:28:53 -07005023 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5024 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5025
5026 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5027 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5028
5029 onHotplugReceived(getBE().mComposerSequenceId,
5030 hwcDisplayId, HWC2::Connection::Disconnected);
5031 onHotplugReceived(getBE().mComposerSequenceId,
5032 hwcDisplayId, HWC2::Connection::Connected);
5033 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5034 reply->writeInt32(frequencyScaler.multiplier);
5035 reply->writeInt32(frequencyScaler.divisor);
5036
David Sodman6d46c1e2018-07-13 12:59:48 -07005037 return NO_ERROR;
5038 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005039 // Is device color managed?
5040 case 1030: {
5041 reply->writeBool(useColorManagement);
5042 return NO_ERROR;
5043 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 }
5045 }
5046 return err;
5047}
5048
Steven Thomas6d8110b2017-08-31 18:24:21 -07005049void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005050 android_atomic_or(1, &mRepaintEverything);
5051 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005052}
5053
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5055class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005056public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005057 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5058 ~WindowDisconnector() {
5059 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005060 }
5061
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005062private:
5063 ANativeWindow* mWindow;
5064 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005065};
5066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005067status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5068 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5069 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5070 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005071 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005072 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005075
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005076 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5077
Chia-I Wu20261cb2018-08-23 12:55:44 -07005078 sp<DisplayDevice> display;
5079 {
5080 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005081
Chia-I Wu20261cb2018-08-23 12:55:44 -07005082 display = getDisplayDeviceLocked(displayToken);
5083 if (!display) return BAD_VALUE;
5084
Chia-I Wucb023152018-08-28 12:57:23 -07005085 // set the source crop to the (projected) logical display viewport
5086 // unconditionally until the framework is fixed
5087 sourceCrop.set(display->getScissor());
5088
5089 // set the requested width/height to the logical display viewport size
5090 // by default
5091 if (reqWidth == 0 || reqHeight == 0) {
5092 reqWidth = uint32_t(display->getViewport().width());
5093 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005094 }
5095
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005096 // XXX primaryDisplayOrientation is ignored
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005097 }
5098
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005099 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005100
5101 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005102 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005103 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005104}
5105
5106status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005107 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005108 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005109 ATRACE_CALL();
5110
5111 class LayerRenderArea : public RenderArea {
5112 public:
Robert Carr578038f2018-03-09 12:25:24 -08005113 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5114 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005115 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005116 mLayer(layer),
5117 mCrop(crop),
5118 mFlinger(flinger),
5119 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005120 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005121 Rect getBounds() const override {
5122 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005123 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005124 }
Marissa Wall61c58622018-07-18 10:12:20 -07005125 int getHeight() const override {
5126 return mLayer->getActiveHeight(mLayer->getDrawingState());
5127 }
5128 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005129 bool isSecure() const override { return false; }
5130 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005131 Rect getSourceCrop() const override {
5132 if (mCrop.isEmpty()) {
5133 return getBounds();
5134 } else {
5135 return mCrop;
5136 }
5137 }
Robert Carr578038f2018-03-09 12:25:24 -08005138 class ReparentForDrawing {
5139 public:
5140 const sp<Layer>& oldParent;
5141 const sp<Layer>& newParent;
5142
5143 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5144 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005145 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005146 }
Robert Carr15eae092018-03-23 13:43:53 -07005147 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005148 };
5149
5150 void render(std::function<void()> drawLayers) override {
5151 if (!mChildrenOnly) {
5152 mTransform = mLayer->getTransform().inverse();
5153 drawLayers();
5154 } else {
5155 Rect bounds = getBounds();
5156 screenshotParentLayer =
5157 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5158 bounds.getWidth(), bounds.getHeight(), 0);
5159
5160 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5161 drawLayers();
5162 }
5163 }
chaviwa76b2712017-09-20 12:02:26 -07005164
chaviwa76b2712017-09-20 12:02:26 -07005165 private:
chaviw7206d492017-11-10 16:16:12 -08005166 const sp<Layer> mLayer;
5167 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005168
5169 // In the "childrenOnly" case we reparent the children to a screenshot
5170 // layer which has no properties set and which does not draw.
5171 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005172 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08005173
5174 SurfaceFlinger* mFlinger;
5175 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005176 };
5177
5178 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5179 auto parent = layerHandle->owner.promote();
5180
chaviw7206d492017-11-10 16:16:12 -08005181 if (parent == nullptr || parent->isPendingRemoval()) {
5182 ALOGE("captureLayers called with a removed parent");
5183 return NAME_NOT_FOUND;
5184 }
5185
Robert Carr578038f2018-03-09 12:25:24 -08005186 const int uid = IPCThreadState::self()->getCallingUid();
5187 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5188 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5189 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5190 return PERMISSION_DENIED;
5191 }
5192
chaviw7206d492017-11-10 16:16:12 -08005193 Rect crop(sourceCrop);
5194 if (sourceCrop.width() <= 0) {
5195 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005196 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005197 }
5198
5199 if (sourceCrop.height() <= 0) {
5200 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005201 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005202 }
5203
5204 int32_t reqWidth = crop.width() * frameScale;
5205 int32_t reqHeight = crop.height() * frameScale;
5206
Chia-I Wu20261cb2018-08-23 12:55:44 -07005207 // really small crop or frameScale
5208 if (reqWidth <= 0) {
5209 reqWidth = 1;
5210 }
5211 if (reqHeight <= 0) {
5212 reqHeight = 1;
5213 }
5214
Robert Carr578038f2018-03-09 12:25:24 -08005215 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005216
Robert Carr578038f2018-03-09 12:25:24 -08005217 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005218 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5219 if (!layer->isVisible()) {
5220 return;
Robert Carr578038f2018-03-09 12:25:24 -08005221 } else if (childrenOnly && layer == parent.get()) {
5222 return;
chaviwa76b2712017-09-20 12:02:26 -07005223 }
5224 visitor(layer);
5225 });
5226 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005227 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005228}
5229
5230status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5231 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005232 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005233 bool useIdentityTransform) {
5234 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005235
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005236 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5237 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5238 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5239 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240
5241 // This mutex protects syncFd and captureResult for communication of the return values from the
5242 // main thread back to this Binder thread
5243 std::mutex captureMutex;
5244 std::condition_variable captureCondition;
5245 std::unique_lock<std::mutex> captureLock(captureMutex);
5246 int syncFd = -1;
5247 std::optional<status_t> captureResult;
5248
Robert Carr03480e22018-01-04 16:02:06 -08005249 const int uid = IPCThreadState::self()->getCallingUid();
5250 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5251
Dominik Laskowski8c001672018-05-30 16:52:06 -07005252 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005253 // If there is a refresh pending, bug out early and tell the binder thread to try again
5254 // after the refresh.
5255 if (mRefreshPending) {
5256 ATRACE_NAME("Skipping screenshot for now");
5257 std::unique_lock<std::mutex> captureLock(captureMutex);
5258 captureResult = std::make_optional<status_t>(EAGAIN);
5259 captureCondition.notify_one();
5260 return;
5261 }
5262
5263 status_t result = NO_ERROR;
5264 int fd = -1;
5265 {
5266 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005267 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005268 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5269 useIdentityTransform, forSystem, &fd);
5270 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005271 }
5272
5273 {
5274 std::unique_lock<std::mutex> captureLock(captureMutex);
5275 syncFd = fd;
5276 captureResult = std::make_optional<status_t>(result);
5277 captureCondition.notify_one();
5278 }
5279 });
5280
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005281 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005282 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005283 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005284 while (*captureResult == EAGAIN) {
5285 captureResult.reset();
5286 result = postMessageAsync(message);
5287 if (result != NO_ERROR) {
5288 return result;
5289 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005290 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005291 }
5292 result = *captureResult;
5293 }
5294
5295 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005296 sync_wait(syncFd, -1);
5297 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005298 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005299
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005300 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005301}
5302
chaviwa76b2712017-09-20 12:02:26 -07005303void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5304 TraverseLayersFunction traverseLayers, bool yswap,
5305 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005306 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005307
Lloyd Pique144e1162017-12-20 16:44:52 -08005308 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005309
5310 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005311 const auto raWidth = renderArea.getWidth();
5312 const auto raHeight = renderArea.getHeight();
5313
5314 const auto reqWidth = renderArea.getReqWidth();
5315 const auto reqHeight = renderArea.getReqHeight();
5316 Rect sourceCrop = renderArea.getSourceCrop();
5317
Iris Chang7501ed62018-04-30 14:45:42 +08005318 bool filtering = false;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005319 if (primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +08005320 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5321 static_cast<int32_t>(reqHeight) != raWidth;
5322 } else {
5323 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5324 static_cast<int32_t>(reqHeight) != raHeight;
5325 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005326
Dan Stozac1879002014-05-22 15:59:05 -07005327 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005328 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005329 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005330 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005331 } else if (primaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005332 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005333 uint32_t flags = 0x00;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005334 switch (primaryDisplayOrientation) {
Iris Chang7501ed62018-04-30 14:45:42 +08005335 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005336 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005337 break;
5338 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005339 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005340 break;
5341 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005342 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005343 break;
5344 }
5345 tr.set(flags, raWidth, raHeight);
5346 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005347 }
5348
Chia-I Wu36574d92018-05-16 10:54:36 -07005349 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5350 engine.setOutputDataSpace(Dataspace::SRGB);
5351 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005352
Mathias Agopian180f10d2013-04-10 22:55:41 -07005353 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005354 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005355
Peiyong Linefefaac2018-08-17 12:27:51 -07005356 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005357 if (primaryDisplayOrientation != DisplayState::eOrientationDefault) {
Iris Chang7501ed62018-04-30 14:45:42 +08005358 // convert hw orientation into flag presentation
5359 // here inverse transform needed
5360 uint8_t hw_rot_90 = 0x00;
5361 uint8_t hw_flip_hv = 0x00;
Chia-I Wu304d9cd2018-08-27 14:38:14 -07005362 switch (primaryDisplayOrientation) {
Iris Chang7501ed62018-04-30 14:45:42 +08005363 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005364 hw_rot_90 = ui::Transform::ROT_90;
5365 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005366 break;
5367 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005368 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005369 break;
5370 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005371 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005372 break;
5373 }
5374
5375 // transform flags operation
5376 // 1) flip H V if both have ROT_90 flag
5377 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005378 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5379 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005380 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005381 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005382 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005383 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005384 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5385 }
5386
Mathias Agopian180f10d2013-04-10 22:55:41 -07005387 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005388 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005389 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005390 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005391
chaviw50da5042018-04-09 13:49:37 -07005392 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005393 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005394 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005395
chaviwa76b2712017-09-20 12:02:26 -07005396 traverseLayers([&](Layer* layer) {
5397 if (filtering) layer->setFiltering(true);
David Sodmanfb95bcc2017-12-22 15:45:30 -08005398 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005399 if (filtering) layer->setFiltering(false);
5400 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005401}
5402
chaviwa76b2712017-09-20 12:02:26 -07005403status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5404 TraverseLayersFunction traverseLayers,
5405 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005406 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005407 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005408 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005409 ATRACE_CALL();
5410
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005411 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005412
5413 traverseLayers([&](Layer* layer) {
5414 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5415 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005416
Robert Carr03480e22018-01-04 16:02:06 -08005417 // We allow the system server to take screenshots of secure layers for
5418 // use in situations like the Screen-rotation animation and place
5419 // the impetus on WindowManager to not persist them.
5420 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005421 ALOGW("FB is protected: PERMISSION_DENIED");
5422 return PERMISSION_DENIED;
5423 }
5424
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005425 // this binds the given EGLImage as a framebuffer for the
5426 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005427 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005428 if (bufferBond.getStatus() != NO_ERROR) {
5429 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005430 return INVALID_OPERATION;
5431 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005432
Dan Stozaabcda352017-06-01 14:37:39 -07005433 // this will in fact render into our dequeued buffer
5434 // via an FBO, which means we didn't have to create
5435 // an EGLSurface and therefore we're not
5436 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005437 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005438
Dan Stozaabcda352017-06-01 14:37:39 -07005439 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005440 getRenderEngine().finish();
5441 *outSyncFd = -1;
5442
chaviwa76b2712017-09-20 12:02:26 -07005443 const auto reqWidth = renderArea.getReqWidth();
5444 const auto reqHeight = renderArea.getReqHeight();
5445
Dan Stozaabcda352017-06-01 14:37:39 -07005446 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5447 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005448 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005449 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005450 } else {
5451 base::unique_fd syncFd = getRenderEngine().flush();
5452 if (syncFd < 0) {
5453 getRenderEngine().finish();
5454 }
5455 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005456 }
5457
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005458 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005459}
5460
Mathias Agopiand5556842013-09-19 17:08:37 -07005461void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005462 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005463 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005464 for (size_t y = 0; y < h; y++) {
5465 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5466 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005467 if (p[x] != 0xFF000000) return;
5468 }
5469 }
chaviwa76b2712017-09-20 12:02:26 -07005470 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005471
Robert Carr2047fae2016-11-28 14:09:09 -08005472 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005473 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005474 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005475 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5476 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5477 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5478 static_cast<float>(state.color.a));
5479 i++;
5480 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005481 }
5482}
5483
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005484// ---------------------------------------------------------------------------
5485
Dan Stoza412903f2017-04-27 13:42:17 -07005486void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5487 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005488}
5489
Dan Stoza412903f2017-04-27 13:42:17 -07005490void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5491 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005492}
5493
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005494void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5495 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005496 const LayerVector::Visitor& visitor) {
5497 // We loop through the first level of layers without traversing,
5498 // as we need to interpret min/max layer Z in the top level Z space.
5499 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005500 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005501 continue;
5502 }
5503 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005504 // relative layers are traversed in Layer::traverseInZOrder
5505 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005506 continue;
5507 }
5508 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005509 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005510 return;
5511 }
chaviwa76b2712017-09-20 12:02:26 -07005512 if (!layer->isVisible()) {
5513 return;
5514 }
5515 visitor(layer);
5516 });
5517 }
5518}
5519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005520}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005521
Lloyd Pique074e8122018-07-26 12:57:23 -07005522
Mathias Agopian3f844832013-08-07 21:24:32 -07005523#if defined(__gl_h_)
5524#error "don't include gl/gl.h in this file"
5525#endif
5526
5527#if defined(__gl2_h_)
5528#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005529#endif