blob: baefb158b99fc9e366c53f5b948d746672705e0e [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
Alec Mouri79108df2019-02-04 19:33:44 +000017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800123using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700124using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700125using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800126using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700127using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700128using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900129
Steven Thomasb02664d2017-07-26 18:48:28 -0700130namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700131
132#pragma clang diagnostic push
133#pragma clang diagnostic error "-Wswitch-enum"
134
135bool isWideColorMode(const ColorMode colorMode) {
136 switch (colorMode) {
137 case ColorMode::DISPLAY_P3:
138 case ColorMode::ADOBE_RGB:
139 case ColorMode::DCI_P3:
140 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700141 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700142 case ColorMode::BT2100_PQ:
143 case ColorMode::BT2100_HLG:
144 return true;
145 case ColorMode::NATIVE:
146 case ColorMode::STANDARD_BT601_625:
147 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
148 case ColorMode::STANDARD_BT601_525:
149 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
150 case ColorMode::STANDARD_BT709:
151 case ColorMode::SRGB:
152 return false;
153 }
154 return false;
155}
156
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700157ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
158 switch (rotation) {
159 case ISurfaceComposer::eRotateNone:
160 return ui::Transform::ROT_0;
161 case ISurfaceComposer::eRotate90:
162 return ui::Transform::ROT_90;
163 case ISurfaceComposer::eRotate180:
164 return ui::Transform::ROT_180;
165 case ISurfaceComposer::eRotate270:
166 return ui::Transform::ROT_270;
167 }
168 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
169 return ui::Transform::ROT_0;
170}
171
Peiyong Linfca547f2018-07-09 13:03:33 -0700172#pragma clang diagnostic pop
173
Steven Thomasb02664d2017-07-26 18:48:28 -0700174class ConditionalLock {
175public:
176 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
177 if (lock) {
178 mMutex.lock();
179 }
180 }
181 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
182private:
183 Mutex& mMutex;
184 bool mLocked;
185};
Peiyong Linfca547f2018-07-09 13:03:33 -0700186
Peiyong Lin9d846a52018-11-05 13:18:20 -0800187// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
188bool validateCompositionDataspace(Dataspace dataspace) {
189 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
190}
191
Steven Thomasb02664d2017-07-26 18:48:28 -0700192} // namespace anonymous
193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194// ---------------------------------------------------------------------------
195
Mathias Agopian99b49842011-06-27 16:05:52 -0700196const String16 sHardwareTest("android.permission.HARDWARE_TEST");
197const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
198const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
199const String16 sDump("android.permission.DUMP");
200
Daniel Solomon42d04562019-01-20 21:03:19 -0800201constexpr float kSrgbRedX = 0.4123f;
202constexpr float kSrgbRedY = 0.2126f;
203constexpr float kSrgbRedZ = 0.0193f;
204constexpr float kSrgbGreenX = 0.3576f;
205constexpr float kSrgbGreenY = 0.7152f;
206constexpr float kSrgbGreenZ = 0.1192f;
207constexpr float kSrgbBlueX = 0.1805f;
208constexpr float kSrgbBlueY = 0.0722f;
209constexpr float kSrgbBlueZ = 0.9506f;
210constexpr float kSrgbWhiteX = 0.9505f;
211constexpr float kSrgbWhiteY = 1.0000f;
212constexpr float kSrgbWhiteZ = 1.0891f;
213
Mathias Agopian99b49842011-06-27 16:05:52 -0700214// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700215int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700216bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800218bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800219bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800220int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600221bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700222int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700223bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700224bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700225Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
226ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
227Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
228ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700229
Kalle Raitaa099a242017-01-11 11:17:29 -0800230std::string getHwcServiceName() {
231 char value[PROPERTY_VALUE_MAX] = {};
232 property_get("debug.sf.hwc_service_name", value, "default");
233 ALOGI("Using HWComposer service: '%s'", value);
234 return std::string(value);
235}
236
237bool useTrebleTestingOverride() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.treble_testing_override", value, "false");
240 ALOGI("Treble testing override: '%s'", value);
241 return std::string(value) == "true";
242}
243
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
245 switch(displayColorSetting) {
246 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800248 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Enhanced");
252 default:
253 return std::string("Unknown ") +
254 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256}
257
David Sodmanbc815282017-11-05 18:57:52 -0800258SurfaceFlingerBE::SurfaceFlingerBE()
259 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800260 mFrameBuckets(),
261 mTotalTime(0),
262 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800263 mComposerSequenceId(0) {
264}
265
Lloyd Pique90c115d2018-09-18 21:39:42 -0700266SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
267 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800268 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700269 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700270 mTransactionPending(false),
271 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700272 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700273 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800275 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800277 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800278 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800279 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700281 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700282 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700283 mDebugInTransaction(0),
284 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700285 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800286 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700287 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700288 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800289 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800290 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800291 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700292 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700293 mMainThreadId(std::this_thread::get_id()),
294 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800295
Lloyd Pique90c115d2018-09-18 21:39:42 -0700296SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
297 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800307
Steven Thomas050b2c82017-03-06 11:45:16 -0800308 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 mDefaultCompositionDataspace =
318 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
319 mWideColorGamutCompositionDataspace =
320 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
321 defaultCompositionDataspace = mDefaultCompositionDataspace;
322 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
323 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
324 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
325 wideColorGamutCompositionPixelFormat =
326 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700327
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
331 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
332 switch (tmpPrimaryDisplayOrientation) {
333 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
Daniel Solomon42d04562019-01-20 21:03:19 -0800352 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
353 if (surfaceFlingerConfigsServiceV1_2) {
354 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
355 [&](auto tmpPrimaries) {
356 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
357 });
358 } else {
359 initDefaultDisplayNativePrimaries();
360 }
361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362 // debugging stuff...
363 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364
Mathias Agopianb4b17302013-03-20 18:36:41 -0700365 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700366 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 property_get("debug.sf.showupdates", value, "0");
369 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000372
373 // DDMS debugging deprecated (b/120782499)
374 property_get("debug.sf.ddms", value, "0");
375 int debugDdms = atoi(value);
376 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700377
378 property_get("debug.sf.disable_backpressure", value, "0");
379 mPropagateBackpressure = !atoi(value);
380 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700381
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800382 property_get("debug.sf.enable_hwc_vds", value, "0");
383 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800384 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800385
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800386 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800387 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800388 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700389
Yiwei Zhang243b3782018-05-15 17:40:04 -0700390 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700391 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
392 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
393
Ana Krulec98b5b242018-08-10 15:03:23 -0700394 property_get("debug.sf.use_scheduler", value, "0");
395 mUseScheduler = atoi(value);
396
Ana Krulec757f63a2019-01-25 10:46:18 -0800397 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
398 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415void SurfaceFlinger::onFirstRef()
416{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420SurfaceFlinger::~SurfaceFlinger()
421{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Robert Carr1db73f62016-12-21 12:58:51 -0800435static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700436 status_t err = client->initCheck();
437 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return nullptr;
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
444 return initClient(new Client(this));
445}
446
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700447sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
448 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449{
450 class DisplayToken : public BBinder {
451 sp<SurfaceFlinger> flinger;
452 virtual ~DisplayToken() {
453 // no more references, this display must be terminated
454 Mutex::Autolock _l(flinger->mStateLock);
455 flinger->mCurrentState.displays.removeItem(this);
456 flinger->setTransactionFlags(eDisplayTransactionNeeded);
457 }
458 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700459 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 : flinger(flinger) {
461 }
462 };
463
464 sp<BBinder> token = new DisplayToken(this);
465
466 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 // Display ID is assigned when virtual display is allocated by HWC.
468 DisplayDeviceState state;
469 state.isSecure = secure;
470 state.displayName = displayName;
471 mCurrentState.displays.add(token, state);
472 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 return token;
474}
475
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700476void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 Mutex::Autolock _l(mStateLock);
478
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
480 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 return;
483 }
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
486 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 ALOGE("destroyDisplay called for non-virtual display");
488 return;
489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 mInterceptor->saveDisplayDeletion(state.sequenceId);
491 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 setTransactionFlags(eDisplayTransactionNeeded);
493}
494
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 std::optional<DisplayId> displayId;
497
498 if (id == HWC_DISPLAY_PRIMARY) {
499 displayId = getInternalDisplayId();
500 } else if (id == HWC_DISPLAY_EXTERNAL) {
501 displayId = getExternalDisplayId();
502 }
503
504 if (!displayId) {
505 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800506 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508
509 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
Ady Abraham37965d42018-11-01 13:43:32 -0700512status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
513 if (!outGetColorManagement) {
514 return BAD_VALUE;
515 }
516 *outGetColorManagement = useColorManagement;
517 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700518}
519
Lloyd Pique441d5042018-10-18 16:49:51 -0700520HWComposer& SurfaceFlinger::getHwComposer() const {
521 return mCompositionEngine->getHwComposer();
522}
523
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700524renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
525 return mCompositionEngine->getRenderEngine();
526}
527
Lloyd Pique70d91362018-10-18 16:02:55 -0700528compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
529 return *mCompositionEngine.get();
530}
531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532void SurfaceFlinger::bootFinished()
533{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
541 // wait patiently for the window manager death
542 const String16 name("window");
543 sp<IBinder> window(defaultServiceManager()->getService(name));
544 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700545 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 postMessageAsync(new LambdaMessage([this] {
569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
571 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572}
573
Dan Stoza436ccf32018-06-21 12:10:12 -0700574uint32_t SurfaceFlinger::getNewTexture() {
575 {
576 std::lock_guard lock(mTexturePoolMutex);
577 if (!mTexturePool.empty()) {
578 uint32_t name = mTexturePool.back();
579 mTexturePool.pop_back();
580 ATRACE_INT("TexturePoolSize", mTexturePool.size());
581 return name;
582 }
583
584 // The pool was too small, so increase it for the future
585 ++mTexturePoolSize;
586 }
587
588 // The pool was empty, so we need to get a new texture name directly using a
589 // blocking call to the main thread
590 uint32_t name = 0;
591 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
592 return name;
593}
594
Mathias Agopian3f844832013-08-07 21:24:32 -0700595void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700596 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700597}
598
Wei Wangf9b05ee2017-07-19 20:59:39 -0700599// Do not call property_set on main thread which will be blocked by init
600// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700602 ALOGI( "SurfaceFlinger's main thread ready to run. "
603 "Initializing graphics H/W...");
604
Ana Krulec757f63a2019-01-25 10:46:18 -0800605 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608
Dominik Laskowski83b88212018-12-11 13:34:06 -0800609 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800616 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
617 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
618 mPhaseOffsets->setRefreshRateType(
619 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700620
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800623 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700624 impl::EventThread::InterceptVSyncsCallback());
625 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800626 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mInterceptor->saveVSyncEvent(timestamp);
629 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800630
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700632 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
633 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 } else {
635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800637 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mEventThread =
639 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 impl::EventThread::InterceptVSyncsCallback(),
641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800644 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700645
646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 [this](nsecs_t timestamp) {
649 mInterceptor->saveVSyncEvent(timestamp);
650 },
651 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800652 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
654 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700657 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700658 renderEngineFeature |= (useColorManagement ?
659 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700660 renderEngineFeature |= (useContextPriority ?
661 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700662
663 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700665 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700670 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
671 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
694 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 .value_or(0),
697 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (!mVrFlinger) {
699 ALOGE("Failed to start vrflinger");
700 }
701 }
702
Lloyd Pique90c115d2018-09-18 21:39:42 -0700703 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700705
Mathias Agopian92a979a2012-08-02 18:32:23 -0700706 // initialize our drawing state
707 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700708
Andy McFadden13a082e2012-08-24 10:16:42 -0700709 // set initial conditions (e.g. unblank default device)
710 initializeDisplays();
711
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700712 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700713
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700715
716 const bool presentFenceReliable =
717 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
718 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719
720 if (mStartPropertySetThread->Start() != NO_ERROR) {
721 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723
Ana Krulec7d1d6832018-12-27 11:10:09 -0800724 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800725 mScheduler->setExpiredIdleTimerCallback([this]() {
726 mPhaseOffsets->setRefreshRateType(
727 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
728 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
729 mVsyncModulator.setPhaseOffsets(early, gl, late);
730 setRefreshRateTo(60.f /* fps */);
731 });
732 mScheduler->setResetIdleTimerCallback([this]() {
733 mPhaseOffsets->setRefreshRateType(
734 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
735 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
736 mVsyncModulator.setPhaseOffsets(early, gl, late);
737 setRefreshRateTo(90.f /* fps */);
738 });
Alec Mourifb571ea2019-01-24 18:42:10 -0800739 mRefreshRateStats =
740 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
741 *display->getId()),
742 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 }
744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700746}
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 Mutex::Autolock _l(mStateLock);
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751 char value[PROPERTY_VALUE_MAX];
752
753 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100757
758 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700759 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 const auto displayId = getPhysicalDisplayId(displayToken);
822 if (!displayId) {
823 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Steven Thomas6d8110b2017-08-31 18:24:21 -0700845 ConditionalLock _l(mStateLock,
846 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800895 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800909 info.presentationDeadline =
910 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowski075d3172018-05-24 15:50:06 -0700915 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulece588e312018-09-18 12:32:24 -0700931 if (mUseScheduler) {
932 mScheduler->getDisplayStatInfo(stats);
933 } else {
934 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
935 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
936 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return NO_ERROR;
938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
941 const auto display = getDisplayDevice(displayToken);
942 if (!display) {
943 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800944 return BAD_VALUE;
945 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
951 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800952 postMessageAsync(new LambdaMessage(
953 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 return NO_ERROR;
955}
956
957status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
958 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800959 postMessageSync(new LambdaMessage(
960 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 return NO_ERROR;
962}
963
964void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
965 Vector<DisplayInfo> configs;
966 getDisplayConfigs(displayToken, &configs);
967 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
968 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
969 return;
970 }
971
972 const auto display = getDisplayDevice(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
975 displayToken.get());
976 return;
977 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800979 ALOGW("Attempt to set active config %d for virtual display", mode);
980 return;
981 }
982 int currentDisplayPowerMode = display->getPowerMode();
983 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
984 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 return;
986 }
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 return;
992 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800993 if (mUseScheduler) {
994 mRefreshRateStats->setConfigMode(mode);
995 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700996
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997 const auto displayId = display->getId();
998 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Ana Krulec7d1d6832018-12-27 11:10:09 -08001003 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001004 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001005}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1008 Vector<ColorMode>* outColorModes) {
1009 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001010 return BAD_VALUE;
1011 }
1012
Dominik Laskowski075d3172018-05-24 15:50:06 -07001013 const auto displayId = getPhysicalDisplayId(displayToken);
1014 if (!displayId) {
1015 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001016 }
1017
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001019 {
1020 ConditionalLock _l(mStateLock,
1021 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001022 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 }
Michael Wright28f24d02016-07-12 13:30:53 -07001024 outColorModes->clear();
1025 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1026
1027 return NO_ERROR;
1028}
1029
Daniel Solomon42d04562019-01-20 21:03:19 -08001030status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1031 ui::DisplayPrimaries &primaries) {
1032 if (!displayToken) {
1033 return BAD_VALUE;
1034 }
1035
1036 // Currently we only support this API for a single internal display.
1037 if (getInternalDisplayToken() != displayToken) {
1038 return BAD_VALUE;
1039 }
1040
1041 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1042 return NO_ERROR;
1043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1046 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001047 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001048 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001049 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001050}
1051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001053 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054 Vector<ColorMode> modes;
1055 getDisplayColorModes(displayToken, &modes);
1056 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1057 if (mode < ColorMode::NATIVE || !exists) {
1058 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1059 decodeColorMode(mode).c_str(), mode, displayToken.get());
1060 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001061 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 const auto display = getDisplayDevice(displayToken);
1063 if (!display) {
1064 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 } else if (display->isVirtual()) {
1067 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1068 decodeColorMode(mode).c_str(), mode);
1069 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001070 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1071 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072 }
1073 }));
1074
Michael Wright28f24d02016-07-12 13:30:53 -07001075 return NO_ERROR;
1076}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001077
Svetoslavd85084b2014-03-20 10:28:31 -07001078status_t SurfaceFlinger::clearAnimationFrameStats() {
1079 Mutex::Autolock _l(mStateLock);
1080 mAnimFrameTracker.clearStats();
1081 return NO_ERROR;
1082}
1083
1084status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1085 Mutex::Autolock _l(mStateLock);
1086 mAnimFrameTracker.getStats(outStats);
1087 return NO_ERROR;
1088}
1089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1091 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001092 Mutex::Autolock _l(mStateLock);
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDeviceLocked(displayToken);
1095 if (!display) {
1096 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001097 return BAD_VALUE;
1098 }
1099
Peiyong Linfb069302018-04-25 14:34:31 -07001100 // At this point the DisplayDeivce should already be set up,
1101 // meaning the luminance information is already queried from
1102 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001104 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1105 capabilities.getDesiredMaxLuminance(),
1106 capabilities.getDesiredMaxAverageLuminance(),
1107 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001108
1109 return NO_ERROR;
1110}
1111
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001112status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1113 ui::PixelFormat* outFormat,
1114 ui::Dataspace* outDataspace,
1115 uint8_t* outComponentMask) const {
1116 if (!outFormat || !outDataspace || !outComponentMask) {
1117 return BAD_VALUE;
1118 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001119 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001120 if (!display || !display->getId()) {
1121 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1122 return BAD_VALUE;
1123 }
1124 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1125 outDataspace, outComponentMask);
1126}
1127
Kevin DuBois74e53772018-11-19 10:52:38 -08001128status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1129 bool enable, uint8_t componentMask,
1130 uint64_t maxFrames) const {
1131 const auto display = getDisplayDevice(displayToken);
1132 if (!display || !display->getId()) {
1133 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1134 return BAD_VALUE;
1135 }
1136
1137 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1138 componentMask, maxFrames);
1139}
1140
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001141status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1142 uint64_t maxFrames, uint64_t timestamp,
1143 DisplayedFrameStats* outStats) const {
1144 const auto display = getDisplayDevice(displayToken);
1145 if (!display || !display->getId()) {
1146 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1147 return BAD_VALUE;
1148 }
1149
1150 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1151 outStats);
1152}
1153
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001154status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1155 if (!outSupported) {
1156 return BAD_VALUE;
1157 }
1158 *outSupported = getRenderEngine().supportsProtectedContent();
1159 return NO_ERROR;
1160}
1161
Marissa Wallebc2c052019-01-16 19:16:55 -08001162status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1163 int32_t* outBufferId) {
1164 if (!outBufferId) {
1165 return BAD_VALUE;
1166 }
1167 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1168 return NO_ERROR;
1169}
1170
1171status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1172 mBufferStateLayerCache.release(token, bufferId);
1173 return NO_ERROR;
1174}
1175
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001176status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1177 bool* outIsWideColorDisplay) const {
1178 if (!displayToken || !outIsWideColorDisplay) {
1179 return BAD_VALUE;
1180 }
1181 Mutex::Autolock _l(mStateLock);
1182 const auto display = getDisplayDeviceLocked(displayToken);
1183 if (!display) {
1184 return BAD_VALUE;
1185 }
1186 *outIsWideColorDisplay = display->hasWideColorGamut();
1187 return NO_ERROR;
1188}
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001192 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001193
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 if (mInjectVSyncs == enable) {
1195 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197
Dominik Laskowski83b88212018-12-11 13:34:06 -08001198 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001199
Ana Krulec98b5b242018-08-10 15:03:23 -07001200 // TODO(akrulec): Part of the Injector should be refactored, so that it
1201 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 if (enable) {
1203 ALOGV("VSync Injections enabled");
1204 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001205 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001206 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001207 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001208 impl::EventThread::InterceptVSyncsCallback(),
1209 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001210 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001211 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 } else {
1213 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001214 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215 }
1216
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001217 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001218 }));
1219
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001220 return NO_ERROR;
1221}
1222
1223status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224 Mutex::Autolock _l(mStateLock);
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226 if (!mInjectVSyncs) {
1227 ALOGE("VSync Injections not enabled");
1228 return BAD_VALUE;
1229 }
1230 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1231 ALOGV("Injecting VSync inside SurfaceFlinger");
1232 mVSyncInjector->onInjectSyncEvent(when);
1233 }
1234 return NO_ERROR;
1235}
1236
Lloyd Pique755e3192018-01-31 16:46:15 -08001237status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1238 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001239 // Try to acquire a lock for 1s, fail gracefully
1240 const status_t err = mStateLock.timedLock(s2ns(1));
1241 const bool locked = (err == NO_ERROR);
1242 if (!locked) {
1243 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1244 return TIMED_OUT;
1245 }
1246
1247 outLayers->clear();
1248 mCurrentState.traverseInZOrder([&](Layer* layer) {
1249 outLayers->push_back(layer->getLayerDebugInfo());
1250 });
1251
1252 mStateLock.unlock();
1253 return NO_ERROR;
1254}
1255
Peiyong Linc6780972018-10-28 15:24:08 -07001256status_t SurfaceFlinger::getCompositionPreference(
1257 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1258 Dataspace* outWideColorGamutDataspace,
1259 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001260 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001261 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001262 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001263 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001264 return NO_ERROR;
1265}
1266
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001267// ----------------------------------------------------------------------------
1268
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001269sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1270 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001271 auto resyncCallback = makeResyncCallback([this] {
1272 Mutex::Autolock lock(mStateLock);
1273 return getVsyncPeriod();
1274 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001275
Ana Krulec98b5b242018-08-10 15:03:23 -07001276 if (mUseScheduler) {
1277 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001278 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001279 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001280 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001281 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001282 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001283 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001288 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001289}
1290
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001291// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001292
1293void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001294 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001295}
1296
1297void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001298 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001299}
1300
1301void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001302 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303}
1304
1305void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001306 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001307 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001308}
1309
1310status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001311 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001312 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001313}
1314
1315status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001316 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001317 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001318 if (res == NO_ERROR) {
1319 msg->wait();
1320 }
1321 return res;
1322}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001323
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001324void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001325 do {
1326 waitForEvent();
1327 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328}
1329
Dominik Laskowski83b88212018-12-11 13:34:06 -08001330nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1331 const auto displayId = getInternalDisplayId();
1332 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1333 return 0;
1334 }
1335
1336 const auto config = getHwComposer().getActiveConfig(*displayId);
1337 return config ? config->getVsyncPeriod() : 0;
1338}
1339
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340void SurfaceFlinger::enableHardwareVsync() {
1341 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001342 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001343 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001346 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347}
1348
Dominik Laskowski83b88212018-12-11 13:34:06 -08001349void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350 Mutex::Autolock _l(mHWVsyncLock);
1351
Jesse Hall948fe0c2013-10-14 12:56:09 -07001352 if (makeAvailable) {
1353 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001354 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1355 if (mUseScheduler) {
1356 mScheduler->makeHWSyncAvailable(true);
1357 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001358 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001359 // Hardware vsync is not currently available, so abort the resync
1360 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001361 return;
1362 }
1363
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001365 return;
1366 }
1367
Ana Krulece588e312018-09-18 12:32:24 -07001368 if (mUseScheduler) {
1369 mScheduler->setVsyncPeriod(period);
1370 } else {
1371 mPrimaryDispSync->reset();
1372 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (!mPrimaryHWVsyncEnabled) {
1375 mPrimaryDispSync->beginResync();
1376 mEventControlThread->setVsyncEnabled(true);
1377 mPrimaryHWVsyncEnabled = true;
1378 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379 }
1380}
1381
Jesse Hall948fe0c2013-10-14 12:56:09 -07001382void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 Mutex::Autolock _l(mHWVsyncLock);
1384 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001385 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001386 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001387 mPrimaryHWVsyncEnabled = false;
1388 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001389 if (makeUnavailable) {
1390 mHWVsyncAvailable = false;
1391 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392}
1393
Dominik Laskowski83b88212018-12-11 13:34:06 -08001394void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001395 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001396
Dan Stoza57164302017-05-08 14:03:54 -07001397 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001398 const nsecs_t last = lastResyncTime.exchange(now);
1399
1400 if (now - last > kIgnoreDelay) {
1401 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001402 }
1403}
1404
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001405void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1406 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001407 ATRACE_NAME("SF onVsync");
1408
Steven Thomas3cfac282017-02-06 12:29:30 -08001409 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001411 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 return;
1413 }
1414
Dominik Laskowski075d3172018-05-24 15:50:06 -07001415 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001416 return;
1417 }
1418
Dominik Laskowski075d3172018-05-24 15:50:06 -07001419 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001420 // For now, we don't do anything with external display vsyncs.
1421 return;
1422 }
1423
Ana Krulece588e312018-09-18 12:32:24 -07001424 if (mUseScheduler) {
1425 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001426 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001427 bool needsHwVsync = false;
1428 { // Scope for the lock
1429 Mutex::Autolock _l(mHWVsyncLock);
1430 if (mPrimaryHWVsyncEnabled) {
1431 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1432 }
1433 }
1434
1435 if (needsHwVsync) {
1436 enableHardwareVsync();
1437 } else {
1438 disableHardwareVsync(false);
1439 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001440 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001441}
1442
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001443void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001444 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1445 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446}
1447
Ana Krulec7d1d6832018-12-27 11:10:09 -08001448void SurfaceFlinger::setRefreshRateTo(float newFps) {
1449 const auto displayId = getInternalDisplayId();
1450 if (!displayId || mBootStage != BootStage::FINISHED) {
1451 return;
1452 }
1453 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1454 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1455 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1456 // refresh cycle.
1457
1458 // Don't do any updating if the current fps is the same as the new one.
1459 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1460 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1461 if (currentVsyncPeriod == 0) {
1462 return;
1463 }
1464 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1465 // floating numbers.
1466 const float currentFps = 1e9 / currentVsyncPeriod;
1467 if (std::abs(currentFps - newFps) <= 1) {
1468 return;
1469 }
1470
1471 auto configs = getHwComposer().getConfigs(*displayId);
1472 for (int i = 0; i < configs.size(); i++) {
1473 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1474 if (vsyncPeriod == 0) {
1475 continue;
1476 }
1477 const float fps = 1e9 / vsyncPeriod;
1478 // TODO(b/113612090): There should be a better way at determining which config
1479 // has the right refresh rate.
1480 if (std::abs(fps - newFps) <= 1) {
1481 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1482 if (!display) return;
1483 // This is posted in async function to avoid deadlock when getDisplayDevice
1484 // requires mStateLock.
1485 setActiveConfigAsync(display, i);
1486 ATRACE_INT("FPS", newFps);
1487 }
1488 }
1489}
1490
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001491void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001492 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001494 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001495
Lloyd Piqueba04e622017-12-14 17:11:26 -08001496 // Ignore events that do not have the right sequenceId.
1497 if (sequenceId != getBE().mComposerSequenceId) {
1498 return;
1499 }
1500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Only lock if we're not on the main thread. This function is normally
1502 // called on a hwbinder thread, but for the primary display it's called on
1503 // the main thread with the state lock already held, so don't attempt to
1504 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001505 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001506
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001507 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001508
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001509 if (std::this_thread::get_id() == mMainThreadId) {
1510 // Process all pending hot plug events immediately if we are on the main thread.
1511 processDisplayHotplugEventsLocked();
1512 }
1513
Lloyd Piqueba04e622017-12-14 17:11:26 -08001514 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001515}
1516
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001517void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001518 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001519 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001521 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001523}
1524
Dominik Laskowski075d3172018-05-24 15:50:06 -07001525void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001526 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001527 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001528 if (const auto displayId = getInternalDisplayId()) {
1529 getHwComposer().setVsyncEnabled(*displayId,
1530 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1531 }
Mathias Agopian86303202012-07-24 22:46:10 -07001532}
1533
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001535void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001536 if (mUseScheduler) {
1537 mScheduler->disableHardwareVsync(true);
1538 } else {
1539 disableHardwareVsync(true);
1540 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001541 // Clear the drawing state so that the logic inside of
1542 // handleTransactionLocked will fire. It will determine the delta between
1543 // mCurrentState and mDrawingState and re-apply all changes when we make the
1544 // transition.
1545 mDrawingState.displays.clear();
1546 mDisplays.clear();
1547}
1548
Steven Thomas050b2c82017-03-06 11:45:16 -08001549void SurfaceFlinger::updateVrFlinger() {
1550 if (!mVrFlinger)
1551 return;
1552 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001554 return;
1555 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 ALOGE("Vr flinger is only supported for remote hardware composer"
1559 " service connections. Ignoring request to transition to vr"
1560 " flinger.");
1561 mVrFlingerRequestsDisplay = false;
1562 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001563 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001568 LOG_ALWAYS_FATAL_IF(!display);
1569 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1571 // called below. Clear the reference now so we don't accidentally use it
1572 // later.
1573 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001576 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001580 // Delete the current instance before creating the new one
1581 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1582 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1583 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1584 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001587 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001588
1589 if (vrFlingerRequestsDisplay) {
1590 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001591 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592
1593 mVisibleRegionsDirty = true;
1594 invalidateHwcGeometry();
1595
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001596 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001597 display = getDefaultDisplayDeviceLocked();
1598 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001599 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001600
Steven Thomasb02664d2017-07-26 18:48:28 -07001601 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001602 const nsecs_t vsyncPeriod = getVsyncPeriod();
1603 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001604
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001605 // The present fences returned from vr_hwc are not an accurate
1606 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001607 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001608 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1609 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001610 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001611 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001612 !hasSyncFramework);
1613 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Use phase of 0 since phase is not known.
1616 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001617 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001618 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001619
Dominik Laskowski83b88212018-12-11 13:34:06 -08001620 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001621
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001622 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001623 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001624}
1625
Mathias Agopian4fec8732012-06-29 14:12:52 -07001626void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001627 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001628 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001630 if (mUseScheduler) {
1631 // This call is made each time SF wakes up and creates a new frame.
1632 mScheduler->incrementFrameCounter();
1633 }
Dan Stoza50182882016-07-08 12:02:20 -07001634 bool frameMissed = !mHadClientComposition &&
1635 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 (mPreviousPresentFence->getSignalTime() ==
1637 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001638 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001639 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001640 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001641 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001642 if (mPropagateBackpressure) {
1643 signalLayerUpdate();
1644 break;
1645 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001646 }
Dan Stoza50182882016-07-08 12:02:20 -07001647
Steven Thomas050b2c82017-03-06 11:45:16 -08001648 // Now that we're going to make it to the handleMessageTransaction()
1649 // call below it's safe to call updateVrFlinger(), which will
1650 // potentially trigger a display handoff.
1651 updateVrFlinger();
1652
Dan Stoza6b9454d2014-11-07 16:00:59 -08001653 bool refreshNeeded = handleMessageTransaction();
1654 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001655 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001656 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001657 // Signal a refresh if a transaction modified the window state,
1658 // a new buffer was latched, or if HWC has requested a full
1659 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001660 signalRefresh();
1661 }
1662 break;
1663 }
1664 case MessageQueue::REFRESH: {
1665 handleMessageRefresh();
1666 break;
1667 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001668 }
1669}
1670
Dan Stoza6b9454d2014-11-07 16:00:59 -08001671bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001672 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001673
1674 // Apply any ready transactions in the queues if there are still transactions that have not been
1675 // applied, wake up during the next vsync period and check again
1676 bool transactionNeeded = false;
1677 if (!flushTransactionQueues()) {
1678 transactionNeeded = true;
1679 }
1680
Mathias Agopian4fec8732012-06-29 14:12:52 -07001681 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001682 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001684
1685 if (transactionNeeded) {
1686 setTransactionFlags(eTransactionNeeded);
1687 }
1688
1689 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690}
1691
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001694
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001695 mRefreshPending = false;
1696
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001697 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001698 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001699 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001700 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 for (const auto& [token, display] : mDisplays) {
1702 beginFrame(display);
1703 prepareFrame(display);
1704 doDebugFlashRegions(display, repaintEverything);
1705 doComposition(display, repaintEverything);
1706 }
1707
Adrian Roos1e1a1282017-11-01 19:05:31 +01001708 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001709 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710
1711 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001712 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001713
Dan Stozabfbffeb2016-07-21 14:49:33 -07001714 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 for (const auto& [token, displayDevice] : mDisplays) {
1716 auto display = displayDevice->getCompositionDisplay();
1717 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001719 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001720 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001721
Alec Mouri86770e52018-09-24 22:40:58 +00001722 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001723 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001724 if (mHadClientComposition) {
1725 base::unique_fd flushFence(getRenderEngine().flush());
1726 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1727 getBE().flushFence = new Fence(std::move(flushFence));
1728 } else {
1729 // Cleanup for hygiene.
1730 getBE().flushFence = Fence::NO_FENCE;
1731 }
1732 }
1733
Jorim Jaggi90535212018-05-23 23:44:06 +02001734 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001735
David Sodman7e4ae112018-02-09 15:02:28 -08001736 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001738 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001739 compositionInfo.hwc.hwcLayer = nullptr;
1740 }
David Sodmanba340492018-08-05 21:51:33 -07001741 }
David Sodman7e4ae112018-02-09 15:02:28 -08001742
1743 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001745
David Sodmanfa9b2af2017-12-24 13:28:59 -08001746
1747bool SurfaceFlinger::handleMessageInvalidate() {
1748 ATRACE_CALL();
1749 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001750}
1751
David Sodman79bba0e2018-08-05 18:07:49 -07001752void SurfaceFlinger::calculateWorkingSet() {
1753 ATRACE_CALL();
1754 ALOGV(__FUNCTION__);
1755
David Sodman79bba0e2018-08-05 18:07:49 -07001756 // build the h/w work list
1757 if (CC_UNLIKELY(mGeometryInvalid)) {
1758 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001759 for (const auto& [token, displayDevice] : mDisplays) {
1760 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001761 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001762 if (!displayId) {
1763 continue;
1764 }
David Sodman79bba0e2018-08-05 18:07:49 -07001765
Lloyd Pique32cbe282018-10-19 13:09:22 -07001766 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001767 for (size_t i = 0; i < currentLayers.size(); i++) {
1768 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001769
Dominik Laskowski075d3172018-05-24 15:50:06 -07001770 if (!layer->hasHwcLayer(*displayId)) {
1771 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1772 layer->forceClientComposition(*displayId);
1773 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001774 }
1775 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776
Lloyd Pique32cbe282018-10-19 13:09:22 -07001777 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 if (mDebugDisableHWC || mDebugRegion) {
1779 layer->forceClientComposition(*displayId);
1780 }
David Sodman79bba0e2018-08-05 18:07:49 -07001781 }
1782 }
1783 }
1784
1785 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001786 for (const auto& [token, displayDevice] : mDisplays) {
1787 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001788 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001790 continue;
1791 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001792 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001793
1794 if (mDrawingState.colorMatrixChanged) {
1795 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001796 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001798 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001799 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001800 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1801 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001802 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001803 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001804 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1805 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001806 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001807 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 }
1809
Peiyong Lind3788632018-09-18 16:01:31 -07001810 // TODO(b/111562338) remove when composer 2.3 is shipped.
1811 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001812 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001813 }
1814
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001815 if (layer->getRoundedCornerState().radius > 0.0f) {
1816 layer->forceClientComposition(*displayId);
1817 }
1818
Dominik Laskowski075d3172018-05-24 15:50:06 -07001819 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001820 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001821 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001822 continue;
1823 }
1824
Lloyd Pique32cbe282018-10-19 13:09:22 -07001825 const auto& displayState = display->getState();
1826 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1827 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001828 }
1829
Peiyong Lin13effd12018-07-24 17:01:47 -07001830 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001831 ColorMode colorMode;
1832 Dataspace dataSpace;
1833 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001834 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001835 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001836 }
1837 }
1838
1839 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001840
1841 for (const auto& [token, display] : mDisplays) {
1842 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001843 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001844 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001845
1846 if (displayId) {
1847 if (!layer->setHwcLayer(*displayId)) {
1848 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1849 }
1850 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001851 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001852
Dominik Laskowski05275f12018-11-01 15:03:24 -07001853 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001854 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1855 }
1856 }
David Sodman79bba0e2018-08-05 18:07:49 -07001857}
1858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1860 bool repaintEverything) {
1861 auto display = displayDevice->getCompositionDisplay();
1862 const auto& displayState = display->getState();
1863
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864 // is debugging enabled
1865 if (CC_LIKELY(!mDebugRegion))
1866 return;
1867
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001869 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00001870 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001871 if (!dirtyRegion.isEmpty()) {
1872 // redraw the whole screen
Alec Mouri79108df2019-02-04 19:33:44 +00001873 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874
Alec Mouri79108df2019-02-04 19:33:44 +00001875 // and draw the dirty region
1876 auto& engine(getRenderEngine());
1877 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
1878
1879 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880 }
1881 }
1882
Lloyd Pique32cbe282018-10-19 13:09:22 -07001883 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884
1885 if (mDebugRegion > 1) {
1886 usleep(mDebugRegion * 1000);
1887 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890}
1891
Adrian Roos1e1a1282017-11-01 19:05:31 +01001892void SurfaceFlinger::doTracing(const char* where) {
1893 ATRACE_CALL();
1894 ATRACE_NAME(where);
1895 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001896 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001897 }
1898}
1899
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001900void SurfaceFlinger::logLayerStats() {
1901 ATRACE_CALL();
1902 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001903 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001904 if (display->isPrimary()) {
1905 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001906 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001907 }
1908 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001909
1910 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001911 }
1912}
1913
David Sodman2b406362017-12-15 13:33:47 -08001914void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 ATRACE_CALL();
1917 ALOGV("preComposition");
1918
David Sodman2b406362017-12-15 13:33:47 -08001919 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001922 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001923 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924 needExtraInvalidate = true;
1925 }
Robert Carr2047fae2016-11-28 14:09:09 -08001926 });
1927
Mathias Agopiancd60f992012-08-16 16:28:27 -07001928 if (needExtraInvalidate) {
1929 signalLayerUpdate();
1930 }
1931}
1932
Ana Krulece588e312018-09-18 12:32:24 -07001933void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1934 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 // Update queue of past composite+present times and determine the
1936 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001937 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001939 while (!getBE().mCompositePresentTimes.empty()) {
1940 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Cached values should have been updated before calling this method,
1942 // which helps avoid duplicate syscalls.
1943 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1944 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1945 break;
1946 }
1947 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001948 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949 }
1950
1951 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001952 while (getBE().mCompositePresentTimes.size() > 16) {
1953 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 }
1955
Ana Krulece588e312018-09-18 12:32:24 -07001956 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001957}
1958
Ana Krulece588e312018-09-18 12:32:24 -07001959void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1960 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961 // Integer division and modulo round toward 0 not -inf, so we need to
1962 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001963 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1964 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1965 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966
Ana Krulec757f63a2019-01-25 10:46:18 -08001967 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001968 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001969 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001970 }
1971
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 // Snap the latency to a value that removes scheduling jitter from the
1973 // composition and present times, which often have >1ms of jitter.
1974 // Reducing jitter is important if an app attempts to extrapolate
1975 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001976 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001978 nsecs_t bias = stats.vsyncPeriod / 2;
1979 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1980 nsecs_t snappedCompositeToPresentLatency =
1981 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001982
David Sodman99974d22017-11-28 12:04:33 -08001983 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001984 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1985 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001986 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001987}
1988
Ady Abraham8164d482019-01-11 14:47:59 -08001989// debug patch for b/119477596 - add stack guards to catch stack
1990// corruptions and disable clang optimizations.
1991// The code below is temporary and planned to be removed once stack
1992// corruptions are found.
1993#pragma clang optimize off
1994class StackGuard {
1995public:
1996 StackGuard(const char* name, const char* func, int line) {
1997 guarders.reserve(MIN_CAPACITY);
1998 guarders.push_back({this, name, func, line});
1999 validate();
2000 }
2001 ~StackGuard() {
2002 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2003 if (i->guard == this) {
2004 guarders.erase(i);
2005 break;
2006 }
2007 }
2008 }
2009
2010 static void validate() {
2011 for (const auto& guard : guarders) {
2012 if (guard.guard->cookie != COOKIE_VALUE) {
2013 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2014 CallStack stack(LOG_TAG);
2015 abort();
2016 }
2017 }
2018 }
2019
2020private:
2021 uint64_t cookie = COOKIE_VALUE;
2022 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2023 static constexpr size_t MIN_CAPACITY = 16;
2024
2025 struct GuarderElement {
2026 StackGuard* guard;
2027 const char* name;
2028 const char* func;
2029 int line;
2030 };
2031
2032 static std::vector<GuarderElement> guarders;
2033};
2034std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2035
2036#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2037
2038#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002039void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002040{
Ady Abraham8164d482019-01-11 14:47:59 -08002041 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 ATRACE_CALL();
2043 ALOGV("postComposition");
2044
Brian Anderson3546a3f2016-07-14 11:51:14 -07002045 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002046 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002048 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002049 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002050 }
Ady Abraham8164d482019-01-11 14:47:59 -08002051 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002052
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002053 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 const auto displayDevice = getDefaultDisplayDeviceLocked();
2055 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056
David Sodman73beded2017-11-15 11:56:06 -08002057 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002058 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002059 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2060
Lloyd Pique32cbe282018-10-19 13:09:22 -07002061 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002063 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2064 ->getRenderSurface()
2065 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002066 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002067 } else {
2068 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2069 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002070
Ady Abraham8164d482019-01-11 14:47:59 -08002071 ASSERT_ON_STACK_GUARD();
2072
David Sodman73beded2017-11-15 11:56:06 -08002073 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002074 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2075 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002076 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002077 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002078 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079
Ana Krulece588e312018-09-18 12:32:24 -07002080 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002082 if (mUseScheduler) {
2083 mScheduler->getDisplayStatInfo(&stats);
2084 } else {
2085 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2086 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2087 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
2090
David Sodman2b406362017-12-15 13:33:47 -08002091 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002092 // when we started doing work for this frame, but that should be okay
2093 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002094 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002095 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002096 DEFINE_STACK_GUARD(compositorTiming);
2097
Brian Andersond0010582017-03-07 13:20:31 -08002098 {
David Sodman99974d22017-11-28 12:04:33 -08002099 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002100 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002101 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002102
2103 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002104 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002105
Robert Carr2047fae2016-11-28 14:09:09 -08002106 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002107 bool frameLatched =
2108 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2109 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002110 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002111 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002112 recordBufferingStats(layer->getName().string(),
2113 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002114 }
Ady Abraham8164d482019-01-11 14:47:59 -08002115 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002116 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002117
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002118 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002119 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002120 if (mUseScheduler) {
2121 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002123 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002124 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2125 enableHardwareVsync();
2126 } else {
2127 disableHardwareVsync(false);
2128 }
Ady Abraham8164d482019-01-11 14:47:59 -08002129 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002130 }
2131 }
2132
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002133 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002134 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2135 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002136 if (mUseScheduler) {
2137 mScheduler->enableHardwareVsync();
2138 } else {
2139 enableHardwareVsync();
2140 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002141 }
2142 }
2143
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
2145
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002146 if (mAnimCompositionPending) {
2147 mAnimCompositionPending = false;
2148
Brian Anderson4e606e32017-03-16 15:34:57 -07002149 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002151 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002152
2153 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002154 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002155 // The HWC doesn't support present fences, so use the refresh
2156 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002157 const nsecs_t presentTime =
2158 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(presentTime);
2160
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002162 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002163 }
2164 mAnimFrameTracker.advanceFrame();
2165 }
Dan Stozab90cf072015-03-05 11:05:59 -08002166
Ady Abraham8164d482019-01-11 14:47:59 -08002167 ASSERT_ON_STACK_GUARD();
2168
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002169 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002170 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002171 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002172 }
2173
Ady Abraham8164d482019-01-11 14:47:59 -08002174 ASSERT_ON_STACK_GUARD();
2175
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002176 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002177
Ady Abraham8164d482019-01-11 14:47:59 -08002178 ASSERT_ON_STACK_GUARD();
2179
Lloyd Pique32cbe282018-10-19 13:09:22 -07002180 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2181 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002182 return;
2183 }
2184
2185 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002186 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002187 if (mHasPoweredOff) {
2188 mHasPoweredOff = false;
2189 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002190 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002191 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002192 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002193 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002194 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2195 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002196 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002197 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002198 }
David Sodman4a36e932017-11-07 14:29:47 -08002199 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002200
2201 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002202 }
David Sodman4a36e932017-11-07 14:29:47 -08002203 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002204 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002205
2206 {
2207 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002208 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002209 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002210 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002211 if (refillCount > 0) {
2212 const size_t offset = mTexturePool.size();
2213 mTexturePool.resize(mTexturePoolSize);
2214 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2215 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2216 }
Ady Abraham8164d482019-01-11 14:47:59 -08002217 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002218 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002219
Marissa Wallfda30bb2018-10-12 11:34:28 -07002220 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002221 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002222
2223 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002224}
Ady Abraham8164d482019-01-11 14:47:59 -08002225#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002226
2227void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 ATRACE_CALL();
2229 ALOGV("rebuildLayerStacks");
2230
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002231 // We need to clear these out now as these may be holding on to a
2232 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2233 // also holds a reference. When the set of visible layers is recomputed,
2234 // some layers may be destroyed if the only thing keeping them alive was
2235 // that list of visible layers associated with each display. The layer
2236 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2237 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2238 for (const auto& [token, display] : mDisplays) {
2239 getBE().mCompositionInfo[token].clear();
2240 }
2241
Mathias Agopiancd60f992012-08-16 16:28:27 -07002242 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002243 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002244 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 mVisibleRegionsDirty = false;
2246 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002247
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002248 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002249 const auto& displayDevice = pair.second;
2250 auto display = displayDevice->getCompositionDisplay();
2251 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 Region opaqueRegion;
2253 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002254 compositionengine::Output::OutputLayers layersSortedByZ;
2255 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002256 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 const ui::Transform& tr = displayState.transform;
2258 const Rect bounds = displayState.bounds;
2259 if (displayState.isEnabled) {
2260 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002261
Jeff Sharkey76488112017-02-27 14:15:18 -07002262 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002263 auto compositionLayer = layer->getCompositionLayer();
2264 if (compositionLayer == nullptr) {
2265 return;
2266 }
2267
Chia-I Wu83806892017-11-16 10:50:20 -08002268 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002270 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2271 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2272
Lloyd Piqueef36b002019-01-23 17:52:04 -08002273 if (display->belongsInOutput(layer->getLayerStack(),
2274 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002275 Region drawRegion(tr.transform(
2276 layer->visibleNonTransparentRegion));
2277 drawRegion.andSelf(bounds);
2278 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002279 layersSortedByZ.emplace_back(
2280 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2281 layerFE));
2282
2283 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002284 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002285 // Clear out the HWC layer if this layer was
2286 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002288 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002289 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002290 // WM changes display->layerStack upon sleep/awake.
2291 // Here we make sure we delete the HWC layers even if
2292 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002294 }
2295
2296 // If a layer is not going to get a release fence because
2297 // it is invisible, but it is also going to release its
2298 // old buffer, add it to the list of layers needing
2299 // fences.
2300 if (hwcLayerDestroyed) {
2301 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2302 mLayersWithQueuedFrames.cend(), layer);
2303 if (found != mLayersWithQueuedFrames.cend()) {
2304 layersNeedingFences.add(layer);
2305 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002306 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002307 });
2308 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002309
2310 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2311
2312 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002313 displayDevice->setLayersNeedingFences(layersNeedingFences);
2314
2315 Region undefinedRegion{bounds};
2316 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2317
2318 display->editState().undefinedRegion = undefinedRegion;
2319 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002320 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002321 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002322}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002323
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002324// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002326// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002328// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329// The returned HDR data space is one of
2330// - Dataspace::UNKNOWN
2331// - Dataspace::BT2020_HLG
2332// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2334 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002335 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336 *outHdrDataSpace = Dataspace::UNKNOWN;
2337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002339 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340 case Dataspace::V0_SCRGB:
2341 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002342 case Dataspace::BT2020:
2343 case Dataspace::BT2020_ITU:
2344 case Dataspace::BT2020_LINEAR:
2345 case Dataspace::DISPLAY_BT2020:
2346 bestDataSpace = Dataspace::DISPLAY_BT2020;
2347 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002348 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002349 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002350 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 case Dataspace::BT2020_PQ:
2352 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002353 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002354 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002355 case Dataspace::BT2020_HLG:
2356 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 // When there's mixed PQ content and HLG content, we set the HDR
2358 // data space to be BT2020_PQ and convert HLG to PQ.
2359 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2360 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002361 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 break;
2363 default:
2364 break;
2365 }
Romain Guy54f154a2017-10-24 21:40:32 +01002366 }
2367
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002368 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002369}
2370
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2373 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002374 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2375 *outMode = ColorMode::NATIVE;
2376 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002379 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002380
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002383
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002384 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2385
Peiyong Lindfde5112018-06-05 10:58:41 -07002386 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002387 const bool isHdr =
2388 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002389 if (isHdr) {
2390 bestDataSpace = hdrDataSpace;
2391 }
2392
Chia-I Wu0d711262018-05-21 15:19:35 -07002393 RenderIntent intent;
2394 switch (mDisplayColorSetting) {
2395 case DisplayColorSetting::MANAGED:
2396 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002397 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002398 break;
2399 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002400 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002401 break;
2402 default: // vendor display color setting
2403 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2404 break;
2405 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002406
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002407 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002408}
2409
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2411 auto display = displayDevice->getCompositionDisplay();
2412 const auto& displayState = display->getState();
2413
Alec Mouri79108df2019-02-04 19:33:44 +00002414 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2416 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002417
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // If nothing has changed (!dirty), don't recompose.
2419 // If something changed, but we don't currently have any visible layers,
2420 // and didn't when we last did a composition, then skip it this time.
2421 // The second rule does two things:
2422 // - When all layers are removed from a display, we'll emit one black
2423 // frame, then nothing more until we get new layers.
2424 // - When a display is created with a private layer stack, we won't
2425 // emit any black frames until a layer is added to the layer stack.
2426 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002427
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 const char flagPrefix[] = {'-', '+'};
2429 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002430 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2431 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2432 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2433 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002434
Lloyd Pique31cb2942018-10-19 17:23:03 -07002435 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002436
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002439 }
2440}
2441
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2443 auto display = displayDevice->getCompositionDisplay();
2444 const auto& displayState = display->getState();
2445
2446 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 return;
David Sodman2b406362017-12-15 13:33:47 -08002448 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449
Lloyd Pique31cb2942018-10-19 17:23:03 -07002450 status_t result = display->getRenderSurface()->prepareFrame(
2451 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002454}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002455
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002457 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 ALOGV("doComposition");
2459
Lloyd Pique32cbe282018-10-19 13:09:22 -07002460 auto display = displayDevice->getCompositionDisplay();
2461 const auto& displayState = display->getState();
2462
2463 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002464 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00002465 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002466
David Sodmanfa9b2af2017-12-24 13:28:59 -08002467 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002469
Lloyd Pique32cbe282018-10-19 13:09:22 -07002470 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002471 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002472 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002473 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474}
2475
David Sodmanfa9b2af2017-12-24 13:28:59 -08002476void SurfaceFlinger::postFrame()
2477{
2478 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002479 const auto display = getDefaultDisplayDeviceLocked();
2480 if (display && getHwComposer().isConnected(*display->getId())) {
2481 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002482 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2483 logFrameStats();
2484 }
2485 }
2486}
2487
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002489 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002491
Lloyd Pique32cbe282018-10-19 13:09:22 -07002492 auto display = displayDevice->getCompositionDisplay();
2493 const auto& displayState = display->getState();
2494 const auto displayId = display->getId();
2495
David Sodmanfa9b2af2017-12-24 13:28:59 -08002496 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002497
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (displayId) {
2500 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002501 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002502 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002504 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002505
Chia-I Wu7b549592017-11-15 09:14:57 -08002506 // The layer buffer from the previous frame (if any) is released
2507 // by HWC only when the release fence from this frame (if any) is
2508 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 if (displayId && layer->hasHwcLayer(*displayId)) {
2510 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2511 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002512 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002513
2514 // If the layer was client composited in the previous frame, we
2515 // need to merge with the previous client target acquire fence.
2516 // Since we do not track that, always merge with the current
2517 // client target acquire fence when it is available, even though
2518 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002519 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002520 releaseFence =
2521 Fence::merge("LayerRelease", releaseFence,
2522 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002523 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002524
David Sodman15094112018-10-11 09:39:37 -07002525 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526 }
Chia-I Wu83806892017-11-16 10:50:20 -08002527
2528 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002529 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002530 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002531 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002533 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002534 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002535 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002536 }
2537 }
2538
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 if (displayId) {
2540 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002541 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543}
2544
Mathias Agopian87baae12012-07-31 12:38:26 -07002545void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546{
Mathias Agopian841cde52012-03-01 15:44:37 -08002547 ATRACE_CALL();
2548
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002549 // here we keep a copy of the drawing state (that is the state that's
2550 // going to be overwritten by handleTransactionLocked()) outside of
2551 // mStateLock so that the side-effects of the State assignment
2552 // don't happen with mStateLock held (which can cause deadlocks).
2553 State drawingState(mDrawingState);
2554
Mathias Agopianca4d3602011-05-19 15:38:14 -07002555 Mutex::Autolock _l(mStateLock);
2556 const nsecs_t now = systemTime();
2557 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558
Mathias Agopianca4d3602011-05-19 15:38:14 -07002559 // Here we're guaranteed that some transaction flags are set
2560 // so we can call handleTransactionLocked() unconditionally.
2561 // We call getTransactionFlags(), which will also clear the flags,
2562 // with mStateLock held to guarantee that mCurrentState won't change
2563 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002564
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002565 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002567 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002568
Mathias Agopianca4d3602011-05-19 15:38:14 -07002569 mLastTransactionTime = systemTime() - now;
2570 mDebugInTransaction = 0;
2571 invalidateHwcGeometry();
2572 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002573}
2574
Lloyd Piqueba04e622017-12-14 17:11:26 -08002575void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2576 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 const std::optional<DisplayIdentificationInfo> info =
2578 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002579
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002581 continue;
2582 }
2583
Lloyd Piqueba04e622017-12-14 17:11:26 -08002584 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002586 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 mPhysicalDisplayTokens[info->id] = new BBinder();
2588 DisplayDeviceState state;
2589 state.displayId = info->id;
2590 state.isSecure = true; // All physical displays are currently considered secure.
2591 state.displayName = info->name;
2592 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2593 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002594 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002596 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002597
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2599 if (index >= 0) {
2600 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2601 mInterceptor->saveDisplayDeletion(state.sequenceId);
2602 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002603 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 }
2606
2607 processDisplayChangesLocked();
2608 }
2609
2610 mPendingHotplugEvents.clear();
2611}
2612
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002613void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2614 bool connected) {
2615 if (mUseScheduler) {
2616 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2617 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2618 } else {
2619 mEventThread->onHotplugReceived(displayType, connected);
2620 mSFEventThread->onHotplugReceived(displayType, connected);
2621 }
2622}
2623
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002626 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 const sp<IGraphicBufferProducer>& producer) {
2628 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002629 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002631 creationArgs.isSecure = state.isSecure;
2632 creationArgs.displaySurface = dispSurface;
2633 creationArgs.hasWideColorGamut = false;
2634 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002635
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2637 creationArgs.isPrimary = isInternalDisplay;
2638
2639 if (useColorManagement && displayId) {
2640 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002642 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002643 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002645
Dominik Laskowski7e045462018-05-30 13:02:02 -07002646 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 }
tangrobin6753a022018-08-10 10:58:54 +08002650 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 if (displayId) {
2653 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002654 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002656 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657
Lloyd Pique90c115d2018-09-18 21:39:42 -07002658 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 // Make sure that composition can never be stalled by a virtual display
2663 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002664 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002665 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2667 }
2668
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 creationArgs.displayInstallOrientation =
2670 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002671
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002673 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674
Lloyd Pique90c115d2018-09-18 21:39:42 -07002675 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676
2677 if (maxFrameBufferAcquiredBuffers >= 3) {
2678 nativeWindowSurface->preallocateBuffers();
2679 }
2680
2681 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002682 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002683 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002685 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002686 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002687 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2688 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002689 if (!state.isVirtual()) {
2690 LOG_ALWAYS_FATAL_IF(!displayId);
2691 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002692 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 display->setLayerStack(state.layerStack);
2695 display->setProjection(state.orientation, state.viewport, state.frame);
2696 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002697
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002699}
2700
Lloyd Pique347200f2017-12-14 17:00:15 -08002701void SurfaceFlinger::processDisplayChangesLocked() {
2702 // here we take advantage of Vector's copy-on-write semantics to
2703 // improve performance by skipping the transaction entirely when
2704 // know that the lists are identical
2705 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2706 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2707 if (!curr.isIdenticalTo(draw)) {
2708 mVisibleRegionsDirty = true;
2709 const size_t cc = curr.size();
2710 size_t dc = draw.size();
2711
2712 // find the displays that were removed
2713 // (ie: in drawing state but not in current state)
2714 // also handle displays that changed
2715 // (ie: displays that are in both lists)
2716 for (size_t i = 0; i < dc;) {
2717 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2718 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 // Save display IDs before disconnecting.
2720 const auto internalDisplayId = getInternalDisplayId();
2721 const auto externalDisplayId = getExternalDisplayId();
2722
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002725 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002728 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002730 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002731 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002732 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 } else {
2734 // this display is in both lists. see if something changed.
2735 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002736 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2738 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2739 if (state_binder != draw_binder) {
2740 // changing the surface is like destroying and
2741 // recreating the DisplayDevice, so we just remove it
2742 // from the drawing state, so that it get re-added
2743 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002745 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002747 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 mDrawingState.displays.removeItemsAt(i);
2749 dc--;
2750 // at this point we must loop to the next item
2751 continue;
2752 }
2753
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002756 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 }
2758 if ((state.orientation != draw[i].orientation) ||
2759 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 }
2762 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 }
2765 }
2766 }
2767 ++i;
2768 }
2769
2770 // find displays that were added
2771 // (ie: in current state but not in drawing state)
2772 for (size_t i = 0; i < cc; i++) {
2773 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2774 const DisplayDeviceState& state(curr[i]);
2775
Lloyd Pique542307f2018-10-19 13:24:08 -07002776 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 sp<IGraphicBufferProducer> producer;
2778 sp<IGraphicBufferProducer> bqProducer;
2779 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002780 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002781
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002783 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 // Virtual displays without a surface are dormant:
2785 // they have external state (layer stack, projection,
2786 // etc.) but no internal state (i.e. a DisplayDevice).
2787 if (state.surface != nullptr) {
2788 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002790 int width = 0;
2791 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2792 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2793 int height = 0;
2794 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2795 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2796 int intFormat = 0;
2797 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2798 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002799 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002800
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801 displayId =
2802 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002803 }
2804
2805 // TODO: Plumb requested format back up to consumer
2806
2807 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002808 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002809 bqProducer, bqConsumer,
2810 state.displayName);
2811
2812 dispSurface = vds;
2813 producer = vds;
2814 }
2815 } else {
2816 ALOGE_IF(state.surface != nullptr,
2817 "adding a supported display, but rendering "
2818 "surface is provided (%p), ignoring it",
2819 state.surface.get());
2820
Dominik Laskowski075d3172018-05-24 15:50:06 -07002821 displayId = state.displayId;
2822 LOG_ALWAYS_FATAL_IF(!displayId);
2823 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002824 producer = bqProducer;
2825 }
2826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002827 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002830 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002832 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002833 LOG_ALWAYS_FATAL_IF(!displayId);
2834
2835 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002836 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002838 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002839 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002840 }
2841 }
2842 }
2843 }
2844 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002845
2846 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002847}
2848
Mathias Agopian87baae12012-07-31 12:38:26 -07002849void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002850{
Dan Stoza7dde5992015-05-22 09:51:44 -07002851 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002852 mCurrentState.traverseInZOrder([](Layer* layer) {
2853 layer->notifyAvailableFrames();
2854 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 /*
2857 * Traversal of the children
2858 * (perform the transaction for each of them if needed)
2859 */
2860
Robert Carr720e5062018-07-30 17:45:14 -07002861 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002862 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002865 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
2867 const uint32_t flags = layer->doTransaction(0);
2868 if (flags & Layer::eVisibleRegion)
2869 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002870
2871 if (flags & Layer::eInputInfoChanged) {
2872 inputChanged = true;
2873 }
Robert Carr2047fae2016-11-28 14:09:09 -08002874 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 }
2876
2877 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002878 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 */
2880
Mathias Agopiane57f2922012-08-09 16:29:12 -07002881 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002882 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002883 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002886 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002887 // The transform hint might have changed for some layers
2888 // (either because a display has changed, or because a layer
2889 // as changed).
2890 //
2891 // Walk through all the layers in currentLayers,
2892 // and update their transform hint.
2893 //
2894 // If a layer is visible only on a single display, then that
2895 // display is used to calculate the hint, otherwise we use the
2896 // default display.
2897 //
2898 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2899 // the hint is set before we acquire a buffer from the surface texture.
2900 //
2901 // NOTE: layer transactions have taken place already, so we use their
2902 // drawing state. However, SurfaceFlinger's own transaction has not
2903 // happened yet, so we must use the current state layer list
2904 // (soon to become the drawing state list).
2905 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002907 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002908 bool first = true;
2909 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002910 // NOTE: we rely on the fact that layers are sorted by
2911 // layerStack first (so we don't have to traverse the list
2912 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002913 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002914 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002915 currentlayerStack = layerStack;
2916 // figure out if this layerstack is mirrored
2917 // (more than one display) if so, pick the default display,
2918 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002919 hintDisplay = nullptr;
2920 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002921 if (display->getCompositionDisplay()
2922 ->belongsInOutput(layer->getLayerStack(),
2923 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002924 if (hintDisplay) {
2925 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002926 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002927 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002928 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002929 }
2930 }
2931 }
2932 }
Chet Haase91d25932013-04-11 15:24:55 -07002933
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002935 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2936 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002937
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002938 // could be null when this layer is using a layerStack
2939 // that is not visible on any display. Also can occur at
2940 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002941 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002942 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002943
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002944 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002945 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002946 if (hintDisplay) {
2947 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002948 }
Robert Carr2047fae2016-11-28 14:09:09 -08002949
2950 first = false;
2951 });
Mathias Agopian84300952012-11-21 16:02:13 -08002952 }
2953
2954
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 /*
2956 * Perform our own transaction if needed
2957 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958
2959 if (mLayersAdded) {
2960 mLayersAdded = false;
2961 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002962 mVisibleRegionsDirty = true;
2963 }
2964
2965 // some layers might have been removed, so
2966 // we need to update the regions they're exposing.
2967 if (mLayersRemoved) {
2968 mLayersRemoved = false;
2969 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002970 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002971 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002972 // this layer is not visible anymore
2973 // TODO: we could traverse the tree from front to back and
2974 // compute the actual visible region
2975 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 Region visibleReg;
2977 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002978 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002979 }
Robert Carr2047fae2016-11-28 14:09:09 -08002980 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981 }
2982
2983 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002984
Vishnu Nairde19f852018-12-18 16:11:53 -08002985 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002986 updateInputWindows();
2987 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002988 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002989
Riley Andrews03414a12014-07-01 14:22:59 -07002990 updateCursorAsync();
2991}
2992
Robert Carr720e5062018-07-30 17:45:14 -07002993void SurfaceFlinger::updateInputWindows() {
2994 ATRACE_CALL();
2995
Vishnu Nairde19f852018-12-18 16:11:53 -08002996 if (mInputFlinger == nullptr) {
2997 return;
2998 }
2999
Robert Carr720e5062018-07-30 17:45:14 -07003000 Vector<InputWindowInfo> inputHandles;
3001
3002 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3003 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003004 // When calculating the screen bounds we ignore the transparent region since it may
3005 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003006 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003007 }
3008 });
3009 mInputFlinger->setInputWindows(inputHandles);
3010}
3011
chaviwfbe5d9c2018-12-26 12:23:37 -08003012void SurfaceFlinger::executeInputWindowCommands() {
3013 if (!mInputFlinger) {
3014 return;
3015 }
3016
3017 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3018 if (transferTouchFocusCommand.fromToken != nullptr &&
3019 transferTouchFocusCommand.toToken != nullptr &&
3020 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3021 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3022 transferTouchFocusCommand.toToken);
3023 }
3024 }
3025
3026 mInputWindowCommands.clear();
3027}
3028
Riley Andrews03414a12014-07-01 14:22:59 -07003029void SurfaceFlinger::updateCursorAsync()
3030{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003031 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003032 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003033 continue;
3034 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3037 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003038 }
3039 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003040}
3041
chaviw61626f22018-11-15 16:26:27 -08003042void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3043 if (layer->hasReadyFrame()) {
3044 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3045 if (layer->shouldPresentNow(expectedPresentTime)) {
3046 bool ignored = false;
3047 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3048 }
3049 }
3050 layer->releasePendingBuffer(systemTime());
3051}
3052
Mathias Agopian4fec8732012-06-29 14:12:52 -07003053void SurfaceFlinger::commitTransaction()
3054{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003055 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 for (const auto& l : mLayersPendingRemoval) {
3058 recordBufferingStats(l->getName().string(),
3059 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003060
3061 // We need to release the HWC layers when the Layer is removed
3062 // from the current state otherwise the HWC layer just continues
3063 // showing at its last configured state until we eventually
3064 // abandon the buffer queue.
3065 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003066 l->destroyHwcLayersForAllDisplays();
3067 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003068 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003069 }
3070 mLayersPendingRemoval.clear();
3071 }
3072
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003073 // If this transaction is part of a window animation then the next frame
3074 // we composite should be considered an animation as well.
3075 mAnimCompositionPending = mAnimTransactionPending;
3076
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003078 // clear the "changed" flags in current state
3079 mCurrentState.colorMatrixChanged = false;
3080
Robert Carr1f0a16a2016-10-24 16:27:39 -07003081 mDrawingState.traverseInZOrder([](Layer* layer) {
3082 layer->commitChildList();
3083 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003084 mTransactionPending = false;
3085 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003086 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087}
3088
Lloyd Pique32cbe282018-10-19 13:09:22 -07003089void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003090 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003091 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003092 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003093
Lloyd Pique32cbe282018-10-19 13:09:22 -07003094 auto display = displayDevice->getCompositionDisplay();
3095
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 Region aboveOpaqueLayers;
3097 Region aboveCoveredLayers;
3098 Region dirty;
3099
Mathias Agopian87baae12012-07-31 12:38:26 -07003100 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101
Robert Carr2047fae2016-11-28 14:09:09 -08003102 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003103 // start with the whole surface at its current location
3104 const Layer::State& s(layer->getDrawingState());
3105
Jesse Hall01e29052013-02-19 16:13:35 -08003106 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003107 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003108 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003109 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003110
Mathias Agopianab028732010-03-16 16:41:46 -07003111 /*
3112 * opaqueRegion: area of a surface that is fully opaque.
3113 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003115
3116 /*
3117 * visibleRegion: area of a surface that is visible on screen
3118 * and not fully transparent. This is essentially the layer's
3119 * footprint minus the opaque regions above it.
3120 * Areas covered by a translucent surface are considered visible.
3121 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003123
3124 /*
3125 * coveredRegion: area of a surface that is covered by all
3126 * visible regions above it (which includes the translucent areas).
3127 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003129
Jesse Halla8026d22012-09-25 13:25:04 -07003130 /*
3131 * transparentRegion: area of a surface that is hinted to be completely
3132 * transparent. This is only used to tell when the layer has no visible
3133 * non-transparent regions and can be removed from the layer list. It
3134 * does not affect the visibleRegion of this layer or any layers
3135 * beneath it. The hint may not be correct if apps don't respect the
3136 * SurfaceView restrictions (which, sadly, some don't).
3137 */
3138 Region transparentRegion;
3139
Mathias Agopianab028732010-03-16 16:41:46 -07003140
3141 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003142 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003143 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003145
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003147 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003148 if (!visibleRegion.isEmpty()) {
3149 // Remove the transparent area from the visible region
3150 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003151 if (tr.preserveRects()) {
3152 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003153 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003154 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003155 // transformation too complex, can't do the
3156 // transparent region optimization.
3157 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003158 }
Mathias Agopianab028732010-03-16 16:41:46 -07003159 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160
Mathias Agopianab028732010-03-16 16:41:46 -07003161 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003163 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003164 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003165 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003166 // the opaque region is the layer's footprint
3167 opaqueRegion = visibleRegion;
3168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 }
3170 }
3171
Robert Carre5f4f692018-01-12 13:12:28 -08003172 if (visibleRegion.isEmpty()) {
3173 layer->clearVisibilityRegions();
3174 return;
3175 }
3176
Mathias Agopianab028732010-03-16 16:41:46 -07003177 // Clip the covered region to the visible region
3178 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3179
3180 // Update aboveCoveredLayers for next (lower) layer
3181 aboveCoveredLayers.orSelf(visibleRegion);
3182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 // subtract the opaque region covered by the layers above us
3184 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185
3186 // compute this layer's dirty region
3187 if (layer->contentDirty) {
3188 // we need to invalidate the whole region
3189 dirty = visibleRegion;
3190 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003191 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192 layer->contentDirty = false;
3193 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003194 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003195 * the exposed region consists of two components:
3196 * 1) what's VISIBLE now and was COVERED before
3197 * 2) what's EXPOSED now less what was EXPOSED before
3198 *
3199 * note that (1) is conservative, we start with the whole
3200 * visible region but only keep what used to be covered by
3201 * something -- which mean it may have been exposed.
3202 *
3203 * (2) handles areas that were not covered by anything but got
3204 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003205 */
Mathias Agopianab028732010-03-16 16:41:46 -07003206 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003207 const Region oldVisibleRegion = layer->visibleRegion;
3208 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003209 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3210 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 }
3212 dirty.subtractSelf(aboveOpaqueLayers);
3213
3214 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003215 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216
Mathias Agopianab028732010-03-16 16:41:46 -07003217 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003219
Jesse Halla8026d22012-09-25 13:25:04 -07003220 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 layer->setVisibleRegion(visibleRegion);
3222 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003223 layer->setVisibleNonTransparentRegion(
3224 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003225 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226
Mathias Agopian87baae12012-07-31 12:38:26 -07003227 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228}
3229
Chia-I Wuab0c3192017-08-01 11:29:00 -07003230void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003231 for (const auto& [token, displayDevice] : mDisplays) {
3232 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003233 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003234 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003235 }
3236 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003237}
3238
Daniel Solomon42d04562019-01-20 21:03:19 -08003239void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3240 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3241 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3242 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3243 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3244 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3245 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3246 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3247 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3248 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3249 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3250 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3251 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3252}
3253
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003256 ALOGV("handlePageFlip");
3257
Brian Andersond6927fb2016-07-23 23:37:30 -07003258 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259
Mathias Agopian4fec8732012-06-29 14:12:52 -07003260 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003262 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003263
3264 // Store the set of layers that need updates. This set must not change as
3265 // buffers are being latched, as this could result in a deadlock.
3266 // Example: Two producers share the same command stream and:
3267 // 1.) Layer 0 is latched
3268 // 2.) Layer 0 gets a new frame
3269 // 2.) Layer 1 gets a new frame
3270 // 3.) Layer 1 is latched.
3271 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3272 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003273 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003274 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003275 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003276 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3277 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003278 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003279 } else {
3280 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003281 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003282 } else {
3283 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003284 }
Robert Carr2047fae2016-11-28 14:09:09 -08003285 });
3286
Lloyd Piquef2c79392018-12-20 16:23:33 -08003287 if (!mLayersWithQueuedFrames.empty()) {
3288 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3289 // writes to Layer current state. See also b/119481871
3290 Mutex::Autolock lock(mStateLock);
3291
3292 for (auto& layer : mLayersWithQueuedFrames) {
3293 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3294 layer->useSurfaceDamage();
3295 invalidateLayerStack(layer, dirty);
3296 if (layer->isBufferLatched()) {
3297 newDataLatched = true;
3298 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003299 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003300 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003301
Alec Mouri86770e52018-09-24 22:40:58 +00003302 // Clear the renderengine fence here...
3303 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3304 // clear instead of sp::clear.
3305 getBE().flushFence = Fence::NO_FENCE;
3306
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003307 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003308
Vishnu Nairde19f852018-12-18 16:11:53 -08003309 if (visibleRegions) {
3310 // Update input window info if the layer receives its first buffer.
3311 updateInputWindows();
3312 }
3313
Dan Stoza6b9454d2014-11-07 16:00:59 -08003314 // If we will need to wake up at some time in the future to deal with a
3315 // queued frame that shouldn't be displayed during this vsync period, wake
3316 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003317 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003318 signalLayerUpdate();
3319 }
3320
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003321 // enter boot animation on first buffer latch
3322 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3323 ALOGI("Enter boot animation");
3324 mBootStage = BootStage::BOOTANIMATION;
3325 }
3326
Dan Stoza6b9454d2014-11-07 16:00:59 -08003327 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003328 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329}
3330
Mathias Agopianad456f92011-01-13 17:53:01 -08003331void SurfaceFlinger::invalidateHwcGeometry()
3332{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003333 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003334}
3335
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003337 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003338 auto display = displayDevice->getCompositionDisplay();
3339
Dan Stoza71433162014-02-04 16:22:36 -08003340 // We only need to actually compose the display if:
3341 // 1) It is being handled by hardware composer, which may need this to
3342 // keep its virtual display state machine in sync, or
3343 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003345 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003346 return;
3347 }
3348
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 ALOGV("doDisplayComposition");
Alec Mouri79108df2019-02-04 19:33:44 +00003350 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003351
3352 // swap buffers (presentation)
Alec Mouri79108df2019-02-04 19:33:44 +00003353 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Alec Mouri79108df2019-02-04 19:33:44 +00003356bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003357 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003358
Lloyd Pique32cbe282018-10-19 13:09:22 -07003359 auto display = displayDevice->getCompositionDisplay();
3360 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003361 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003362
3363 const Region bounds(displayState.bounds);
3364 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003365 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003366 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003367
Peiyong Lind3788632018-09-18 16:01:31 -07003368 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003369 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003370
Alec Mouri79108df2019-02-04 19:33:44 +00003371 // Framebuffer will live in this scope for GPU composition.
3372 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003373
Dan Stoza9e56aa02015-11-02 13:00:03 -08003374 if (hasClientComposition) {
3375 ALOGV("hasClientComposition");
3376
Alec Mouri79108df2019-02-04 19:33:44 +00003377 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003378
3379 if (buf == nullptr) {
3380 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3381 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003382 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003383 return false;
3384 }
3385
Alec Mouri79108df2019-02-04 19:33:44 +00003386 // Bind the framebuffer in this scope.
3387 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3388 buf->getNativeBuffer());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003389
Alec Mouri79108df2019-02-04 19:33:44 +00003390 if (fbo->getStatus() != NO_ERROR) {
3391 ALOGW("Binding buffer for display [%s] failed with status: %d",
3392 displayDevice->getDisplayName().c_str(), fbo->getStatus());
3393 return false;
3394 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003395
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003396 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003397 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003398 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003399 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003400 }
Alec Mouri79108df2019-02-04 19:33:44 +00003401 getRenderEngine().setOutputDataSpace(outputDataspace);
3402 getRenderEngine().setDisplayMaxLuminance(
3403 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003404
Lloyd Pique441d5042018-10-18 16:49:51 -07003405 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003406 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003407 getHwComposer()
3408 .hasDisplayCapability(displayId,
3409 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003410
Peiyong Lind3788632018-09-18 16:01:31 -07003411 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003412 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3413 if (applyColorMatrix) {
Alec Mouri79108df2019-02-04 19:33:44 +00003414 colorMatrix = mDrawingState.colorMatrix;
3415 }
3416
3417 display->getRenderSurface()->setViewportAndProjection();
3418
3419 // Never touch the framebuffer if we don't have any framebuffer layers
3420 if (hasDeviceComposition) {
3421 // when using overlays, we assume a fully transparent framebuffer
3422 // NOTE: we could reduce how much we need to clear, for instance
3423 // remove where there are opaque FB layers. however, on some
3424 // GPUs doing a "clean slate" clear might be more efficient.
3425 // We'll revisit later if needed.
3426 getRenderEngine().clearWithColor(0, 0, 0, 0);
3427 } else {
3428 // we start with the whole screen area and remove the scissor part
3429 // we're left with the letterbox region
3430 // (common case is that letterbox ends-up being empty)
3431 const Region letterbox = bounds.subtract(displayState.scissor);
3432
3433 // compute the area to clear
3434 const Region region = displayState.undefinedRegion.merge(letterbox);
3435
3436 // screen is already cleared here
3437 if (!region.isEmpty()) {
3438 // can happen with SurfaceView
3439 drawWormhole(region);
3440 }
3441 }
3442
3443 const Rect& bounds = displayState.bounds;
3444 const Rect& scissor = displayState.scissor;
3445 if (scissor != bounds) {
3446 // scissor doesn't match the screen's dimensions, so we
3447 // need to clear everything outside of it and enable
3448 // the GL scissor so we don't draw anything where we shouldn't
3449
3450 // enable scissor for this frame
3451 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003452 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003453 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003454
Mathias Agopian85d751c2012-08-29 16:59:24 -07003455 /*
3456 * and then, render the layers targeted at the framebuffer
3457 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003458
Dan Stoza9e56aa02015-11-02 13:00:03 -08003459 ALOGV("Rendering client layers");
Alec Mouri79108df2019-02-04 19:33:44 +00003460 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003461 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003462 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri79108df2019-02-04 19:33:44 +00003463 const Region clip(bounds.intersect(displayTransform.transform(layer->visibleRegion)));
David Sodmanc1498e62018-09-12 14:36:26 -07003464 ALOGV("Layer: %s", layer->getName().string());
3465 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003466 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003467 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003468 case HWC2::Composition::Cursor:
3469 case HWC2::Composition::Device:
3470 case HWC2::Composition::Sideband:
3471 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003472 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003473 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003474 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003475 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003476 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003477 // never clear the very first layer since we're
3478 // guaranteed the FB is already cleared
Alec Mouri79108df2019-02-04 19:33:44 +00003479 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003480 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003481 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003482 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003483 case HWC2::Composition::Client: {
Alec Mouri79108df2019-02-04 19:33:44 +00003484 if (layer->hasColorTransform()) {
3485 mat4 tmpMatrix;
3486 if (applyColorMatrix) {
3487 tmpMatrix = mDrawingState.colorMatrix;
3488 }
3489 tmpMatrix *= layer->getColorTransform();
3490 getRenderEngine().setColorTransform(tmpMatrix);
3491 } else {
3492 getRenderEngine().setColorTransform(colorMatrix);
Peiyong Lind3788632018-09-18 16:01:31 -07003493 }
Alec Mouri79108df2019-02-04 19:33:44 +00003494 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003495 break;
3496 }
3497 default:
3498 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003499 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003500 } else {
3501 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003502 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003503 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003504 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003505
Alec Mouri79108df2019-02-04 19:33:44 +00003506 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003507 if (hasClientComposition) {
Alec Mouri79108df2019-02-04 19:33:44 +00003508 getRenderEngine().setColorTransform(mat4());
3509 getRenderEngine().disableScissor();
3510 display->getRenderSurface()->finishBuffer();
3511 // Clear out error flags here so that we don't wait until next
3512 // composition to log.
3513 getRenderEngine().checkErrors();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003514 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003515 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516}
3517
Chia-I Wu28e3a252018-09-07 12:05:02 -07003518void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003519 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003520 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521}
3522
Dan Stoza7d89d062015-04-30 13:29:25 -07003523status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003524 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003525 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003526 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003527 const sp<Layer>& parent,
3528 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003529{
Dan Stoza7d89d062015-04-30 13:29:25 -07003530 // add this layer to the current state list
3531 {
3532 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003533 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003534 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3535 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003536 return NO_MEMORY;
3537 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003538 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003539 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003540 } else if (parent == nullptr) {
3541 lbc->onRemovedFromCurrentState();
3542 } else if (parent->isRemovedFromCurrentState()) {
3543 parent->addChild(lbc);
3544 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003545 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003546 parent->addChild(lbc);
3547 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003548
Yiwei Zhang243b3782018-05-15 17:40:04 -07003549 if (gbc != nullptr) {
3550 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3551 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3552 mMaxGraphicBufferProducerListSize,
3553 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3554 mGraphicBufferProducerList.size(),
3555 mMaxGraphicBufferProducerListSize, mNumLayers);
3556 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003557 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003558 }
3559
Mathias Agopian96f08192010-06-02 23:28:45 -07003560 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003561 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003562
Dan Stoza7d89d062015-04-30 13:29:25 -07003563 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003564}
3565
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003566uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003567 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003568}
3569
Mathias Agopian3f844832013-08-07 21:24:32 -07003570uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003571 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572}
3573
Mathias Agopian3f844832013-08-07 21:24:32 -07003574uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003575 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003576}
3577
3578uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003579 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003580 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003581 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003583 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 }
3585 return old;
3586}
3587
Marissa Wall713b63f2018-10-17 15:42:43 -07003588bool SurfaceFlinger::flushTransactionQueues() {
3589 Mutex::Autolock _l(mStateLock);
3590 auto it = mTransactionQueues.begin();
3591 while (it != mTransactionQueues.end()) {
3592 auto& [applyToken, transactionQueue] = *it;
3593
3594 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003595 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3596 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003597 break;
3598 }
chaviw273171b2018-12-26 11:46:30 -08003599 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003600 transactionQueue.pop();
3601 }
3602
3603 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3604 }
3605 return mTransactionQueues.empty();
3606}
3607
chaviwca27f252018-02-06 16:46:39 -08003608bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3609 for (const ComposerState& state : states) {
3610 // Here we need to check that the interface we're given is indeed
3611 // one of our own. A malicious client could give us a nullptr
3612 // IInterface, or one of its own or even one of our own but a
3613 // different type. All these situations would cause us to crash.
3614 if (state.client == nullptr) {
3615 return true;
3616 }
3617
3618 sp<IBinder> binder = IInterface::asBinder(state.client);
3619 if (binder == nullptr) {
3620 return true;
3621 }
3622
3623 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3624 return true;
3625 }
3626 }
3627 return false;
3628}
3629
Marissa Wall17b4e452018-12-26 16:32:34 -08003630bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3631 const Vector<ComposerState>& states) {
3632 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3633 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3634 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3635 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3636 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3637 return false;
3638 }
3639
Marissa Wall713b63f2018-10-17 15:42:43 -07003640 for (const ComposerState& state : states) {
3641 const layer_state_t& s = state.state;
3642 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3643 continue;
3644 }
3645 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003646 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003647 }
3648 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003649 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003650}
3651
3652void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3653 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003654 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003655 const InputWindowCommands& inputWindowCommands,
3656 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003657 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003658 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003659
chaviwca27f252018-02-06 16:46:39 -08003660 if (containsAnyInvalidClientState(states)) {
3661 return;
3662 }
3663
Marissa Wall713b63f2018-10-17 15:42:43 -07003664 // If its TransactionQueue already has a pending TransactionState or if it is pending
3665 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003666 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3667 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003668 setTransactionFlags(eTransactionNeeded);
3669 return;
3670 }
3671
chaviw273171b2018-12-26 11:46:30 -08003672 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003673}
3674
3675void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003676 const Vector<DisplayState>& displays, uint32_t flags,
3677 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003678 uint32_t transactionFlags = 0;
3679
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003680 if (flags & eAnimation) {
3681 // For window updates that are part of an animation we must wait for
3682 // previous animation "frames" to be handled.
3683 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003684 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003685 if (CC_UNLIKELY(err != NO_ERROR)) {
3686 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003687 // caller after a few seconds.
3688 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3689 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003690 mAnimTransactionPending = false;
3691 break;
3692 }
3693 }
3694 }
3695
chaviwca27f252018-02-06 16:46:39 -08003696 for (const DisplayState& display : displays) {
3697 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003698 }
3699
Marissa Walle2ffb422018-10-12 11:33:52 -07003700 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003701 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003702 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003703 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003704 // If the state doesn't require a traversal and there are callbacks, send them now
3705 if (!(clientStateFlags & eTraversalNeeded)) {
3706 mTransactionCompletedThread.sendCallbacks();
3707 }
3708 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003709
chaviw273171b2018-12-26 11:46:30 -08003710 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3711
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003712 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3713 // anyway. This can be used as a flush mechanism for previous async transactions.
3714 // Empty animation transaction can be used to simulate back-pressure, so also force a
3715 // transaction for empty animation transactions.
3716 if (transactionFlags == 0 &&
3717 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003718 transactionFlags = eTransactionNeeded;
3719 }
3720
Mathias Agopian386aa982011-11-07 21:58:03 -08003721 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003722 if (mInterceptor->isEnabled()) {
3723 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003724 }
Irvel468051e2016-06-13 16:44:44 -07003725
Mathias Agopian386aa982011-11-07 21:58:03 -08003726 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003727 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3728 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003729 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003730
3731 // if this is a synchronous transaction, wait for it to take effect
3732 // before returning.
3733 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003734 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003735 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003736 if (flags & eAnimation) {
3737 mAnimTransactionPending = true;
3738 }
3739 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003740 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3741 if (CC_UNLIKELY(err != NO_ERROR)) {
3742 // just in case something goes wrong in SF, return to the
3743 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003744 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3745 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003746 break;
3747 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003748 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749 }
3750}
3751
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003752uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3753 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3754 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003755
Mathias Agopiane57f2922012-08-09 16:29:12 -07003756 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003757 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3758
3759 const uint32_t what = s.what;
3760 if (what & DisplayState::eSurfaceChanged) {
3761 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3762 state.surface = s.surface;
3763 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003764 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003766 if (what & DisplayState::eLayerStackChanged) {
3767 if (state.layerStack != s.layerStack) {
3768 state.layerStack = s.layerStack;
3769 flags |= eDisplayTransactionNeeded;
3770 }
3771 }
3772 if (what & DisplayState::eDisplayProjectionChanged) {
3773 if (state.orientation != s.orientation) {
3774 state.orientation = s.orientation;
3775 flags |= eDisplayTransactionNeeded;
3776 }
3777 if (state.frame != s.frame) {
3778 state.frame = s.frame;
3779 flags |= eDisplayTransactionNeeded;
3780 }
3781 if (state.viewport != s.viewport) {
3782 state.viewport = s.viewport;
3783 flags |= eDisplayTransactionNeeded;
3784 }
3785 }
3786 if (what & DisplayState::eDisplaySizeChanged) {
3787 if (state.width != s.width) {
3788 state.width = s.width;
3789 flags |= eDisplayTransactionNeeded;
3790 }
3791 if (state.height != s.height) {
3792 state.height = s.height;
3793 flags |= eDisplayTransactionNeeded;
3794 }
3795 }
3796
Mathias Agopiane57f2922012-08-09 16:29:12 -07003797 return flags;
3798}
3799
Robert Carrd4ae7f32018-06-07 16:10:57 -07003800bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3801 IPCThreadState* ipc = IPCThreadState::self();
3802 const int pid = ipc->getCallingPid();
3803 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003804 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003805 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003806 return false;
3807 }
3808 return true;
3809}
3810
chaviwca27f252018-02-06 16:46:39 -08003811uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3812 const layer_state_t& s = composerState.state;
3813 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3814
Mathias Agopian13127d82013-03-05 17:47:11 -08003815 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003816 if (layer == nullptr) {
3817 return 0;
3818 }
3819
chaviw8b3871a2017-11-01 17:41:01 -07003820 uint32_t flags = 0;
3821
Garfield Tan8a3083e2018-12-03 13:21:07 -08003822 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003823 bool geometryAppliesWithResize =
3824 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003825
3826 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3827 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003828 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003829 layer->pushPendingState();
3830 }
3831
chaviw8b3871a2017-11-01 17:41:01 -07003832 if (what & layer_state_t::ePositionChanged) {
3833 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3834 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 }
3837 if (what & layer_state_t::eLayerChanged) {
3838 // NOTE: index needs to be calculated before we update the state
3839 const auto& p = layer->getParent();
3840 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003841 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003842 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003843 mCurrentState.layersSortedByZ.removeAt(idx);
3844 mCurrentState.layersSortedByZ.add(layer);
3845 // we need traversal (state changed)
3846 // AND transaction (list changed)
3847 flags |= eTransactionNeeded|eTraversalNeeded;
3848 }
chaviw8b3871a2017-11-01 17:41:01 -07003849 } else {
3850 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003851 flags |= eTransactionNeeded|eTraversalNeeded;
3852 }
3853 }
chaviw8b3871a2017-11-01 17:41:01 -07003854 }
3855 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003856 // NOTE: index needs to be calculated before we update the state
3857 const auto& p = layer->getParent();
3858 if (p == nullptr) {
3859 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3860 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3861 mCurrentState.layersSortedByZ.removeAt(idx);
3862 mCurrentState.layersSortedByZ.add(layer);
3863 // we need traversal (state changed)
3864 // AND transaction (list changed)
3865 flags |= eTransactionNeeded|eTraversalNeeded;
3866 }
3867 } else {
3868 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3869 flags |= eTransactionNeeded|eTraversalNeeded;
3870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 }
3872 }
3873 if (what & layer_state_t::eSizeChanged) {
3874 if (layer->setSize(s.w, s.h)) {
3875 flags |= eTraversalNeeded;
3876 }
3877 }
3878 if (what & layer_state_t::eAlphaChanged) {
3879 if (layer->setAlpha(s.alpha))
3880 flags |= eTraversalNeeded;
3881 }
3882 if (what & layer_state_t::eColorChanged) {
3883 if (layer->setColor(s.color))
3884 flags |= eTraversalNeeded;
3885 }
Peiyong Lind3788632018-09-18 16:01:31 -07003886 if (what & layer_state_t::eColorTransformChanged) {
3887 if (layer->setColorTransform(s.colorTransform)) {
3888 flags |= eTraversalNeeded;
3889 }
3890 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003891 if (what & layer_state_t::eBackgroundColorChanged) {
3892 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3893 flags |= eTraversalNeeded;
3894 }
3895 }
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003897 // TODO: b/109894387
3898 //
3899 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3900 // rotation. To see the problem observe that if we have a square parent, and a child
3901 // of the same size, then we rotate the child 45 degrees around it's center, the child
3902 // must now be cropped to a non rectangular 8 sided region.
3903 //
3904 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3905 // private API, and the WindowManager only uses rotation in one case, which is on a top
3906 // level layer in which cropping is not an issue.
3907 //
3908 // However given that abuse of rotation matrices could lead to surfaces extending outside
3909 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3910 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3911 // transformations.
3912 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003913 flags |= eTraversalNeeded;
3914 }
3915 if (what & layer_state_t::eTransparentRegionChanged) {
3916 if (layer->setTransparentRegionHint(s.transparentRegion))
3917 flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eFlagsChanged) {
3920 if (layer->setFlags(s.flags, s.mask))
3921 flags |= eTraversalNeeded;
3922 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003923 if (what & layer_state_t::eCropChanged_legacy) {
3924 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003925 flags |= eTraversalNeeded;
3926 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003927 if (what & layer_state_t::eCornerRadiusChanged) {
3928 if (layer->setCornerRadius(s.cornerRadius))
3929 flags |= eTraversalNeeded;
3930 }
chaviw8b3871a2017-11-01 17:41:01 -07003931 if (what & layer_state_t::eLayerStackChanged) {
3932 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3933 // We only allow setting layer stacks for top level layers,
3934 // everything else inherits layer stack from its parent.
3935 if (layer->hasParent()) {
3936 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3937 layer->getName().string());
3938 } else if (idx < 0) {
3939 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3940 "that also does not appear in the top level layer list. Something"
3941 " has gone wrong.", layer->getName().string());
3942 } else if (layer->setLayerStack(s.layerStack)) {
3943 mCurrentState.layersSortedByZ.removeAt(idx);
3944 mCurrentState.layersSortedByZ.add(layer);
3945 // we need traversal (state changed)
3946 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003947 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003948 }
3949 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003950 if (what & layer_state_t::eDeferTransaction_legacy) {
3951 if (s.barrierHandle_legacy != nullptr) {
3952 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3953 } else if (s.barrierGbp_legacy != nullptr) {
3954 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003955 if (authenticateSurfaceTextureLocked(gbp)) {
3956 const auto& otherLayer =
3957 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003958 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003959 } else {
3960 ALOGE("Attempt to defer transaction to to an"
3961 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003962 }
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 // We don't trigger a traversal here because if no other state is
3965 // changed, we don't want this to cause any more work
3966 }
3967 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003968 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003969 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003970 if (!hadParent) {
3971 mCurrentState.layersSortedByZ.remove(layer);
3972 }
chaviw8b3871a2017-11-01 17:41:01 -07003973 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003974 }
chaviw8b3871a2017-11-01 17:41:01 -07003975 }
3976 if (what & layer_state_t::eReparentChildren) {
3977 if (layer->reparentChildren(s.reparentHandle)) {
3978 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003979 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003980 }
chaviw8b3871a2017-11-01 17:41:01 -07003981 if (what & layer_state_t::eDetachChildren) {
3982 layer->detachChildren();
3983 }
3984 if (what & layer_state_t::eOverrideScalingModeChanged) {
3985 layer->setOverrideScalingMode(s.overrideScalingMode);
3986 // We don't trigger a traversal here because if no other state is
3987 // changed, we don't want this to cause any more work
3988 }
Marissa Wall61c58622018-07-18 10:12:20 -07003989 if (what & layer_state_t::eTransformChanged) {
3990 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3991 }
3992 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3993 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3994 flags |= eTraversalNeeded;
3995 }
3996 if (what & layer_state_t::eCropChanged) {
3997 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3998 }
Marissa Wall861616d2018-10-22 12:52:23 -07003999 if (what & layer_state_t::eFrameChanged) {
4000 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4001 }
Marissa Wall61c58622018-07-18 10:12:20 -07004002 if (what & layer_state_t::eBufferChanged) {
4003 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
4004 }
4005 if (what & layer_state_t::eAcquireFenceChanged) {
4006 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4007 }
4008 if (what & layer_state_t::eDataspaceChanged) {
4009 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4010 }
4011 if (what & layer_state_t::eHdrMetadataChanged) {
4012 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4013 }
4014 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4015 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4016 }
4017 if (what & layer_state_t::eApiChanged) {
4018 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4019 }
4020 if (what & layer_state_t::eSidebandStreamChanged) {
4021 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4022 }
Robert Carr720e5062018-07-30 17:45:14 -07004023 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004024 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4025 layer->setInputInfo(s.inputInfo);
4026 flags |= eTraversalNeeded;
4027 } else {
4028 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4029 }
Robert Carr720e5062018-07-30 17:45:14 -07004030 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004031 if (what & layer_state_t::eMetadataChanged) {
4032 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4033 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004034 std::vector<sp<CallbackHandle>> callbackHandles;
4035 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4036 mTransactionCompletedThread.run();
4037 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4038 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4039 }
4040 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004041 if (what & layer_state_t::eCachedBufferChanged) {
4042 sp<GraphicBuffer> buffer =
4043 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4044 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4045 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004046 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4047 // Do not put anything that updates layer state or modifies flags after
4048 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004049 return flags;
4050}
4051
chaviw273171b2018-12-26 11:46:30 -08004052uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4053 uint32_t flags = 0;
4054 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4055 flags |= eTraversalNeeded;
4056 }
4057
4058 mInputWindowCommands.merge(inputWindowCommands);
4059 return flags;
4060}
4061
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004062status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4063 uint32_t h, PixelFormat format, uint32_t flags,
4064 LayerMetadata metadata, sp<IBinder>* handle,
4065 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004066 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004067 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004068 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004069 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004070 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004071
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072 status_t result = NO_ERROR;
4073
4074 sp<Layer> layer;
4075
Cody Northropbc755282017-03-31 12:00:08 -06004076 String8 uniqueName = getUniqueLayerName(name);
4077
Mathias Agopian3165cc22012-08-08 19:42:09 -07004078 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004079 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004080 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4081 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004084 case ISurfaceComposerClient::eFXSurfaceBufferState:
4085 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4086 break;
chaviw13fdc492017-06-27 12:40:18 -07004087 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004088 // check if buffer size is set for color layer.
4089 if (w > 0 || h > 0) {
4090 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4091 int(w), int(h));
4092 return BAD_VALUE;
4093 }
4094
chaviw13fdc492017-06-27 12:40:18 -07004095 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004096 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004097 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004098 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004099 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004100 // check if buffer size is set for container layer.
4101 if (w > 0 || h > 0) {
4102 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4103 int(w), int(h));
4104 return BAD_VALUE;
4105 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004106 result = createContainerLayer(client,
4107 uniqueName, w, h, flags,
4108 handle, &layer);
4109 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004110 default:
4111 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 break;
4113 }
4114
Dan Stoza7d89d062015-04-30 13:29:25 -07004115 if (result != NO_ERROR) {
4116 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004118
Chia-I Wuab0c3192017-08-01 11:29:00 -07004119 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4120 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004121 if (metadata.has(METADATA_WINDOW_TYPE)) {
4122 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4123 if (windowType == 441731) {
4124 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4125 layer->setPrimaryDisplayOnly();
4126 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004127 }
4128
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004129 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004130
Robert Carrb89ea9d2018-12-10 13:01:14 -08004131 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4132 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4133 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004134 if (result != NO_ERROR) {
4135 return result;
4136 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004137 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004138
4139 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004140 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004141}
4142
Cody Northropbc755282017-03-31 12:00:08 -06004143String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4144{
4145 bool matchFound = true;
4146 uint32_t dupeCounter = 0;
4147
4148 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4149 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4150
Dan Stoza436ccf32018-06-21 12:10:12 -07004151 // Grab the state lock since we're accessing mCurrentState
4152 Mutex::Autolock lock(mStateLock);
4153
Cody Northropbc755282017-03-31 12:00:08 -06004154 // Loop over layers until we're sure there is no matching name
4155 while (matchFound) {
4156 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004157 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004158 if (layer->getName() == uniqueName) {
4159 matchFound = true;
4160 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4161 }
4162 });
4163 }
4164
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004165 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4166 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004167
4168 return uniqueName;
4169}
4170
Marissa Wallfd668622018-05-10 10:21:13 -07004171status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4172 uint32_t w, uint32_t h, uint32_t flags,
4173 PixelFormat& format, sp<IBinder>* handle,
4174 sp<IGraphicBufferProducer>* gbp,
4175 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004176 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004177 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004178 case PIXEL_FORMAT_TRANSPARENT:
4179 case PIXEL_FORMAT_TRANSLUCENT:
4180 format = PIXEL_FORMAT_RGBA_8888;
4181 break;
4182 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004183 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 break;
4185 }
4186
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004187 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004188 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004189 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004190 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004191 *handle = layer->getHandle();
4192 *gbp = layer->getProducer();
4193 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004194 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004195
Marissa Wallfd668622018-05-10 10:21:13 -07004196 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004197 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004198}
4199
Marissa Wall61c58622018-07-18 10:12:20 -07004200status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4201 uint32_t w, uint32_t h, uint32_t flags,
4202 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004203 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004204 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004205 *handle = layer->getHandle();
4206 *outLayer = layer;
4207
4208 return NO_ERROR;
4209}
4210
chaviw13fdc492017-06-27 12:40:18 -07004211status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004212 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004213 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004214{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004215 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004216 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004217 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004218}
4219
Robert Carr6b3f6c52018-08-13 13:05:17 -07004220status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4221 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4222 sp<IBinder>* handle, sp<Layer>* outLayer)
4223{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004224 *outLayer =
4225 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004226 *handle = (*outLayer)->getHandle();
4227 return NO_ERROR;
4228}
4229
4230
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004231void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004232 mLayersPendingRemoval.add(layer);
4233 mLayersRemoved = true;
4234 setTransactionFlags(eTransactionNeeded);
4235}
4236
Robert Carr695d5282018-12-18 15:27:58 -08004237void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004238{
Robert Carr2e102c92018-10-23 12:11:15 -07004239 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004240 // If a layer has a parent, we allow it to out-live it's handle
4241 // with the idea that the parent holds a reference and will eventually
4242 // be cleaned up. However no one cleans up the top-level so we do so
4243 // here.
4244 if (layer->getParent() == nullptr) {
4245 mCurrentState.layersSortedByZ.remove(layer);
4246 }
4247 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004248 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004249}
4250
Mathias Agopianb60314a2012-04-10 22:09:54 -07004251// ---------------------------------------------------------------------------
4252
Andy McFadden13a082e2012-08-24 10:16:42 -07004253void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004254 const auto display = getDefaultDisplayDeviceLocked();
4255 if (!display) return;
4256
4257 const sp<IBinder> token = display->getDisplayToken().promote();
4258 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004259
Jesse Hall01e29052013-02-19 16:13:35 -08004260 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004261 Vector<ComposerState> state;
4262 Vector<DisplayState> displays;
4263 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004264 d.what = DisplayState::eDisplayProjectionChanged |
4265 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004266 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004267 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004268 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004269 d.frame.makeInvalid();
4270 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004271 d.width = 0;
4272 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004273 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004274 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004275
Dominik Laskowskie9774092018-12-11 10:04:24 -08004276 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004277
Dominik Laskowski83b88212018-12-11 13:34:06 -08004278 const nsecs_t vsyncPeriod = getVsyncPeriod();
4279 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004280
Brian Andersond0010582017-03-07 13:20:31 -08004281 // Use phase of 0 since phase is not known.
4282 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004283 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004284 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004285}
4286
4287void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004288 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 postMessageAsync(
4290 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004291}
4292
Dominik Laskowskie9774092018-12-11 10:04:24 -08004293void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004294 if (display->isVirtual()) {
4295 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004296 return;
4297 }
4298
Dominik Laskowski075d3172018-05-24 15:50:06 -07004299 const auto displayId = display->getId();
4300 LOG_ALWAYS_FATAL_IF(!displayId);
4301
Dominik Laskowski34157762018-10-31 13:07:19 -07004302 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303
4304 int currentMode = display->getPowerMode();
4305 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004306 return;
4307 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 display->setPowerMode(mode);
4310
Lloyd Pique4dccc412018-01-22 17:21:36 -08004311 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004312 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004313 }
4314
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004315 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004316 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004317 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004319 if (mUseScheduler) {
4320 mScheduler->onScreenAcquired(mAppConnectionHandle);
4321 } else {
4322 mEventThread->onScreenAcquired();
4323 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004324 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004326
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004327 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004328 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004329 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004330
4331 struct sched_param param = {0};
4332 param.sched_priority = 1;
4333 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4334 ALOGW("Couldn't set SCHED_FIFO on display on");
4335 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004336 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004337 // Turn off the display
4338 struct sched_param param = {0};
4339 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4340 ALOGW("Couldn't set SCHED_OTHER on display off");
4341 }
4342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004344 if (mUseScheduler) {
4345 mScheduler->disableHardwareVsync(true);
4346 } else {
4347 disableHardwareVsync(true); // also cancels any in-progress resync
4348 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004349 if (mUseScheduler) {
4350 mScheduler->onScreenReleased(mAppConnectionHandle);
4351 } else {
4352 mEventThread->onScreenReleased();
4353 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004354 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004355
Dominik Laskowski075d3172018-05-24 15:50:06 -07004356 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004357 mVisibleRegionsDirty = true;
4358 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004359 } else if (mode == HWC_POWER_MODE_DOZE ||
4360 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004361 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004362 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004363 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004364 if (mUseScheduler) {
4365 mScheduler->onScreenAcquired(mAppConnectionHandle);
4366 } else {
4367 mEventThread->onScreenAcquired();
4368 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004369 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004370 }
4371 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4372 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004373 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004374 if (mUseScheduler) {
4375 mScheduler->disableHardwareVsync(true);
4376 } else {
4377 disableHardwareVsync(true); // also cancels any in-progress resync
4378 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004379 if (mUseScheduler) {
4380 mScheduler->onScreenReleased(mAppConnectionHandle);
4381 } else {
4382 mEventThread->onScreenReleased();
4383 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004384 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004385 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004386 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004387 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004388 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004389 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004390
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004391 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004392 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004393 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004394 // Update refresh rate stats.
4395 mRefreshRateStats->setPowerMode(mode);
4396 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004397 }
4398
Dominik Laskowski34157762018-10-31 13:07:19 -07004399 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004400}
4401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004402void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004403 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004404 const auto display = getDisplayDevice(displayToken);
4405 if (!display) {
4406 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4407 displayToken.get());
4408 } else if (display->isVirtual()) {
4409 ALOGW("Attempt to set power mode %d for virtual display", mode);
4410 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004411 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004412 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004413 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004414}
4415
4416// ---------------------------------------------------------------------------
4417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4419 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004421
Mathias Agopianbd115332013-04-18 16:41:04 -07004422 IPCThreadState* ipc = IPCThreadState::self();
4423 const int pid = ipc->getCallingPid();
4424 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004425
Mathias Agopianbd115332013-04-18 16:41:04 -07004426 if ((uid != AID_SHELL) &&
4427 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4429 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004431 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004432 // (this would indicate SF is stuck, but we want to be able to
4433 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004434 status_t err = mStateLock.timedLock(s2ns(1));
4435 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004436 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437 StringAppendF(&result,
4438 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4439 "(no locks held)\n",
4440 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004441 }
4442
Dominik Laskowskic2867142019-01-21 11:33:38 -08004443 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004444
Dominik Laskowskic2867142019-01-21 11:33:38 -08004445 static const std::unordered_map<std::string, Dumper> dumpers = {
4446 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4447 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4448 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4449 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4450 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4451 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4452 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4453 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4454 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4455 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4456 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4457 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4458 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004459 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004460 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4461 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004462
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004464
Dominik Laskowskic2867142019-01-21 11:33:38 -08004465 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4466 (it->second)(args, asProto, result);
4467 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004468 if (asProto) {
4469 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4470 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4471 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004472 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004473 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004474 }
4475
Mathias Agopian9795c422009-08-26 16:36:26 -07004476 if (locked) {
4477 mStateLock.unlock();
4478 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 return NO_ERROR;
4482}
4483
Dominik Laskowskic2867142019-01-21 11:33:38 -08004484void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 mCurrentState.traverseInZOrder(
4486 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004487}
4488
Dominik Laskowskic2867142019-01-21 11:33:38 -08004489void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004490 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492 if (args.size() > 1) {
4493 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004494 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004495 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004496 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004497 }
Robert Carr2047fae2016-11-28 14:09:09 -08004498 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004499 } else {
4500 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004501 }
4502}
4503
Dominik Laskowskic2867142019-01-21 11:33:38 -08004504void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004505 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004506 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004507 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004508 }
Robert Carr2047fae2016-11-28 14:09:09 -08004509 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004510
Svetoslavd85084b2014-03-20 10:28:31 -07004511 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004512}
4513
Dominik Laskowskic2867142019-01-21 11:33:38 -08004514void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4515 mTimeStats->parseArgs(asProto, args, result);
4516}
4517
Jamie Gennis6547ff42013-07-16 20:12:42 -07004518// This should only be called from the main thread. Otherwise it would need
4519// the lock and should use mCurrentState rather than mDrawingState.
4520void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004521 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004522 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004523 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004524
4525 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4526}
4527
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004529 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004530
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004531 if (isLayerTripleBufferingDisabled())
4532 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004533
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4535 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4536 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4537 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4538 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4539 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004540 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004541}
4542
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004543void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004544 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004545 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004546 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004547 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004548
4549 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4550
4551 if (mUseScheduler) {
4552 mScheduler->dump(mAppConnectionHandle, result);
4553 } else {
4554 mEventThread->dump(result);
4555 }
4556}
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4559 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004560 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4561 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004562 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004563 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004565 }
David Sodman4a36e932017-11-07 14:29:47 -08004566 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004567 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004568 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4570 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004571}
4572
Dan Stozae77c7662016-05-13 11:37:28 -07004573void SurfaceFlinger::recordBufferingStats(const char* layerName,
4574 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004575 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4576 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004577 for (const auto& segment : history) {
4578 if (!segment.usedThirdBuffer) {
4579 stats.twoBufferTime += segment.totalTime;
4580 }
4581 if (segment.occupancyAverage < 1.0f) {
4582 stats.doubleBufferedTime += segment.totalTime;
4583 } else if (segment.occupancyAverage < 2.0f) {
4584 stats.tripleBufferedTime += segment.totalTime;
4585 }
4586 ++stats.numSegments;
4587 stats.totalTime += segment.totalTime;
4588 }
4589}
4590
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4592 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004593
4594 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4595 const size_t count = currentLayers.size();
4596 for (size_t i=0 ; i<count ; i++) {
4597 currentLayers[i]->dumpFrameEvents(result);
4598 }
4599}
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004602 result.append("Buffering stats:\n");
4603 result.append(" [Layer name] <Active time> <Two buffer> "
4604 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004605 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004606 typedef std::tuple<std::string, float, float, float> BufferTuple;
4607 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004608 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004609 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004610 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004611 if (stats.numSegments == 0) {
4612 continue;
4613 }
4614 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4615 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4616 stats.totalTime;
4617 float doubleBufferRatio = static_cast<float>(
4618 stats.doubleBufferedTime) / stats.totalTime;
4619 float tripleBufferRatio = static_cast<float>(
4620 stats.tripleBufferedTime) / stats.totalTime;
4621 sorted.insert({activeTime, {name, twoBufferRatio,
4622 doubleBufferRatio, tripleBufferRatio}});
4623 }
4624 for (const auto& sortedPair : sorted) {
4625 float activeTime = sortedPair.first;
4626 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4628 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004629 }
4630 result.append("\n");
4631}
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004634 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004635 const auto displayId = display->getId();
4636 if (!displayId) {
4637 continue;
4638 }
4639 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result,
4645 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4646 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 uint8_t port;
4648 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004649 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 result.append("no identification data\n");
4651 continue;
4652 }
4653
4654 if (!isEdid(data)) {
4655 result.append("unknown identification data: ");
4656 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 }
4659 result.append("\n");
4660 continue;
4661 }
4662
4663 const auto edid = parseEdid(data);
4664 if (!edid) {
4665 result.append("invalid EDID: ");
4666 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004668 }
4669 result.append("\n");
4670 continue;
4671 }
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 result.append(edid->displayName.data(), edid->displayName.length());
4675 result.append("\"\n");
4676 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004677}
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4680 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4681 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4682 StringAppendF(&result, "DisplayColorSetting: %s\n",
4683 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684
4685 // TODO: print out if wide-color mode is active or not
4686
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004687 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 const auto displayId = display->getId();
4689 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004690 continue;
4691 }
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004695 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004697 }
4698
Lloyd Pique32cbe282018-10-19 13:09:22 -07004699 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, " Current color mode: %s (%d)\n",
4701 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004702 }
4703 result.append("\n");
4704}
4705
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004708 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4709 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004710 continue;
4711 }
4712
Dominik Laskowski05275f12018-11-01 15:03:24 -07004713 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4715 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004716 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 compositionInfo.dump(result, nullptr);
4718 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004719 }
4720 }
David Sodman7e4ae112018-02-09 15:02:28 -08004721}
4722
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004723LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004724 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004725 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4726 const State& state = useDrawing ? mDrawingState : mCurrentState;
4727 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004728 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004729 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004730 });
4731
4732 return layersProto;
4733}
4734
Lloyd Pique32cbe282018-10-19 13:09:22 -07004735LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004736 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004737
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004738 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004739 resolution->set_w(displayDevice.getWidth());
4740 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004741
Lloyd Pique32cbe282018-10-19 13:09:22 -07004742 auto display = displayDevice.getCompositionDisplay();
4743 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004744
Lloyd Pique32cbe282018-10-19 13:09:22 -07004745 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4746 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4747 layersProto.set_global_transform(displayState.orientation);
4748
4749 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004750 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004752 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004753 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004754 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004755 }
4756 });
4757
4758 return layersProto;
4759}
4760
Dominik Laskowskic2867142019-01-21 11:33:38 -08004761void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4762 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 Colorizer colorizer(colorize);
4764
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765 // figure out if we're stuck somewhere
4766 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004767 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4769
4770 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004771 * Dump library configuration.
4772 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773
4774 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004775 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004777 appendSfConfigString(result);
4778 appendUiConfigString(result);
4779 appendGuiConfigString(result);
4780 result.append("\n");
4781
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004782 result.append("\nDisplay identification data:\n");
4783 dumpDisplayIdentificationData(result);
4784
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004785 result.append("\nWide-Color information:\n");
4786 dumpWideColorInfo(result);
4787
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004788 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004789 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004790 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004791 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004792 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004793
Andy McFadden41d67d72014-04-25 16:58:34 -07004794 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004795 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004796 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004797 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004798 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004799
Dan Stozab90cf072015-03-05 11:05:59 -08004800 dumpStaticScreenStats(result);
4801 result.append("\n");
4802
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004804
Dan Stozae77c7662016-05-13 11:37:28 -07004805 dumpBufferingStats(result);
4806
Andy McFadden4803b742012-09-24 19:07:20 -07004807 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808 * Dump the visible layer list
4809 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004810 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4812 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4813 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004815
Chia-I Wu2f884132018-09-13 15:17:58 -07004816 {
4817 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4818 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004820 result.append("\n");
4821 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
David Sodman7e4ae112018-02-09 15:02:28 -08004823 result.append("\nFrame-Composition information:\n");
4824 dumpFrameCompositionInfo(result);
4825 result.append("\n");
4826
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004827 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004828 * Dump Display state
4829 */
4830
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004833 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004834 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004835 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004836 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004837 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004838
4839 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004840 * Dump SurfaceFlinger global state
4841 */
4842
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004843 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004844 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004847 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848
Dominik Laskowski075d3172018-05-24 15:50:06 -07004849 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004850 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4851 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004852 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4853 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004854 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result,
4856 " transaction-flags : %08x\n"
4857 " gpu_to_cpu_unsupported : %d\n",
4858 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004859
Dominik Laskowski075d3172018-05-24 15:50:06 -07004860 if (const auto displayId = getInternalDisplayId();
4861 displayId && getHwComposer().isConnected(*displayId)) {
4862 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result,
4864 " refresh-rate : %f fps\n"
4865 " x-dpi : %f\n"
4866 " y-dpi : %f\n",
4867 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4868 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004869 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004870
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004872
Dan Stozae22aec72016-08-01 13:20:59 -07004873 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004874 * Tracing state
4875 */
4876 mTracing.dump(result);
4877 result.append("\n");
4878
4879 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004880 * HWC layer minidump
4881 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004882 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004883 const auto displayId = display->getId();
4884 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004885 continue;
4886 }
4887
Yiwei Zhang5434a782018-12-05 18:06:32 -08004888 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004889 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004890 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004891 result.append("\n");
4892 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004893
4894 /*
4895 * Dump HWComposer state
4896 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004897 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004898 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004899 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004900 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004901 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004902 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
4904 /*
4905 * Dump gralloc state
4906 */
4907 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4908 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004909
4910 /*
4911 * Dump VrFlinger state if in use.
4912 */
4913 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4914 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004915 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004916 result.append("\n");
4917 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004918
4919 /**
4920 * Scheduler dump state.
4921 */
4922 if (mUseScheduler) {
4923 result.append("\nScheduler state:\n");
4924 result.append(mScheduler->doDump() + "\n");
4925 result.append(mRefreshRateStats->doDump() + "\n");
4926 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004927}
4928
Dominik Laskowski075d3172018-05-24 15:50:06 -07004929const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004930 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004931 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004932 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004933 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004934 }
4935 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004936
Dominik Laskowski34157762018-10-31 13:07:19 -07004937 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004938 static const Vector<sp<Layer>> empty;
4939 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004940}
4941
Chia-I Wu28f320b2018-05-03 11:02:56 -07004942void SurfaceFlinger::updateColorMatrixLocked() {
4943 mat4 colorMatrix;
4944 if (mGlobalSaturationFactor != 1.0f) {
4945 // Rec.709 luma coefficients
4946 float3 luminance{0.213f, 0.715f, 0.072f};
4947 luminance *= 1.0f - mGlobalSaturationFactor;
4948 mat4 saturationMatrix = mat4(
4949 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4950 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4951 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4952 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4953 );
4954 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4955 } else {
4956 colorMatrix = mClientColorMatrix * mDaltonizer();
4957 }
4958
4959 if (mCurrentState.colorMatrix != colorMatrix) {
4960 mCurrentState.colorMatrix = colorMatrix;
4961 mCurrentState.colorMatrixChanged = true;
4962 setTransactionFlags(eTransactionNeeded);
4963 }
4964}
4965
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004966status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967#pragma clang diagnostic push
4968#pragma clang diagnostic error "-Wswitch-enum"
4969 switch (static_cast<ISurfaceComposerTag>(code)) {
4970 // These methods should at minimum make sure that the client requested
4971 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004972 case BOOT_FINISHED:
4973 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974 case CREATE_DISPLAY:
4975 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004976 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977 case GET_ACTIVE_COLOR_MODE:
4978 case GET_ANIMATION_FRAME_STATS:
4979 case GET_HDR_CAPABILITIES:
4980 case SET_ACTIVE_CONFIG:
4981 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004982 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004983 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004984 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004985 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4986 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004987 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4988 IPCThreadState* ipc = IPCThreadState::self();
4989 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4990 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004991 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004992 }
Robert Carr1db73f62016-12-21 12:58:51 -08004993 return OK;
4994 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004995 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004996 IPCThreadState* ipc = IPCThreadState::self();
4997 const int pid = ipc->getCallingPid();
4998 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004999 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5000 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005001 return PERMISSION_DENIED;
5002 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005003 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005005 // Used by apps to hook Choreographer to SurfaceFlinger.
5006 case CREATE_DISPLAY_EVENT_CONNECTION:
5007 // The following calls are currently used by clients that do not
5008 // request necessary permissions. However, they do not expose any secret
5009 // information, so it is OK to pass them.
5010 case AUTHENTICATE_SURFACE:
5011 case GET_ACTIVE_CONFIG:
5012 case GET_BUILT_IN_DISPLAY:
5013 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005014 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005015 case GET_DISPLAY_CONFIGS:
5016 case GET_DISPLAY_STATS:
5017 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5018 // Calling setTransactionState is safe, because you need to have been
5019 // granted a reference to Client* and Handle* to do anything with it.
5020 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005021 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005022 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005023 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005024 case GET_PROTECTED_CONTENT_SUPPORT:
5025 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005026 case UNCACHE_BUFFER:
5027 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005028 return OK;
5029 }
5030 case CAPTURE_LAYERS:
5031 case CAPTURE_SCREEN: {
5032 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005033 IPCThreadState* ipc = IPCThreadState::self();
5034 const int pid = ipc->getCallingPid();
5035 const int uid = ipc->getCallingUid();
5036 if ((uid != AID_GRAPHICS) &&
5037 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5038 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5039 return PERMISSION_DENIED;
5040 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005041 return OK;
5042 }
5043 // The following codes are deprecated and should never be allowed to access SF.
5044 case CONNECT_DISPLAY_UNUSED:
5045 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5046 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5047 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050
5051 // These codes are used for the IBinder protocol to either interrogate the recipient
5052 // side of the transaction for its canonical interface descriptor or to dump its state.
5053 // We let them pass by default.
5054 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5055 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5056 code == IBinder::SYSPROPS_TRANSACTION) {
5057 return OK;
5058 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005059 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005060 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005061 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5063 return OK;
5064 }
5065 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5066 return PERMISSION_DENIED;
5067#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005068}
5069
Ana Krulec13be8ad2018-08-21 02:43:56 +00005070status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5071 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005072 status_t credentialCheck = CheckTransactCodeCredentials(code);
5073 if (credentialCheck != OK) {
5074 return credentialCheck;
5075 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005077 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5078 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005079 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005080 IPCThreadState* ipc = IPCThreadState::self();
5081 const int uid = ipc->getCallingUid();
5082 if (CC_UNLIKELY(uid != AID_SYSTEM
5083 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005084 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005085 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005086 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005087 return PERMISSION_DENIED;
5088 }
5089 int n;
5090 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005091 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005092 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 return NO_ERROR;
5094 case 1002: // SHOW_UPDATES
5095 n = data.readInt32();
5096 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005097 invalidateHwcGeometry();
5098 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005101 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005102 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005103 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005104 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005105 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005106 setTransactionFlags(
5107 eTransactionNeeded|
5108 eDisplayTransactionNeeded|
5109 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005110 return NO_ERROR;
5111 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005112 case 1006:{ // send empty update
5113 signalRefresh();
5114 return NO_ERROR;
5115 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005116 case 1008: // toggle use of hw composer
5117 n = data.readInt32();
5118 mDebugDisableHWC = n ? 1 : 0;
5119 invalidateHwcGeometry();
5120 repaintEverything();
5121 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005122 case 1009: // toggle use of transform hint
5123 n = data.readInt32();
5124 mDebugDisableTransformHint = n ? 1 : 0;
5125 invalidateHwcGeometry();
5126 repaintEverything();
5127 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005128 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005129 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 reply->writeInt32(0);
5131 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005132 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005133 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005134 return NO_ERROR;
5135 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005136 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005137 if (!display) {
5138 return NAME_NOT_FOUND;
5139 }
5140
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005141 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005142 return NO_ERROR;
5143 }
5144 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005145 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005146 // daltonize
5147 n = data.readInt32();
5148 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005149 case 1:
5150 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5151 break;
5152 case 2:
5153 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5154 break;
5155 case 3:
5156 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5157 break;
5158 default:
5159 mDaltonizer.setType(ColorBlindnessType::None);
5160 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005161 }
5162 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005163 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005164 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005165 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005166 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005167
5168 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005169 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005170 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005172 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 // apply a color matrix
5174 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005176 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005177 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005178 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005180 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005181 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005183 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005184 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005185
5186 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5187 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005188 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005189 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5190 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5191 }
5192
Chia-I Wu28f320b2018-05-03 11:02:56 -07005193 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005194 return NO_ERROR;
5195 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005196 // This is an experimental interface
5197 // Needs to be shifted to proper binder interface when we productize
5198 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005199 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005200 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005201 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005202 return NO_ERROR;
5203 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005204 case 1017: {
5205 n = data.readInt32();
5206 mForceFullDamage = static_cast<bool>(n);
5207 return NO_ERROR;
5208 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005209 case 1018: { // Modify Choreographer's phase offset
5210 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005211 if (mUseScheduler) {
5212 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5213 } else {
5214 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5215 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005216 return NO_ERROR;
5217 }
5218 case 1019: { // Modify SurfaceFlinger's phase offset
5219 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005220 if (mUseScheduler) {
5221 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5222 } else {
5223 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5224 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005225 return NO_ERROR;
5226 }
Irvel468051e2016-06-13 16:44:44 -07005227 case 1020: { // Layer updates interceptor
5228 n = data.readInt32();
5229 if (n) {
5230 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005231 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005232 }
5233 else{
5234 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005235 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005236 }
5237 return NO_ERROR;
5238 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005239 case 1021: { // Disable HWC virtual displays
5240 n = data.readInt32();
5241 mUseHwcVirtualDisplays = !n;
5242 return NO_ERROR;
5243 }
Romain Guy0147a172017-06-01 13:53:56 -07005244 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005245 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005246 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005247
Chia-I Wu28f320b2018-05-03 11:02:56 -07005248 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005249 return NO_ERROR;
5250 }
Romain Guy54f154a2017-10-24 21:40:32 +01005251 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005252 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005253 invalidateHwcGeometry();
5254 repaintEverything();
5255 return NO_ERROR;
5256 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005257 // Deprecate, use 1030 to check whether the device is color managed.
5258 case 1024: {
5259 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005260 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005261 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005262 n = data.readInt32();
5263 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005264 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005265 mTracing.enable();
5266 doTracing("tracing.enable");
5267 reply->writeInt32(NO_ERROR);
5268 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005269 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005270 status_t err = mTracing.disable();
5271 reply->writeInt32(err);
5272 }
5273 return NO_ERROR;
5274 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005275 case 1026: { // Get layer tracing status
5276 reply->writeBool(mTracing.isEnabled());
5277 return NO_ERROR;
5278 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005279 // Is a DisplayColorSetting supported?
5280 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005281 const auto display = getDefaultDisplayDevice();
5282 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005283 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005284 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005285
5286 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5287 switch (setting) {
5288 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005289 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 break;
5291 case DisplayColorSetting::UNMANAGED:
5292 reply->writeBool(true);
5293 break;
5294 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005295 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005296 break;
5297 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005298 reply->writeBool(
5299 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005300 break;
5301 }
5302 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005303 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005304 // Is VrFlinger active?
5305 case 1028: {
5306 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005307 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005308 return NO_ERROR;
5309 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005310 // Is device color managed?
5311 case 1030: {
5312 reply->writeBool(useColorManagement);
5313 return NO_ERROR;
5314 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005315 // Override default composition data space
5316 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5317 // && adb shell stop zygote && adb shell start zygote
5318 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5319 // adb shell stop zygote && adb shell start zygote
5320 case 1031: {
5321 Mutex::Autolock _l(mStateLock);
5322 n = data.readInt32();
5323 if (n) {
5324 n = data.readInt32();
5325 if (n) {
5326 Dataspace dataspace = static_cast<Dataspace>(n);
5327 if (!validateCompositionDataspace(dataspace)) {
5328 return BAD_VALUE;
5329 }
5330 mDefaultCompositionDataspace = dataspace;
5331 }
5332 n = data.readInt32();
5333 if (n) {
5334 Dataspace dataspace = static_cast<Dataspace>(n);
5335 if (!validateCompositionDataspace(dataspace)) {
5336 return BAD_VALUE;
5337 }
5338 mWideColorGamutCompositionDataspace = dataspace;
5339 }
5340 } else {
5341 // restore composition data space.
5342 mDefaultCompositionDataspace = defaultCompositionDataspace;
5343 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5344 }
5345 return NO_ERROR;
5346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005347 }
5348 }
5349 return err;
5350}
5351
Steven Thomas6d8110b2017-08-31 18:24:21 -07005352void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005353 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005354 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005355}
5356
Ana Krulec7d1d6832018-12-27 11:10:09 -08005357void SurfaceFlinger::repaintEverythingForHWC() {
5358 mRepaintEverything = true;
5359 mEventQueue->invalidateForHWC();
5360}
5361
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5363class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005364public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005365 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5366 ~WindowDisconnector() {
5367 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005368 }
5369
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005370private:
5371 ANativeWindow* mWindow;
5372 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005373};
5374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005375status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005376 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5377 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005378 uint32_t reqWidth, uint32_t reqHeight,
5379 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005380 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005381 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005383 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005384
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005385 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5386
Chia-I Wu20261cb2018-08-23 12:55:44 -07005387 sp<DisplayDevice> display;
5388 {
5389 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005390
Chia-I Wu20261cb2018-08-23 12:55:44 -07005391 display = getDisplayDeviceLocked(displayToken);
5392 if (!display) return BAD_VALUE;
5393
Chia-I Wucb023152018-08-28 12:57:23 -07005394 // set the requested width/height to the logical display viewport size
5395 // by default
5396 if (reqWidth == 0 || reqHeight == 0) {
5397 reqWidth = uint32_t(display->getViewport().width());
5398 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005399 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005400 }
5401
Peiyong Lin0e003c92018-09-17 11:09:51 -07005402 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5403 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005404
5405 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005406 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005407 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5408 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005409}
5410
5411status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005412 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5413 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005414 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005415 ATRACE_CALL();
5416
5417 class LayerRenderArea : public RenderArea {
5418 public:
Robert Carr578038f2018-03-09 12:25:24 -08005419 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005420 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5421 bool childrenOnly)
5422 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005423 mLayer(layer),
5424 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005425 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005426 mFlinger(flinger),
5427 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005428 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005429 Rect getBounds() const override {
5430 const Layer::State& layerState(mLayer->getDrawingState());
5431 return mLayer->getBufferSize(layerState);
5432 }
Marissa Wall61c58622018-07-18 10:12:20 -07005433 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005434 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005435 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005436 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005437 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005438 }
chaviwa76b2712017-09-20 12:02:26 -07005439 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005440 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005441 Rect getSourceCrop() const override {
5442 if (mCrop.isEmpty()) {
5443 return getBounds();
5444 } else {
5445 return mCrop;
5446 }
5447 }
Robert Carr578038f2018-03-09 12:25:24 -08005448 class ReparentForDrawing {
5449 public:
5450 const sp<Layer>& oldParent;
5451 const sp<Layer>& newParent;
5452
5453 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5454 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005455 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005456 }
Robert Carr15eae092018-03-23 13:43:53 -07005457 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005458 };
5459
5460 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005461 const Rect sourceCrop = getSourceCrop();
5462 // no need to check rotation because there is none
5463 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5464 sourceCrop.height() != getReqHeight();
5465
Robert Carr578038f2018-03-09 12:25:24 -08005466 if (!mChildrenOnly) {
5467 mTransform = mLayer->getTransform().inverse();
5468 drawLayers();
5469 } else {
5470 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005471 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005472 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5473 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005474
5475 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5476 drawLayers();
5477 }
5478 }
chaviwa76b2712017-09-20 12:02:26 -07005479
chaviwa76b2712017-09-20 12:02:26 -07005480 private:
chaviw7206d492017-11-10 16:16:12 -08005481 const sp<Layer> mLayer;
5482 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005483
5484 // In the "childrenOnly" case we reparent the children to a screenshot
5485 // layer which has no properties set and which does not draw.
5486 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005487 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005488 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005489
5490 SurfaceFlinger* mFlinger;
5491 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005492 };
5493
5494 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5495 auto parent = layerHandle->owner.promote();
5496
Robert Carr2e102c92018-10-23 12:11:15 -07005497 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005498 ALOGE("captureLayers called with a removed parent");
5499 return NAME_NOT_FOUND;
5500 }
5501
Robert Carr578038f2018-03-09 12:25:24 -08005502 const int uid = IPCThreadState::self()->getCallingUid();
5503 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005504 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005505 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5506 return PERMISSION_DENIED;
5507 }
5508
chaviw7206d492017-11-10 16:16:12 -08005509 Rect crop(sourceCrop);
5510 if (sourceCrop.width() <= 0) {
5511 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005512 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005513 }
5514
5515 if (sourceCrop.height() <= 0) {
5516 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005517 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005518 }
5519
5520 int32_t reqWidth = crop.width() * frameScale;
5521 int32_t reqHeight = crop.height() * frameScale;
5522
Chia-I Wu20261cb2018-08-23 12:55:44 -07005523 // really small crop or frameScale
5524 if (reqWidth <= 0) {
5525 reqWidth = 1;
5526 }
5527 if (reqHeight <= 0) {
5528 reqHeight = 1;
5529 }
5530
Peiyong Lin0e003c92018-09-17 11:09:51 -07005531 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005532
Robert Carr578038f2018-03-09 12:25:24 -08005533 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005534 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5535 if (!layer->isVisible()) {
5536 return;
Robert Carr578038f2018-03-09 12:25:24 -08005537 } else if (childrenOnly && layer == parent.get()) {
5538 return;
chaviwa76b2712017-09-20 12:02:26 -07005539 }
5540 visitor(layer);
5541 });
5542 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005543 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005544}
5545
5546status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5547 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005548 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005549 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005550 bool useIdentityTransform) {
5551 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005552
Peiyong Lin0e003c92018-09-17 11:09:51 -07005553 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005554 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5555 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005556 *outBuffer =
5557 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5558 static_cast<android_pixel_format>(reqPixelFormat), 1,
5559 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005560
5561 // This mutex protects syncFd and captureResult for communication of the return values from the
5562 // main thread back to this Binder thread
5563 std::mutex captureMutex;
5564 std::condition_variable captureCondition;
5565 std::unique_lock<std::mutex> captureLock(captureMutex);
5566 int syncFd = -1;
5567 std::optional<status_t> captureResult;
5568
Robert Carr03480e22018-01-04 16:02:06 -08005569 const int uid = IPCThreadState::self()->getCallingUid();
5570 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5571
Dominik Laskowski8c001672018-05-30 16:52:06 -07005572 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005573 // If there is a refresh pending, bug out early and tell the binder thread to try again
5574 // after the refresh.
5575 if (mRefreshPending) {
5576 ATRACE_NAME("Skipping screenshot for now");
5577 std::unique_lock<std::mutex> captureLock(captureMutex);
5578 captureResult = std::make_optional<status_t>(EAGAIN);
5579 captureCondition.notify_one();
5580 return;
5581 }
5582
5583 status_t result = NO_ERROR;
5584 int fd = -1;
5585 {
5586 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005587 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005588 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5589 useIdentityTransform, forSystem, &fd);
5590 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005591 }
5592
5593 {
5594 std::unique_lock<std::mutex> captureLock(captureMutex);
5595 syncFd = fd;
5596 captureResult = std::make_optional<status_t>(result);
5597 captureCondition.notify_one();
5598 }
5599 });
5600
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005602 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005603 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005604 while (*captureResult == EAGAIN) {
5605 captureResult.reset();
5606 result = postMessageAsync(message);
5607 if (result != NO_ERROR) {
5608 return result;
5609 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005610 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005611 }
5612 result = *captureResult;
5613 }
5614
5615 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005616 sync_wait(syncFd, -1);
5617 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005618 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005621}
5622
chaviwa76b2712017-09-20 12:02:26 -07005623void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005624 TraverseLayersFunction traverseLayers,
Alec Mouri79108df2019-02-04 19:33:44 +00005625 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005626 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005627
Alec Mouri79108df2019-02-04 19:33:44 +00005628 auto& engine(getRenderEngine());
5629
chaviwa76b2712017-09-20 12:02:26 -07005630 const auto reqWidth = renderArea.getReqWidth();
5631 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005632 const auto sourceCrop = renderArea.getSourceCrop();
5633 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005634
Alec Mouri79108df2019-02-04 19:33:44 +00005635 engine.setOutputDataSpace(renderArea.getReqDataSpace());
5636 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005637
Alec Mouri79108df2019-02-04 19:33:44 +00005638 // make sure to clear all GL error flags
5639 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005640
Alec Mouri79108df2019-02-04 19:33:44 +00005641 // set-up our viewport
5642 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
5643 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005644
chaviw50da5042018-04-09 13:49:37 -07005645 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Alec Mouri79108df2019-02-04 19:33:44 +00005646 // redraw the screen entirely...
5647 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005648
chaviwa76b2712017-09-20 12:02:26 -07005649 traverseLayers([&](Layer* layer) {
Alec Mouri79108df2019-02-04 19:33:44 +00005650 engine.setColorTransform(layer->getColorTransform());
5651 layer->draw(renderArea, useIdentityTransform);
5652 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005653 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005654}
5655
chaviwa76b2712017-09-20 12:02:26 -07005656status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5657 TraverseLayersFunction traverseLayers,
5658 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005660 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005661 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005662 ATRACE_CALL();
5663
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005664 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005665
5666 traverseLayers([&](Layer* layer) {
5667 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5668 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005669
Robert Carr03480e22018-01-04 16:02:06 -08005670 // We allow the system server to take screenshots of secure layers for
5671 // use in situations like the Screen-rotation animation and place
5672 // the impetus on WindowManager to not persist them.
5673 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005674 ALOGW("FB is protected: PERMISSION_DENIED");
5675 return PERMISSION_DENIED;
5676 }
Alec Mouri79108df2019-02-04 19:33:44 +00005677 auto& engine(getRenderEngine());
5678
5679 // this binds the given EGLImage as a framebuffer for the
5680 // duration of this scope.
5681 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
5682 if (bufferBond.getStatus() != NO_ERROR) {
5683 ALOGE("got ANWB binding error while taking screenshot");
5684 return INVALID_OPERATION;
5685 }
5686
5687 // this will in fact render into our dequeued buffer
5688 // via an FBO, which means we didn't have to create
5689 // an EGLSurface and therefore we're not
5690 // dependent on the context's EGLConfig.
5691 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
5692
5693 base::unique_fd syncFd = engine.flush();
5694 if (syncFd < 0) {
5695 engine.finish();
5696 }
5697 *outSyncFd = syncFd.release();
5698
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005699 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005700}
5701
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005702// ---------------------------------------------------------------------------
5703
Dan Stoza412903f2017-04-27 13:42:17 -07005704void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5705 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005706}
5707
Dan Stoza412903f2017-04-27 13:42:17 -07005708void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5709 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005710}
5711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005712void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005713 const LayerVector::Visitor& visitor) {
5714 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005715 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005716 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005717 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005718 continue;
5719 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005720 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005721 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005722 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005723 return;
5724 }
chaviwa76b2712017-09-20 12:02:26 -07005725 if (!layer->isVisible()) {
5726 return;
5727 }
5728 visitor(layer);
5729 });
5730 }
5731}
5732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005733}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005734
Lloyd Pique074e8122018-07-26 12:57:23 -07005735
Mathias Agopian3f844832013-08-07 21:24:32 -07005736#if defined(__gl_h_)
5737#error "don't include gl/gl.h in this file"
5738#endif
5739
5740#if defined(__gl2_h_)
5741#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005742#endif