blob: 2cf2cd8a5d6836d7c98d3a93dc673f1faafe1026 [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 Mouri0f714832018-11-12 15:31:06 -080017//#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 Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080079#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070082#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080083#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070084#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Steven Thomasb02664d2017-07-26 18:48:28 -070089#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070090#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070091#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070092#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070093#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070094#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070096#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/EventControlThread.h"
98#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070099#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700101#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800102#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700105
David Sodman7e4ae112018-02-09 15:02:28 -0800106#include "android-base/stringprintf.h"
107
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700110#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900112#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
chaviw1d044282017-09-27 12:19:28 -0700114#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900115#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700118
Jaesoo Lee43518572017-01-23 19:03:16 +0900119using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800122using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700123using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700124using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800125using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700126using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700127using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128
Steven Thomasb02664d2017-07-26 18:48:28 -0700129namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700130
131#pragma clang diagnostic push
132#pragma clang diagnostic error "-Wswitch-enum"
133
134bool isWideColorMode(const ColorMode colorMode) {
135 switch (colorMode) {
136 case ColorMode::DISPLAY_P3:
137 case ColorMode::ADOBE_RGB:
138 case ColorMode::DCI_P3:
139 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700140 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700141 case ColorMode::BT2100_PQ:
142 case ColorMode::BT2100_HLG:
143 return true;
144 case ColorMode::NATIVE:
145 case ColorMode::STANDARD_BT601_625:
146 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
147 case ColorMode::STANDARD_BT601_525:
148 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
149 case ColorMode::STANDARD_BT709:
150 case ColorMode::SRGB:
151 return false;
152 }
153 return false;
154}
155
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700156ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
157 switch (rotation) {
158 case ISurfaceComposer::eRotateNone:
159 return ui::Transform::ROT_0;
160 case ISurfaceComposer::eRotate90:
161 return ui::Transform::ROT_90;
162 case ISurfaceComposer::eRotate180:
163 return ui::Transform::ROT_180;
164 case ISurfaceComposer::eRotate270:
165 return ui::Transform::ROT_270;
166 }
167 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
168 return ui::Transform::ROT_0;
169}
170
Peiyong Linfca547f2018-07-09 13:03:33 -0700171#pragma clang diagnostic pop
172
Steven Thomasb02664d2017-07-26 18:48:28 -0700173class ConditionalLock {
174public:
175 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
176 if (lock) {
177 mMutex.lock();
178 }
179 }
180 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
181private:
182 Mutex& mMutex;
183 bool mLocked;
184};
Peiyong Linfca547f2018-07-09 13:03:33 -0700185
Peiyong Lin9d846a52018-11-05 13:18:20 -0800186// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
187bool validateCompositionDataspace(Dataspace dataspace) {
188 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
189}
190
Steven Thomasb02664d2017-07-26 18:48:28 -0700191} // namespace anonymous
192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193// ---------------------------------------------------------------------------
194
Mathias Agopian99b49842011-06-27 16:05:52 -0700195const String16 sHardwareTest("android.permission.HARDWARE_TEST");
196const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
197const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
198const String16 sDump("android.permission.DUMP");
199
Daniel Solomon42d04562019-01-20 21:03:19 -0800200constexpr float kSrgbRedX = 0.4123f;
201constexpr float kSrgbRedY = 0.2126f;
202constexpr float kSrgbRedZ = 0.0193f;
203constexpr float kSrgbGreenX = 0.3576f;
204constexpr float kSrgbGreenY = 0.7152f;
205constexpr float kSrgbGreenZ = 0.1192f;
206constexpr float kSrgbBlueX = 0.1805f;
207constexpr float kSrgbBlueY = 0.0722f;
208constexpr float kSrgbBlueZ = 0.9506f;
209constexpr float kSrgbWhiteX = 0.9505f;
210constexpr float kSrgbWhiteY = 1.0000f;
211constexpr float kSrgbWhiteZ = 1.0891f;
212
Mathias Agopian99b49842011-06-27 16:05:52 -0700213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600220bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700221int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700222bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700223bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700224Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
226Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700228
Kalle Raitaa099a242017-01-11 11:17:29 -0800229std::string getHwcServiceName() {
230 char value[PROPERTY_VALUE_MAX] = {};
231 property_get("debug.sf.hwc_service_name", value, "default");
232 ALOGI("Using HWComposer service: '%s'", value);
233 return std::string(value);
234}
235
236bool useTrebleTestingOverride() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.treble_testing_override", value, "false");
239 ALOGI("Treble testing override: '%s'", value);
240 return std::string(value) == "true";
241}
242
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800243std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
244 switch(displayColorSetting) {
245 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700246 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800247 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Enhanced");
251 default:
252 return std::string("Unknown ") +
253 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255}
256
David Sodmanbc815282017-11-05 18:57:52 -0800257SurfaceFlingerBE::SurfaceFlingerBE()
258 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800259 mFrameBuckets(),
260 mTotalTime(0),
261 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800262 mComposerSequenceId(0) {
263}
264
Lloyd Pique90c115d2018-09-18 21:39:42 -0700265SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
266 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800267 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700269 mTransactionPending(false),
270 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700271 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700272 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800274 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800276 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800277 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800278 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700280 mDebugDDMS(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 Agopian8afb7e32011-08-15 20:44:40 -0700371 property_get("debug.sf.ddms", value, "0");
372 mDebugDDMS = atoi(value);
373 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700374 if (!startDdmConnection()) {
375 // start failed, and DDMS debugging not enabled
376 mDebugDDMS = 0;
377 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700378 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700379 ALOGI_IF(mDebugRegion, "showupdates enabled");
380 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700381
382 property_get("debug.sf.disable_backpressure", value, "0");
383 mPropagateBackpressure = !atoi(value);
384 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700385
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800386 property_get("debug.sf.enable_hwc_vds", value, "0");
387 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800388 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800390 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800391 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800392 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700393
Yiwei Zhang243b3782018-05-15 17:40:04 -0700394 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700395 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
396 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
397
Ana Krulec98b5b242018-08-10 15:03:23 -0700398 property_get("debug.sf.use_scheduler", value, "0");
399 mUseScheduler = atoi(value);
400
Ana Krulec757f63a2019-01-25 10:46:18 -0800401 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
402 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700403
Romain Guy11d63f42017-07-20 12:47:14 -0700404 // We should be reading 'persist.sys.sf.color_saturation' here
405 // but since /data may be encrypted, we need to wait until after vold
406 // comes online to attempt to read the property. The property is
407 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800408
409 if (useTrebleTestingOverride()) {
410 // Without the override SurfaceFlinger cannot connect to HIDL
411 // services that are not listed in the manifests. Considered
412 // deriving the setting from the set service name, but it
413 // would be brittle if the name that's not 'default' is used
414 // for production purposes later on.
415 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
416 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417}
418
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419void SurfaceFlinger::onFirstRef()
420{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800421 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422}
423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424SurfaceFlinger::~SurfaceFlinger()
425{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426}
427
Dan Stozac7014012014-02-14 15:03:43 -0800428void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429{
430 // the window manager died on us. prepare its eulogy.
431
Andy McFadden13a082e2012-08-24 10:16:42 -0700432 // restore initial conditions (default device unblank, etc)
433 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434
435 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700436 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437}
438
Robert Carr1db73f62016-12-21 12:58:51 -0800439static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700440 status_t err = client->initCheck();
441 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443 }
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return nullptr;
445}
446
447sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
448 return initClient(new Client(this));
449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 // Display ID is assigned when virtual display is allocated by HWC.
472 DisplayDeviceState state;
473 state.isSecure = secure;
474 state.displayName = displayName;
475 mCurrentState.displays.add(token, state);
476 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
484 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
490 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 mInterceptor->saveDisplayDeletion(state.sequenceId);
495 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 std::optional<DisplayId> displayId;
501
502 if (id == HWC_DISPLAY_PRIMARY) {
503 displayId = getInternalDisplayId();
504 } else if (id == HWC_DISPLAY_EXTERNAL) {
505 displayId = getExternalDisplayId();
506 }
507
508 if (!displayId) {
509 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800510 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512
513 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514}
515
Ady Abraham37965d42018-11-01 13:43:32 -0700516status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
517 if (!outGetColorManagement) {
518 return BAD_VALUE;
519 }
520 *outGetColorManagement = useColorManagement;
521 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700522}
523
Lloyd Pique441d5042018-10-18 16:49:51 -0700524HWComposer& SurfaceFlinger::getHwComposer() const {
525 return mCompositionEngine->getHwComposer();
526}
527
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700528renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
529 return mCompositionEngine->getRenderEngine();
530}
531
Lloyd Pique70d91362018-10-18 16:02:55 -0700532compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
533 return *mCompositionEngine.get();
534}
535
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536void SurfaceFlinger::bootFinished()
537{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700538 if (mStartPropertySetThread->join() != NO_ERROR) {
539 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 const nsecs_t now = systemTime();
542 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000543 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544
545 // wait patiently for the window manager death
546 const String16 name("window");
547 sp<IBinder> window(defaultServiceManager()->getService(name));
548 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700549 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550 }
Robert Carr720e5062018-07-30 17:45:14 -0700551 sp<IBinder> input(defaultServiceManager()->getService(
552 String16("inputflinger")));
553 if (input == nullptr) {
554 ALOGE("Failed to link to input service");
555 } else {
556 mInputFlinger = interface_cast<IInputFlinger>(input);
557 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
Steven Thomas050b2c82017-03-06 11:45:16 -0800559 if (mVrFlinger) {
560 mVrFlinger->OnBootFinished();
561 }
562
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700564 // formerly we would just kill the process, but we now ask it to exit so it
565 // can choose where to stop the animation.
566 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700567
568 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
569 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
570 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700571
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800572 postMessageAsync(new LambdaMessage([this] {
573 readPersistentProperties();
574 mBootStage = BootStage::FINISHED;
575 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576}
577
Dan Stoza436ccf32018-06-21 12:10:12 -0700578uint32_t SurfaceFlinger::getNewTexture() {
579 {
580 std::lock_guard lock(mTexturePoolMutex);
581 if (!mTexturePool.empty()) {
582 uint32_t name = mTexturePool.back();
583 mTexturePool.pop_back();
584 ATRACE_INT("TexturePoolSize", mTexturePool.size());
585 return name;
586 }
587
588 // The pool was too small, so increase it for the future
589 ++mTexturePoolSize;
590 }
591
592 // The pool was empty, so we need to get a new texture name directly using a
593 // blocking call to the main thread
594 uint32_t name = 0;
595 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
596 return name;
597}
598
Mathias Agopian3f844832013-08-07 21:24:32 -0700599void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700600 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700601}
602
Wei Wangf9b05ee2017-07-19 20:59:39 -0700603// Do not call property_set on main thread which will be blocked by init
604// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700606 ALOGI( "SurfaceFlinger's main thread ready to run. "
607 "Initializing graphics H/W...");
608
Ana Krulec757f63a2019-01-25 10:46:18 -0800609 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612
Dominik Laskowski83b88212018-12-11 13:34:06 -0800613 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700616 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700617 mScheduler = getFactory().createScheduler([this](bool enabled) {
618 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
619 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800620 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
621 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
622 mPhaseOffsets->setRefreshRateType(
623 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700624
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800626 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 impl::EventThread::InterceptVSyncsCallback());
629 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800630 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800631 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 mInterceptor->saveVSyncEvent(timestamp);
633 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800634
Ana Krulec98b5b242018-08-10 15:03:23 -0700635 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700636 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
637 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 } else {
639 mEventThreadSource =
640 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800641 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 mEventThread =
643 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 impl::EventThread::InterceptVSyncsCallback(),
645 "appEventThread");
646 mSfEventThreadSource =
647 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800648 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700649
650 mSFEventThread =
651 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700652 [this](nsecs_t timestamp) {
653 mInterceptor->saveVSyncEvent(timestamp);
654 },
655 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800656 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659
Steven Thomasb02664d2017-07-26 18:48:28 -0700660 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700661 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700662 renderEngineFeature |= (useColorManagement ?
663 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700664 renderEngineFeature |= (useContextPriority ?
665 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700666
667 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700668 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700669 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700670 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700671
672 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
673 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700674 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
675 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800676 // Process any initial hotplug and resulting display changes.
677 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700678 const auto display = getDefaultDisplayDeviceLocked();
679 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700680 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800682
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 // This callback is called from the vr flinger dispatch thread. We
686 // need to call signalTransaction(), which requires holding
687 // mStateLock when we're not on the main thread. Acquiring
688 // mStateLock from the vr flinger dispatch thread might trigger a
689 // deadlock in surface flinger (see b/66916578), so post a message
690 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
693 mVrFlingerRequestsDisplay = requestDisplay;
694 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
698 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 .value_or(0),
701 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (!mVrFlinger) {
703 ALOGE("Failed to start vrflinger");
704 }
705 }
706
Lloyd Pique90c115d2018-09-18 21:39:42 -0700707 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700709
Mathias Agopian92a979a2012-08-02 18:32:23 -0700710 // initialize our drawing state
711 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700712
Andy McFadden13a082e2012-08-24 10:16:42 -0700713 // set initial conditions (e.g. unblank default device)
714 initializeDisplays();
715
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700716 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700717
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700719
720 const bool presentFenceReliable =
721 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
722 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723
724 if (mStartPropertySetThread->Start() != NO_ERROR) {
725 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727
Ana Krulec7d1d6832018-12-27 11:10:09 -0800728 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800729 mScheduler->setExpiredIdleTimerCallback([this]() {
730 mPhaseOffsets->setRefreshRateType(
731 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
732 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
733 mVsyncModulator.setPhaseOffsets(early, gl, late);
734 setRefreshRateTo(60.f /* fps */);
735 });
736 mScheduler->setResetIdleTimerCallback([this]() {
737 mPhaseOffsets->setRefreshRateType(
738 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
739 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
740 mVsyncModulator.setPhaseOffsets(early, gl, late);
741 setRefreshRateTo(90.f /* fps */);
742 });
Ana Krulecb43429d2019-01-09 14:28:51 -0800743 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
744 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800745 }
746
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700748}
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 Mutex::Autolock _l(mStateLock);
752
Romain Guy11d63f42017-07-20 12:47:14 -0700753 char value[PROPERTY_VALUE_MAX];
754
755 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700757 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100759
760 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700761 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Dominik Laskowski075d3172018-05-24 15:50:06 -0700823 const auto displayId = getPhysicalDisplayId(displayToken);
824 if (!displayId) {
825 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 // TODO: Not sure if display density should handled by SF any longer
829 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700832 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800833 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836 return density;
837 }
838 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("ro.sf.lcd_density"); }
843 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Steven Thomas6d8110b2017-08-31 18:24:21 -0700847 ConditionalLock _l(mStateLock,
848 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700849 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 DisplayInfo info = DisplayInfo();
851
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 float xdpi = hwConfig->getDpiX();
853 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700854
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855 info.w = hwConfig->getWidth();
856 info.h = hwConfig->getHeight();
857 // Default display viewport to display width and height
858 info.viewportW = info.w;
859 info.viewportH = info.h;
860
Dominik Laskowski075d3172018-05-24 15:50:06 -0700861 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 // The density of the device is provided by a build property
863 float density = Density::getBuildDensity() / 160.0f;
864 if (density == 0) {
865 // the build doesn't provide a density -- this is wrong!
866 // use xdpi instead
867 ALOGE("ro.sf.lcd_density must be defined as a build property");
868 density = xdpi / 160.0f;
869 }
870 if (Density::getEmuDensity()) {
871 // if "qemu.sf.lcd_density" is specified, it overrides everything
872 xdpi = ydpi = density = Density::getEmuDensity();
873 density /= 160.0f;
874 }
875 info.density = density;
876
877 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878 const auto display = getDefaultDisplayDeviceLocked();
879 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700880
881 // This is for screenrecord
882 const Rect viewport = display->getViewport();
883 if (viewport.isValid()) {
884 info.viewportW = uint32_t(viewport.getWidth());
885 info.viewportH = uint32_t(viewport.getHeight());
886 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 } else {
888 // TODO: where should this value come from?
889 static const int TV_DENSITY = 213;
890 info.density = TV_DENSITY / 160.0f;
891 info.orientation = 0;
892 }
893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 info.xdpi = xdpi;
895 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800897 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898
Andy McFadden91b2ca82014-06-13 14:04:23 -0700899 // This is how far in advance a buffer must be queued for
900 // presentation at a given time. If you want a buffer to appear
901 // on the screen at time N, you must submit the buffer before
902 // (N - presentationDeadline).
903 //
904 // Normally it's one full refresh period (to give SF a chance to
905 // latch the buffer), but this can be reduced by configuring a
906 // DispSync offset. Any additional delays introduced by the hardware
907 // composer or panel must be accounted for here.
908 //
909 // We add an additional 1ms to allow for processing time and
910 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800911 info.presentationDeadline =
912 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700913
914 // All non-virtual displays are currently considered secure.
915 info.secure = true;
916
Dominik Laskowski075d3172018-05-24 15:50:06 -0700917 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700918 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800919 std::swap(info.w, info.h);
920 }
921
Michael Wright28f24d02016-07-12 13:30:53 -0700922 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700923 }
924
Dan Stoza7f7da322014-05-02 15:26:25 -0700925 return NO_ERROR;
926}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
929 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return BAD_VALUE;
931 }
932
Ana Krulece588e312018-09-18 12:32:24 -0700933 if (mUseScheduler) {
934 mScheduler->getDisplayStatInfo(stats);
935 } else {
936 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
937 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
938 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700939 return NO_ERROR;
940}
941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
943 const auto display = getDisplayDevice(displayToken);
944 if (!display) {
945 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800946 return BAD_VALUE;
947 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700950}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700951
Ana Krulec7d1d6832018-12-27 11:10:09 -0800952status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
953 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800954 postMessageAsync(new LambdaMessage(
955 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800956 return NO_ERROR;
957}
958
959status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
960 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800961 postMessageSync(new LambdaMessage(
962 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800963 return NO_ERROR;
964}
965
966void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
967 Vector<DisplayInfo> configs;
968 getDisplayConfigs(displayToken, &configs);
969 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
970 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
971 return;
972 }
973
974 const auto display = getDisplayDevice(displayToken);
975 if (!display) {
976 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
977 displayToken.get());
978 return;
979 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700980 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 ALOGW("Attempt to set active config %d for virtual display", mode);
982 return;
983 }
984 int currentDisplayPowerMode = display->getPowerMode();
985 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
986 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 return;
988 }
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800992 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993 return;
994 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800995 if (mUseScheduler) {
996 mRefreshRateStats->setConfigMode(mode);
997 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998
Dominik Laskowski075d3172018-05-24 15:50:06 -0700999 const auto displayId = display->getId();
1000 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001003 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001004
Ana Krulec7d1d6832018-12-27 11:10:09 -08001005 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001006 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001007}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1010 Vector<ColorMode>* outColorModes) {
1011 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001012 return BAD_VALUE;
1013 }
1014
Dominik Laskowski075d3172018-05-24 15:50:06 -07001015 const auto displayId = getPhysicalDisplayId(displayToken);
1016 if (!displayId) {
1017 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001018 }
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
1022 ConditionalLock _l(mStateLock,
1023 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001024 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001025 }
Michael Wright28f24d02016-07-12 13:30:53 -07001026 outColorModes->clear();
1027 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1028
1029 return NO_ERROR;
1030}
1031
Daniel Solomon42d04562019-01-20 21:03:19 -08001032status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1033 ui::DisplayPrimaries &primaries) {
1034 if (!displayToken) {
1035 return BAD_VALUE;
1036 }
1037
1038 // Currently we only support this API for a single internal display.
1039 if (getInternalDisplayToken() != displayToken) {
1040 return BAD_VALUE;
1041 }
1042
1043 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1044 return NO_ERROR;
1045}
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1048 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001049 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001050 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001051 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001055 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 Vector<ColorMode> modes;
1057 getDisplayColorModes(displayToken, &modes);
1058 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1059 if (mode < ColorMode::NATIVE || !exists) {
1060 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDevice(displayToken);
1065 if (!display) {
1066 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1067 decodeColorMode(mode).c_str(), mode, displayToken.get());
1068 } else if (display->isVirtual()) {
1069 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1070 decodeColorMode(mode).c_str(), mode);
1071 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001072 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1073 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 }
1075 }));
1076
Michael Wright28f24d02016-07-12 13:30:53 -07001077 return NO_ERROR;
1078}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079
Svetoslavd85084b2014-03-20 10:28:31 -07001080status_t SurfaceFlinger::clearAnimationFrameStats() {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.clearStats();
1083 return NO_ERROR;
1084}
1085
1086status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.getStats(outStats);
1089 return NO_ERROR;
1090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1093 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001094 Mutex::Autolock _l(mStateLock);
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const auto display = getDisplayDeviceLocked(displayToken);
1097 if (!display) {
1098 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001099 return BAD_VALUE;
1100 }
1101
Peiyong Linfb069302018-04-25 14:34:31 -07001102 // At this point the DisplayDeivce should already be set up,
1103 // meaning the luminance information is already queried from
1104 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001106 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1107 capabilities.getDesiredMaxLuminance(),
1108 capabilities.getDesiredMaxAverageLuminance(),
1109 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110
1111 return NO_ERROR;
1112}
1113
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001114status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1115 ui::PixelFormat* outFormat,
1116 ui::Dataspace* outDataspace,
1117 uint8_t* outComponentMask) const {
1118 if (!outFormat || !outDataspace || !outComponentMask) {
1119 return BAD_VALUE;
1120 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001121 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001122 if (!display || !display->getId()) {
1123 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1124 return BAD_VALUE;
1125 }
1126 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1127 outDataspace, outComponentMask);
1128}
1129
Kevin DuBois74e53772018-11-19 10:52:38 -08001130status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1131 bool enable, uint8_t componentMask,
1132 uint64_t maxFrames) const {
1133 const auto display = getDisplayDevice(displayToken);
1134 if (!display || !display->getId()) {
1135 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1136 return BAD_VALUE;
1137 }
1138
1139 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1140 componentMask, maxFrames);
1141}
1142
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001143status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1144 uint64_t maxFrames, uint64_t timestamp,
1145 DisplayedFrameStats* outStats) const {
1146 const auto display = getDisplayDevice(displayToken);
1147 if (!display || !display->getId()) {
1148 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1149 return BAD_VALUE;
1150 }
1151
1152 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1153 outStats);
1154}
1155
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001156status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1157 if (!outSupported) {
1158 return BAD_VALUE;
1159 }
1160 *outSupported = getRenderEngine().supportsProtectedContent();
1161 return NO_ERROR;
1162}
1163
Marissa Wallebc2c052019-01-16 19:16:55 -08001164status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1165 int32_t* outBufferId) {
1166 if (!outBufferId) {
1167 return BAD_VALUE;
1168 }
1169 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1170 return NO_ERROR;
1171}
1172
1173status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1174 mBufferStateLayerCache.release(token, bufferId);
1175 return NO_ERROR;
1176}
1177
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001178status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1179 bool* outIsWideColorDisplay) const {
1180 if (!displayToken || !outIsWideColorDisplay) {
1181 return BAD_VALUE;
1182 }
1183 Mutex::Autolock _l(mStateLock);
1184 const auto display = getDisplayDeviceLocked(displayToken);
1185 if (!display) {
1186 return BAD_VALUE;
1187 }
1188 *outIsWideColorDisplay = display->hasWideColorGamut();
1189 return NO_ERROR;
1190}
1191
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001192status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001193 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001195
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 if (mInjectVSyncs == enable) {
1197 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001198 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199
Dominik Laskowski83b88212018-12-11 13:34:06 -08001200 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001201
Ana Krulec98b5b242018-08-10 15:03:23 -07001202 // TODO(akrulec): Part of the Injector should be refactored, so that it
1203 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001204 if (enable) {
1205 ALOGV("VSync Injections enabled");
1206 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001207 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001208 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001209 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001210 impl::EventThread::InterceptVSyncsCallback(),
1211 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001213 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001214 } else {
1215 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001216 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001217 }
1218
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001219 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001220 }));
1221
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001222 return NO_ERROR;
1223}
1224
1225status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001226 Mutex::Autolock _l(mStateLock);
1227
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228 if (!mInjectVSyncs) {
1229 ALOGE("VSync Injections not enabled");
1230 return BAD_VALUE;
1231 }
1232 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1233 ALOGV("Injecting VSync inside SurfaceFlinger");
1234 mVSyncInjector->onInjectSyncEvent(when);
1235 }
1236 return NO_ERROR;
1237}
1238
Lloyd Pique755e3192018-01-31 16:46:15 -08001239status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1240 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001241 // Try to acquire a lock for 1s, fail gracefully
1242 const status_t err = mStateLock.timedLock(s2ns(1));
1243 const bool locked = (err == NO_ERROR);
1244 if (!locked) {
1245 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1246 return TIMED_OUT;
1247 }
1248
1249 outLayers->clear();
1250 mCurrentState.traverseInZOrder([&](Layer* layer) {
1251 outLayers->push_back(layer->getLayerDebugInfo());
1252 });
1253
1254 mStateLock.unlock();
1255 return NO_ERROR;
1256}
1257
Peiyong Linc6780972018-10-28 15:24:08 -07001258status_t SurfaceFlinger::getCompositionPreference(
1259 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1260 Dataspace* outWideColorGamutDataspace,
1261 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001262 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001263 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001264 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001265 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001266 return NO_ERROR;
1267}
1268
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001269// ----------------------------------------------------------------------------
1270
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001271sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1272 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001273 auto resyncCallback = makeResyncCallback([this] {
1274 Mutex::Autolock lock(mStateLock);
1275 return getVsyncPeriod();
1276 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001277
Ana Krulec98b5b242018-08-10 15:03:23 -07001278 if (mUseScheduler) {
1279 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001280 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001281 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001282 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001283 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001284 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001288 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001289 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001290 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001291}
1292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001294
1295void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001296 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001297}
1298
1299void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001300 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301}
1302
1303void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001304 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001305}
1306
1307void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001308 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001309 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001310}
1311
1312status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001313 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001314 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315}
1316
1317status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001318 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001319 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001320 if (res == NO_ERROR) {
1321 msg->wait();
1322 }
1323 return res;
1324}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001325
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001326void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001327 do {
1328 waitForEvent();
1329 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001330}
1331
Dominik Laskowski83b88212018-12-11 13:34:06 -08001332nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1333 const auto displayId = getInternalDisplayId();
1334 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1335 return 0;
1336 }
1337
1338 const auto config = getHwComposer().getActiveConfig(*displayId);
1339 return config ? config->getVsyncPeriod() : 0;
1340}
1341
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342void SurfaceFlinger::enableHardwareVsync() {
1343 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001344 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001345 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001346 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001348 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349}
1350
Dominik Laskowski83b88212018-12-11 13:34:06 -08001351void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352 Mutex::Autolock _l(mHWVsyncLock);
1353
Jesse Hall948fe0c2013-10-14 12:56:09 -07001354 if (makeAvailable) {
1355 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001356 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1357 if (mUseScheduler) {
1358 mScheduler->makeHWSyncAvailable(true);
1359 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001360 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001361 // Hardware vsync is not currently available, so abort the resync
1362 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001363 return;
1364 }
1365
Dominik Laskowski83b88212018-12-11 13:34:06 -08001366 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001367 return;
1368 }
1369
Ana Krulece588e312018-09-18 12:32:24 -07001370 if (mUseScheduler) {
1371 mScheduler->setVsyncPeriod(period);
1372 } else {
1373 mPrimaryDispSync->reset();
1374 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375
Ana Krulece588e312018-09-18 12:32:24 -07001376 if (!mPrimaryHWVsyncEnabled) {
1377 mPrimaryDispSync->beginResync();
1378 mEventControlThread->setVsyncEnabled(true);
1379 mPrimaryHWVsyncEnabled = true;
1380 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001381 }
1382}
1383
Jesse Hall948fe0c2013-10-14 12:56:09 -07001384void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001385 Mutex::Autolock _l(mHWVsyncLock);
1386 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001387 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001388 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389 mPrimaryHWVsyncEnabled = false;
1390 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001391 if (makeUnavailable) {
1392 mHWVsyncAvailable = false;
1393 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001394}
1395
Dominik Laskowski83b88212018-12-11 13:34:06 -08001396void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001397 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001398
Dan Stoza57164302017-05-08 14:03:54 -07001399 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001400 const nsecs_t last = lastResyncTime.exchange(now);
1401
1402 if (now - last > kIgnoreDelay) {
1403 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001404 }
1405}
1406
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001407void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1408 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001409 ATRACE_NAME("SF onVsync");
1410
Steven Thomas3cfac282017-02-06 12:29:30 -08001411 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 return;
1415 }
1416
Dominik Laskowski075d3172018-05-24 15:50:06 -07001417 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001418 return;
1419 }
1420
Dominik Laskowski075d3172018-05-24 15:50:06 -07001421 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001422 // For now, we don't do anything with external display vsyncs.
1423 return;
1424 }
1425
Ana Krulece588e312018-09-18 12:32:24 -07001426 if (mUseScheduler) {
1427 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001428 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001429 bool needsHwVsync = false;
1430 { // Scope for the lock
1431 Mutex::Autolock _l(mHWVsyncLock);
1432 if (mPrimaryHWVsyncEnabled) {
1433 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1434 }
1435 }
1436
1437 if (needsHwVsync) {
1438 enableHardwareVsync();
1439 } else {
1440 disableHardwareVsync(false);
1441 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001442 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001443}
1444
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001445void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001446 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1447 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001448}
1449
Ana Krulec7d1d6832018-12-27 11:10:09 -08001450void SurfaceFlinger::setRefreshRateTo(float newFps) {
1451 const auto displayId = getInternalDisplayId();
1452 if (!displayId || mBootStage != BootStage::FINISHED) {
1453 return;
1454 }
1455 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1456 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1457 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1458 // refresh cycle.
1459
1460 // Don't do any updating if the current fps is the same as the new one.
1461 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1462 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1463 if (currentVsyncPeriod == 0) {
1464 return;
1465 }
1466 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1467 // floating numbers.
1468 const float currentFps = 1e9 / currentVsyncPeriod;
1469 if (std::abs(currentFps - newFps) <= 1) {
1470 return;
1471 }
1472
1473 auto configs = getHwComposer().getConfigs(*displayId);
1474 for (int i = 0; i < configs.size(); i++) {
1475 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1476 if (vsyncPeriod == 0) {
1477 continue;
1478 }
1479 const float fps = 1e9 / vsyncPeriod;
1480 // TODO(b/113612090): There should be a better way at determining which config
1481 // has the right refresh rate.
1482 if (std::abs(fps - newFps) <= 1) {
1483 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1484 if (!display) return;
1485 // This is posted in async function to avoid deadlock when getDisplayDevice
1486 // requires mStateLock.
1487 setActiveConfigAsync(display, i);
1488 ATRACE_INT("FPS", newFps);
1489 }
1490 }
1491}
1492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001494 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001495 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001496 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497
Lloyd Piqueba04e622017-12-14 17:11:26 -08001498 // Ignore events that do not have the right sequenceId.
1499 if (sequenceId != getBE().mComposerSequenceId) {
1500 return;
1501 }
1502
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 // Only lock if we're not on the main thread. This function is normally
1504 // called on a hwbinder thread, but for the primary display it's called on
1505 // the main thread with the state lock already held, so don't attempt to
1506 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001507 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001508
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001509 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001510
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001511 if (std::this_thread::get_id() == mMainThreadId) {
1512 // Process all pending hot plug events immediately if we are on the main thread.
1513 processDisplayHotplugEventsLocked();
1514 }
1515
Lloyd Piqueba04e622017-12-14 17:11:26 -08001516 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001517}
1518
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001519void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001520 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001521 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001523 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001524 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001525}
1526
Dominik Laskowski075d3172018-05-24 15:50:06 -07001527void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001528 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001530 if (const auto displayId = getInternalDisplayId()) {
1531 getHwComposer().setVsyncEnabled(*displayId,
1532 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1533 }
Mathias Agopian86303202012-07-24 22:46:10 -07001534}
1535
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001537void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001538 if (mUseScheduler) {
1539 mScheduler->disableHardwareVsync(true);
1540 } else {
1541 disableHardwareVsync(true);
1542 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001543 // Clear the drawing state so that the logic inside of
1544 // handleTransactionLocked will fire. It will determine the delta between
1545 // mCurrentState and mDrawingState and re-apply all changes when we make the
1546 // transition.
1547 mDrawingState.displays.clear();
1548 mDisplays.clear();
1549}
1550
Steven Thomas050b2c82017-03-06 11:45:16 -08001551void SurfaceFlinger::updateVrFlinger() {
1552 if (!mVrFlinger)
1553 return;
1554 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001555 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001556 return;
1557 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001558
Lloyd Pique441d5042018-10-18 16:49:51 -07001559 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001560 ALOGE("Vr flinger is only supported for remote hardware composer"
1561 " service connections. Ignoring request to transition to vr"
1562 " flinger.");
1563 mVrFlingerRequestsDisplay = false;
1564 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001565 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001568
Steven Thomas0123ac62018-07-12 11:32:34 -07001569 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001570 LOG_ALWAYS_FATAL_IF(!display);
1571 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001572 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1573 // called below. Clear the reference now so we don't accidentally use it
1574 // later.
1575 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001576
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001578 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001580
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001582 // Delete the current instance before creating the new one
1583 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1584 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1585 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1586 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001587
Lloyd Pique441d5042018-10-18 16:49:51 -07001588 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001589 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001590
1591 if (vrFlingerRequestsDisplay) {
1592 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594
1595 mVisibleRegionsDirty = true;
1596 invalidateHwcGeometry();
1597
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001598 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001599 display = getDefaultDisplayDeviceLocked();
1600 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001601 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001602
Steven Thomasb02664d2017-07-26 18:48:28 -07001603 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001604 const nsecs_t vsyncPeriod = getVsyncPeriod();
1605 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001606
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001607 // The present fences returned from vr_hwc are not an accurate
1608 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001609 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1611 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001612 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001613 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001614 !hasSyncFramework);
1615 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001616
Steven Thomasb02664d2017-07-26 18:48:28 -07001617 // Use phase of 0 since phase is not known.
1618 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001619 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001620 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001621
Dominik Laskowski83b88212018-12-11 13:34:06 -08001622 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001623
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001624 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001625 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001626}
1627
Mathias Agopian4fec8732012-06-29 14:12:52 -07001628void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001629 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001630 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001631 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001632 if (mUseScheduler) {
1633 // This call is made each time SF wakes up and creates a new frame.
1634 mScheduler->incrementFrameCounter();
1635 }
Dan Stoza50182882016-07-08 12:02:20 -07001636 bool frameMissed = !mHadClientComposition &&
1637 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638 (mPreviousPresentFence->getSignalTime() ==
1639 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001640 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001641 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001642 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001643 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001644 if (mPropagateBackpressure) {
1645 signalLayerUpdate();
1646 break;
1647 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001648 }
Dan Stoza50182882016-07-08 12:02:20 -07001649
Steven Thomas050b2c82017-03-06 11:45:16 -08001650 // Now that we're going to make it to the handleMessageTransaction()
1651 // call below it's safe to call updateVrFlinger(), which will
1652 // potentially trigger a display handoff.
1653 updateVrFlinger();
1654
Dan Stoza6b9454d2014-11-07 16:00:59 -08001655 bool refreshNeeded = handleMessageTransaction();
1656 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001657 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001658 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001659 // Signal a refresh if a transaction modified the window state,
1660 // a new buffer was latched, or if HWC has requested a full
1661 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001662 signalRefresh();
1663 }
1664 break;
1665 }
1666 case MessageQueue::REFRESH: {
1667 handleMessageRefresh();
1668 break;
1669 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001670 }
1671}
1672
Dan Stoza6b9454d2014-11-07 16:00:59 -08001673bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001674 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001675
1676 // Apply any ready transactions in the queues if there are still transactions that have not been
1677 // applied, wake up during the next vsync period and check again
1678 bool transactionNeeded = false;
1679 if (!flushTransactionQueues()) {
1680 transactionNeeded = true;
1681 }
1682
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001684 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001685 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001686
1687 if (transactionNeeded) {
1688 setTransactionFlags(eTransactionNeeded);
1689 }
1690
1691 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692}
1693
Mathias Agopian4fec8732012-06-29 14:12:52 -07001694void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001696
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001697 mRefreshPending = false;
1698
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001699 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001700 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001701 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001702 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001703 for (const auto& [token, display] : mDisplays) {
1704 beginFrame(display);
1705 prepareFrame(display);
1706 doDebugFlashRegions(display, repaintEverything);
1707 doComposition(display, repaintEverything);
1708 }
1709
Adrian Roos1e1a1282017-11-01 19:05:31 +01001710 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001711 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001712
1713 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001714 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001715
Dan Stozabfbffeb2016-07-21 14:49:33 -07001716 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001717 for (const auto& [token, displayDevice] : mDisplays) {
1718 auto display = displayDevice->getCompositionDisplay();
1719 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001720 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001721 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001722 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001723
Alec Mouri86770e52018-09-24 22:40:58 +00001724 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001725 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001726 if (mHadClientComposition) {
1727 base::unique_fd flushFence(getRenderEngine().flush());
1728 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1729 getBE().flushFence = new Fence(std::move(flushFence));
1730 } else {
1731 // Cleanup for hygiene.
1732 getBE().flushFence = Fence::NO_FENCE;
1733 }
1734 }
1735
Jorim Jaggi90535212018-05-23 23:44:06 +02001736 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001737
David Sodman7e4ae112018-02-09 15:02:28 -08001738 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001739 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001740 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001741 compositionInfo.hwc.hwcLayer = nullptr;
1742 }
David Sodmanba340492018-08-05 21:51:33 -07001743 }
David Sodman7e4ae112018-02-09 15:02:28 -08001744
1745 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001747
David Sodmanfa9b2af2017-12-24 13:28:59 -08001748
1749bool SurfaceFlinger::handleMessageInvalidate() {
1750 ATRACE_CALL();
1751 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001752}
1753
David Sodman79bba0e2018-08-05 18:07:49 -07001754void SurfaceFlinger::calculateWorkingSet() {
1755 ATRACE_CALL();
1756 ALOGV(__FUNCTION__);
1757
David Sodman79bba0e2018-08-05 18:07:49 -07001758 // build the h/w work list
1759 if (CC_UNLIKELY(mGeometryInvalid)) {
1760 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001761 for (const auto& [token, displayDevice] : mDisplays) {
1762 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001763 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001764 if (!displayId) {
1765 continue;
1766 }
David Sodman79bba0e2018-08-05 18:07:49 -07001767
Lloyd Pique32cbe282018-10-19 13:09:22 -07001768 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 for (size_t i = 0; i < currentLayers.size(); i++) {
1770 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001771
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772 if (!layer->hasHwcLayer(*displayId)) {
1773 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1774 layer->forceClientComposition(*displayId);
1775 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001776 }
1777 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778
Lloyd Pique32cbe282018-10-19 13:09:22 -07001779 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001780 if (mDebugDisableHWC || mDebugRegion) {
1781 layer->forceClientComposition(*displayId);
1782 }
David Sodman79bba0e2018-08-05 18:07:49 -07001783 }
1784 }
1785 }
1786
1787 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001788 for (const auto& [token, displayDevice] : mDisplays) {
1789 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001790 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001792 continue;
1793 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001794 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001795
1796 if (mDrawingState.colorMatrixChanged) {
1797 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001798 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001799 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001800 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001802 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1803 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001804 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1807 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001808 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001809 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001810 }
1811
Peiyong Lind3788632018-09-18 16:01:31 -07001812 // TODO(b/111562338) remove when composer 2.3 is shipped.
1813 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001814 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001815 }
1816
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001817 if (layer->getRoundedCornerState().radius > 0.0f) {
1818 layer->forceClientComposition(*displayId);
1819 }
1820
Dominik Laskowski075d3172018-05-24 15:50:06 -07001821 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001822 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001823 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001824 continue;
1825 }
1826
Lloyd Pique32cbe282018-10-19 13:09:22 -07001827 const auto& displayState = display->getState();
1828 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1829 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001830 }
1831
Peiyong Lin13effd12018-07-24 17:01:47 -07001832 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001833 ColorMode colorMode;
1834 Dataspace dataSpace;
1835 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001836 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001837 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001838 }
1839 }
1840
1841 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001842
1843 for (const auto& [token, display] : mDisplays) {
1844 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001845 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001846 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001847
1848 if (displayId) {
1849 if (!layer->setHwcLayer(*displayId)) {
1850 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1851 }
1852 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001853 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001854
Dominik Laskowski05275f12018-11-01 15:03:24 -07001855 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001856 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1857 }
1858 }
David Sodman79bba0e2018-08-05 18:07:49 -07001859}
1860
Lloyd Pique32cbe282018-10-19 13:09:22 -07001861void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1862 bool repaintEverything) {
1863 auto display = displayDevice->getCompositionDisplay();
1864 const auto& displayState = display->getState();
1865
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 // is debugging enabled
1867 if (CC_LIKELY(!mDebugRegion))
1868 return;
1869
Lloyd Pique32cbe282018-10-19 13:09:22 -07001870 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001871 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08001872 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001873 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001874 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001875 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001876 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877
Alec Mouri0f714832018-11-12 15:31:06 -08001878 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879 }
1880 }
1881
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883
1884 if (mDebugRegion > 1) {
1885 usleep(mDebugRegion * 1000);
1886 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001887
Lloyd Pique32cbe282018-10-19 13:09:22 -07001888 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889}
1890
Adrian Roos1e1a1282017-11-01 19:05:31 +01001891void SurfaceFlinger::doTracing(const char* where) {
1892 ATRACE_CALL();
1893 ATRACE_NAME(where);
1894 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001895 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001896 }
1897}
1898
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001899void SurfaceFlinger::logLayerStats() {
1900 ATRACE_CALL();
1901 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001902 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001903 if (display->isPrimary()) {
1904 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001905 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001906 }
1907 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001908
1909 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001910 }
1911}
1912
David Sodman2b406362017-12-15 13:33:47 -08001913void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 ATRACE_CALL();
1916 ALOGV("preComposition");
1917
David Sodman2b406362017-12-15 13:33:47 -08001918 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1919
Mathias Agopiancd60f992012-08-16 16:28:27 -07001920 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001921 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001922 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001923 needExtraInvalidate = true;
1924 }
Robert Carr2047fae2016-11-28 14:09:09 -08001925 });
1926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 if (needExtraInvalidate) {
1928 signalLayerUpdate();
1929 }
1930}
1931
Ana Krulece588e312018-09-18 12:32:24 -07001932void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1933 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 // Update queue of past composite+present times and determine the
1935 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001936 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001938 while (!getBE().mCompositePresentTimes.empty()) {
1939 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940 // Cached values should have been updated before calling this method,
1941 // which helps avoid duplicate syscalls.
1942 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1943 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1944 break;
1945 }
1946 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001947 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 }
1949
1950 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001951 while (getBE().mCompositePresentTimes.size() > 16) {
1952 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 }
1954
Ana Krulece588e312018-09-18 12:32:24 -07001955 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001956}
1957
Ana Krulece588e312018-09-18 12:32:24 -07001958void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1959 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 // Integer division and modulo round toward 0 not -inf, so we need to
1961 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001962 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1963 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1964 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965
Ana Krulec757f63a2019-01-25 10:46:18 -08001966 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001967 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001968 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001969 }
1970
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971 // Snap the latency to a value that removes scheduling jitter from the
1972 // composition and present times, which often have >1ms of jitter.
1973 // Reducing jitter is important if an app attempts to extrapolate
1974 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001975 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001977 nsecs_t bias = stats.vsyncPeriod / 2;
1978 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1979 nsecs_t snappedCompositeToPresentLatency =
1980 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981
David Sodman99974d22017-11-28 12:04:33 -08001982 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001983 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1984 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001985 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986}
1987
Ady Abraham8164d482019-01-11 14:47:59 -08001988// debug patch for b/119477596 - add stack guards to catch stack
1989// corruptions and disable clang optimizations.
1990// The code below is temporary and planned to be removed once stack
1991// corruptions are found.
1992#pragma clang optimize off
1993class StackGuard {
1994public:
1995 StackGuard(const char* name, const char* func, int line) {
1996 guarders.reserve(MIN_CAPACITY);
1997 guarders.push_back({this, name, func, line});
1998 validate();
1999 }
2000 ~StackGuard() {
2001 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2002 if (i->guard == this) {
2003 guarders.erase(i);
2004 break;
2005 }
2006 }
2007 }
2008
2009 static void validate() {
2010 for (const auto& guard : guarders) {
2011 if (guard.guard->cookie != COOKIE_VALUE) {
2012 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2013 CallStack stack(LOG_TAG);
2014 abort();
2015 }
2016 }
2017 }
2018
2019private:
2020 uint64_t cookie = COOKIE_VALUE;
2021 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2022 static constexpr size_t MIN_CAPACITY = 16;
2023
2024 struct GuarderElement {
2025 StackGuard* guard;
2026 const char* name;
2027 const char* func;
2028 int line;
2029 };
2030
2031 static std::vector<GuarderElement> guarders;
2032};
2033std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2034
2035#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2036
2037#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002038void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002039{
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 ATRACE_CALL();
2042 ALOGV("postComposition");
2043
Brian Anderson3546a3f2016-07-14 11:51:14 -07002044 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002045 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002047 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002048 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002049 }
Ady Abraham8164d482019-01-11 14:47:59 -08002050 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002052 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002053 const auto displayDevice = getDefaultDisplayDeviceLocked();
2054 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055
David Sodman73beded2017-11-15 11:56:06 -08002056 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002057 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002058 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2059
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002062 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2063 ->getRenderSurface()
2064 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002065 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066 } else {
2067 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2068 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002069
Ady Abraham8164d482019-01-11 14:47:59 -08002070 ASSERT_ON_STACK_GUARD();
2071
David Sodman73beded2017-11-15 11:56:06 -08002072 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2074 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002075 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002076 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002077 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002078
Ana Krulece588e312018-09-18 12:32:24 -07002079 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002080 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002081 if (mUseScheduler) {
2082 mScheduler->getDisplayStatInfo(&stats);
2083 } else {
2084 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2085 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2086 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087
Ady Abraham8164d482019-01-11 14:47:59 -08002088 ASSERT_ON_STACK_GUARD();
2089
David Sodman2b406362017-12-15 13:33:47 -08002090 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091 // when we started doing work for this frame, but that should be okay
2092 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002093 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002094 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002095 DEFINE_STACK_GUARD(compositorTiming);
2096
Brian Andersond0010582017-03-07 13:20:31 -08002097 {
David Sodman99974d22017-11-28 12:04:33 -08002098 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002099 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002100 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002101
2102 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002103 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002104
Robert Carr2047fae2016-11-28 14:09:09 -08002105 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002106 bool frameLatched =
2107 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2108 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002110 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002111 recordBufferingStats(layer->getName().string(),
2112 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002113 }
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002115 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002117 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002118 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002119 if (mUseScheduler) {
2120 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002122 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002123 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2124 enableHardwareVsync();
2125 } else {
2126 disableHardwareVsync(false);
2127 }
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 }
2130 }
2131
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002132 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002133 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2134 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002135 if (mUseScheduler) {
2136 mScheduler->enableHardwareVsync();
2137 } else {
2138 enableHardwareVsync();
2139 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002140 }
2141 }
2142
Ady Abraham8164d482019-01-11 14:47:59 -08002143 ASSERT_ON_STACK_GUARD();
2144
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002145 if (mAnimCompositionPending) {
2146 mAnimCompositionPending = false;
2147
Brian Anderson4e606e32017-03-16 15:34:57 -07002148 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002149 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002150 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002151
2152 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002154 // The HWC doesn't support present fences, so use the refresh
2155 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002156 const nsecs_t presentTime =
2157 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(presentTime);
2159
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002160 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002161 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002162 }
2163 mAnimFrameTracker.advanceFrame();
2164 }
Dan Stozab90cf072015-03-05 11:05:59 -08002165
Ady Abraham8164d482019-01-11 14:47:59 -08002166 ASSERT_ON_STACK_GUARD();
2167
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002168 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002169 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002170 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002171 }
2172
Ady Abraham8164d482019-01-11 14:47:59 -08002173 ASSERT_ON_STACK_GUARD();
2174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002176
Ady Abraham8164d482019-01-11 14:47:59 -08002177 ASSERT_ON_STACK_GUARD();
2178
Lloyd Pique32cbe282018-10-19 13:09:22 -07002179 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2180 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002181 return;
2182 }
2183
2184 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002185 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002186 if (mHasPoweredOff) {
2187 mHasPoweredOff = false;
2188 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002189 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002190 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002191 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002192 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002193 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2194 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002195 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002196 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002197 }
David Sodman4a36e932017-11-07 14:29:47 -08002198 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002199
2200 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002201 }
David Sodman4a36e932017-11-07 14:29:47 -08002202 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002203 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002204
2205 {
2206 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002207 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002208 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002209 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002210 if (refillCount > 0) {
2211 const size_t offset = mTexturePool.size();
2212 mTexturePool.resize(mTexturePoolSize);
2213 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2214 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2215 }
Ady Abraham8164d482019-01-11 14:47:59 -08002216 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002217 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002218
Marissa Wallfda30bb2018-10-12 11:34:28 -07002219 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002220 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002221
2222 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002223}
Ady Abraham8164d482019-01-11 14:47:59 -08002224#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225
2226void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002227 ATRACE_CALL();
2228 ALOGV("rebuildLayerStacks");
2229
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002230 // We need to clear these out now as these may be holding on to a
2231 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2232 // also holds a reference. When the set of visible layers is recomputed,
2233 // some layers may be destroyed if the only thing keeping them alive was
2234 // that list of visible layers associated with each display. The layer
2235 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2236 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2237 for (const auto& [token, display] : mDisplays) {
2238 getBE().mCompositionInfo[token].clear();
2239 }
2240
Mathias Agopiancd60f992012-08-16 16:28:27 -07002241 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002242 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002243 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002244 mVisibleRegionsDirty = false;
2245 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002246
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002247 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002248 const auto& displayDevice = pair.second;
2249 auto display = displayDevice->getCompositionDisplay();
2250 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 Region opaqueRegion;
2252 Region dirtyRegion;
2253 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002254 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const ui::Transform& tr = displayState.transform;
2256 const Rect bounds = displayState.bounds;
2257 if (displayState.isEnabled) {
2258 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002259
Jeff Sharkey76488112017-02-27 14:15:18 -07002260 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002261 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002262 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002263 if (display->belongsInOutput(layer->getLayerStack(),
2264 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002265 Region drawRegion(tr.transform(
2266 layer->visibleNonTransparentRegion));
2267 drawRegion.andSelf(bounds);
2268 if (!drawRegion.isEmpty()) {
2269 layersSortedByZ.add(layer);
2270 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002271 // Clear out the HWC layer if this layer was
2272 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002274 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002275 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002276 // WM changes display->layerStack upon sleep/awake.
2277 // Here we make sure we delete the HWC layers even if
2278 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002280 }
2281
2282 // If a layer is not going to get a release fence because
2283 // it is invisible, but it is also going to release its
2284 // old buffer, add it to the list of layers needing
2285 // fences.
2286 if (hwcLayerDestroyed) {
2287 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2288 mLayersWithQueuedFrames.cend(), layer);
2289 if (found != mLayersWithQueuedFrames.cend()) {
2290 layersNeedingFences.add(layer);
2291 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002292 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002293 });
2294 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002295 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2296 displayDevice->setLayersNeedingFences(layersNeedingFences);
2297
2298 Region undefinedRegion{bounds};
2299 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2300
2301 display->editState().undefinedRegion = undefinedRegion;
2302 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002303 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002304 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002305}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002306
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002309// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002311// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312// The returned HDR data space is one of
2313// - Dataspace::UNKNOWN
2314// - Dataspace::BT2020_HLG
2315// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002316Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2317 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002318 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319 *outHdrDataSpace = Dataspace::UNKNOWN;
2320
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002322 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 case Dataspace::V0_SCRGB:
2324 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002325 case Dataspace::BT2020:
2326 case Dataspace::BT2020_ITU:
2327 case Dataspace::BT2020_LINEAR:
2328 case Dataspace::DISPLAY_BT2020:
2329 bestDataSpace = Dataspace::DISPLAY_BT2020;
2330 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002332 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002333 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 case Dataspace::BT2020_PQ:
2335 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002338 case Dataspace::BT2020_HLG:
2339 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340 // When there's mixed PQ content and HLG content, we set the HDR
2341 // data space to be BT2020_PQ and convert HLG to PQ.
2342 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2343 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002344 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 break;
2346 default:
2347 break;
2348 }
Romain Guy54f154a2017-10-24 21:40:32 +01002349 }
2350
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002352}
2353
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002354// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2356 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2358 *outMode = ColorMode::NATIVE;
2359 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002362 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002363
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002364 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002367 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2368
Peiyong Lindfde5112018-06-05 10:58:41 -07002369 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002370 const bool isHdr =
2371 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002372 if (isHdr) {
2373 bestDataSpace = hdrDataSpace;
2374 }
2375
Chia-I Wu0d711262018-05-21 15:19:35 -07002376 RenderIntent intent;
2377 switch (mDisplayColorSetting) {
2378 case DisplayColorSetting::MANAGED:
2379 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002380 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002381 break;
2382 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002383 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002384 break;
2385 default: // vendor display color setting
2386 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2387 break;
2388 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002389
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002390 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002391}
2392
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2394 auto display = displayDevice->getCompositionDisplay();
2395 const auto& displayState = display->getState();
2396
Alec Mouri0f714832018-11-12 15:31:06 -08002397 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002398 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2399 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002400
David Sodmanfa9b2af2017-12-24 13:28:59 -08002401 // If nothing has changed (!dirty), don't recompose.
2402 // If something changed, but we don't currently have any visible layers,
2403 // and didn't when we last did a composition, then skip it this time.
2404 // The second rule does two things:
2405 // - When all layers are removed from a display, we'll emit one black
2406 // frame, then nothing more until we get new layers.
2407 // - When a display is created with a private layer stack, we won't
2408 // emit any black frames until a layer is added to the layer stack.
2409 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002410
Dominik Laskowski075d3172018-05-24 15:50:06 -07002411 const char flagPrefix[] = {'-', '+'};
2412 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2414 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2415 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2416 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002417
Lloyd Pique31cb2942018-10-19 17:23:03 -07002418 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002419
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002422 }
2423}
2424
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2426 auto display = displayDevice->getCompositionDisplay();
2427 const auto& displayState = display->getState();
2428
2429 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 return;
David Sodman2b406362017-12-15 13:33:47 -08002431 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002432
Lloyd Pique31cb2942018-10-19 17:23:03 -07002433 status_t result = display->getRenderSurface()->prepareFrame(
2434 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002437}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002440 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 ALOGV("doComposition");
2442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 auto display = displayDevice->getCompositionDisplay();
2444 const auto& displayState = display->getState();
2445
2446 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002448 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002449
David Sodmanfa9b2af2017-12-24 13:28:59 -08002450 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002452
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002454 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002455 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002457}
2458
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459void SurfaceFlinger::postFrame()
2460{
2461 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 const auto display = getDefaultDisplayDeviceLocked();
2463 if (display && getHwComposer().isConnected(*display->getId())) {
2464 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002465 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2466 logFrameStats();
2467 }
2468 }
2469}
2470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002472 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002474
Lloyd Pique32cbe282018-10-19 13:09:22 -07002475 auto display = displayDevice->getCompositionDisplay();
2476 const auto& displayState = display->getState();
2477 const auto displayId = display->getId();
2478
David Sodmanfa9b2af2017-12-24 13:28:59 -08002479 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 if (displayId) {
2483 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002484 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002485 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002487 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002488
Chia-I Wu7b549592017-11-15 09:14:57 -08002489 // The layer buffer from the previous frame (if any) is released
2490 // by HWC only when the release fence from this frame (if any) is
2491 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 if (displayId && layer->hasHwcLayer(*displayId)) {
2493 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2494 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002495 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002496
2497 // If the layer was client composited in the previous frame, we
2498 // need to merge with the previous client target acquire fence.
2499 // Since we do not track that, always merge with the current
2500 // client target acquire fence when it is available, even though
2501 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002502 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002503 releaseFence =
2504 Fence::merge("LayerRelease", releaseFence,
2505 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002506 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002507
David Sodman15094112018-10-11 09:39:37 -07002508 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002509 }
Chia-I Wu83806892017-11-16 10:50:20 -08002510
2511 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002513 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002514 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002516 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002517 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002518 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002519 }
2520 }
2521
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 if (displayId) {
2523 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002524 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526}
2527
Mathias Agopian87baae12012-07-31 12:38:26 -07002528void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529{
Mathias Agopian841cde52012-03-01 15:44:37 -08002530 ATRACE_CALL();
2531
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002532 // here we keep a copy of the drawing state (that is the state that's
2533 // going to be overwritten by handleTransactionLocked()) outside of
2534 // mStateLock so that the side-effects of the State assignment
2535 // don't happen with mStateLock held (which can cause deadlocks).
2536 State drawingState(mDrawingState);
2537
Mathias Agopianca4d3602011-05-19 15:38:14 -07002538 Mutex::Autolock _l(mStateLock);
2539 const nsecs_t now = systemTime();
2540 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541
Mathias Agopianca4d3602011-05-19 15:38:14 -07002542 // Here we're guaranteed that some transaction flags are set
2543 // so we can call handleTransactionLocked() unconditionally.
2544 // We call getTransactionFlags(), which will also clear the flags,
2545 // with mStateLock held to guarantee that mCurrentState won't change
2546 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002547
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002548 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002549 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002550 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002551
Mathias Agopianca4d3602011-05-19 15:38:14 -07002552 mLastTransactionTime = systemTime() - now;
2553 mDebugInTransaction = 0;
2554 invalidateHwcGeometry();
2555 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002556}
2557
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2559 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 const std::optional<DisplayIdentificationInfo> info =
2561 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002564 continue;
2565 }
2566
Lloyd Piqueba04e622017-12-14 17:11:26 -08002567 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002569 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 mPhysicalDisplayTokens[info->id] = new BBinder();
2571 DisplayDeviceState state;
2572 state.displayId = info->id;
2573 state.isSecure = true; // All physical displays are currently considered secure.
2574 state.displayName = info->name;
2575 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2576 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002577 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002579 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002580
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2582 if (index >= 0) {
2583 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2584 mInterceptor->saveDisplayDeletion(state.sequenceId);
2585 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002586 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588 }
2589
2590 processDisplayChangesLocked();
2591 }
2592
2593 mPendingHotplugEvents.clear();
2594}
2595
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002596void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2597 bool connected) {
2598 if (mUseScheduler) {
2599 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2600 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2601 } else {
2602 mEventThread->onHotplugReceived(displayType, connected);
2603 mSFEventThread->onHotplugReceived(displayType, connected);
2604 }
2605}
2606
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002609 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 const sp<IGraphicBufferProducer>& producer) {
2611 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002612 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.isSecure = state.isSecure;
2615 creationArgs.displaySurface = dispSurface;
2616 creationArgs.hasWideColorGamut = false;
2617 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002618
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2620 creationArgs.isPrimary = isInternalDisplay;
2621
2622 if (useColorManagement && displayId) {
2623 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002625 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002626 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002628
Dominik Laskowski7e045462018-05-30 13:02:02 -07002629 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002631 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632 }
tangrobin6753a022018-08-10 10:58:54 +08002633 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 if (displayId) {
2636 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002637 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002639 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640
Lloyd Pique90c115d2018-09-18 21:39:42 -07002641 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002643 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644
Lloyd Pique99d3da52018-01-22 17:48:03 -08002645 // Make sure that composition can never be stalled by a virtual display
2646 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002647 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002648 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2650 }
2651
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 creationArgs.displayInstallOrientation =
2653 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002654
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002656 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657
Lloyd Pique90c115d2018-09-18 21:39:42 -07002658 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659
2660 if (maxFrameBufferAcquiredBuffers >= 3) {
2661 nativeWindowSurface->preallocateBuffers();
2662 }
2663
2664 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002665 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002666 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002668 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002670 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2671 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 if (!state.isVirtual()) {
2673 LOG_ALWAYS_FATAL_IF(!displayId);
2674 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002675 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002677 display->setLayerStack(state.layerStack);
2678 display->setProjection(state.orientation, state.viewport, state.frame);
2679 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002682}
2683
Lloyd Pique347200f2017-12-14 17:00:15 -08002684void SurfaceFlinger::processDisplayChangesLocked() {
2685 // here we take advantage of Vector's copy-on-write semantics to
2686 // improve performance by skipping the transaction entirely when
2687 // know that the lists are identical
2688 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2689 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2690 if (!curr.isIdenticalTo(draw)) {
2691 mVisibleRegionsDirty = true;
2692 const size_t cc = curr.size();
2693 size_t dc = draw.size();
2694
2695 // find the displays that were removed
2696 // (ie: in drawing state but not in current state)
2697 // also handle displays that changed
2698 // (ie: displays that are in both lists)
2699 for (size_t i = 0; i < dc;) {
2700 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2701 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002702 // Save display IDs before disconnecting.
2703 const auto internalDisplayId = getInternalDisplayId();
2704 const auto externalDisplayId = getExternalDisplayId();
2705
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002708 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002711 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002712 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002713 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002714 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 } else {
2717 // this display is in both lists. see if something changed.
2718 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2721 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2722 if (state_binder != draw_binder) {
2723 // changing the surface is like destroying and
2724 // recreating the DisplayDevice, so we just remove it
2725 // from the drawing state, so that it get re-added
2726 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002728 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 mDrawingState.displays.removeItemsAt(i);
2732 dc--;
2733 // at this point we must loop to the next item
2734 continue;
2735 }
2736
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 }
2741 if ((state.orientation != draw[i].orientation) ||
2742 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002743 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 }
2745 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747 }
2748 }
2749 }
2750 ++i;
2751 }
2752
2753 // find displays that were added
2754 // (ie: in current state but not in drawing state)
2755 for (size_t i = 0; i < cc; i++) {
2756 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2757 const DisplayDeviceState& state(curr[i]);
2758
Lloyd Pique542307f2018-10-19 13:24:08 -07002759 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 sp<IGraphicBufferProducer> producer;
2761 sp<IGraphicBufferProducer> bqProducer;
2762 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002763 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002766 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 // Virtual displays without a surface are dormant:
2768 // they have external state (layer stack, projection,
2769 // etc.) but no internal state (i.e. a DisplayDevice).
2770 if (state.surface != nullptr) {
2771 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002773 int width = 0;
2774 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2775 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2776 int height = 0;
2777 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2778 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2779 int intFormat = 0;
2780 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2781 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002782 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002783
Dominik Laskowski075d3172018-05-24 15:50:06 -07002784 displayId =
2785 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 }
2787
2788 // TODO: Plumb requested format back up to consumer
2789
2790 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 bqProducer, bqConsumer,
2793 state.displayName);
2794
2795 dispSurface = vds;
2796 producer = vds;
2797 }
2798 } else {
2799 ALOGE_IF(state.surface != nullptr,
2800 "adding a supported display, but rendering "
2801 "surface is provided (%p), ignoring it",
2802 state.surface.get());
2803
Dominik Laskowski075d3172018-05-24 15:50:06 -07002804 displayId = state.displayId;
2805 LOG_ALWAYS_FATAL_IF(!displayId);
2806 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 producer = bqProducer;
2808 }
2809
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002810 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002811 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002812 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002813 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002815 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002816 LOG_ALWAYS_FATAL_IF(!displayId);
2817
2818 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002819 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002820 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002821 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002822 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002823 }
2824 }
2825 }
2826 }
2827 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002828
2829 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002830}
2831
Mathias Agopian87baae12012-07-31 12:38:26 -07002832void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002833{
Dan Stoza7dde5992015-05-22 09:51:44 -07002834 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002835 mCurrentState.traverseInZOrder([](Layer* layer) {
2836 layer->notifyAvailableFrames();
2837 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002838
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 /*
2840 * Traversal of the children
2841 * (perform the transaction for each of them if needed)
2842 */
2843
Robert Carr720e5062018-07-30 17:45:14 -07002844 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002845 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002846 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002848 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849
2850 const uint32_t flags = layer->doTransaction(0);
2851 if (flags & Layer::eVisibleRegion)
2852 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002853
2854 if (flags & Layer::eInputInfoChanged) {
2855 inputChanged = true;
2856 }
Robert Carr2047fae2016-11-28 14:09:09 -08002857 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 }
2859
2860 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002861 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 */
2863
Mathias Agopiane57f2922012-08-09 16:29:12 -07002864 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002865 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002866 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002867 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002869 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002870 // The transform hint might have changed for some layers
2871 // (either because a display has changed, or because a layer
2872 // as changed).
2873 //
2874 // Walk through all the layers in currentLayers,
2875 // and update their transform hint.
2876 //
2877 // If a layer is visible only on a single display, then that
2878 // display is used to calculate the hint, otherwise we use the
2879 // default display.
2880 //
2881 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2882 // the hint is set before we acquire a buffer from the surface texture.
2883 //
2884 // NOTE: layer transactions have taken place already, so we use their
2885 // drawing state. However, SurfaceFlinger's own transaction has not
2886 // happened yet, so we must use the current state layer list
2887 // (soon to become the drawing state list).
2888 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002890 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002891 bool first = true;
2892 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002893 // NOTE: we rely on the fact that layers are sorted by
2894 // layerStack first (so we don't have to traverse the list
2895 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002897 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002898 currentlayerStack = layerStack;
2899 // figure out if this layerstack is mirrored
2900 // (more than one display) if so, pick the default display,
2901 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002902 hintDisplay = nullptr;
2903 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002904 if (display->getCompositionDisplay()
2905 ->belongsInOutput(layer->getLayerStack(),
2906 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 if (hintDisplay) {
2908 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002909 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002911 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002912 }
2913 }
2914 }
2915 }
Chet Haase91d25932013-04-11 15:24:55 -07002916
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002917 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002918 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2919 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002920
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002921 // could be null when this layer is using a layerStack
2922 // that is not visible on any display. Also can occur at
2923 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002924 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002925 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002926
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002928 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002929 if (hintDisplay) {
2930 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002931 }
Robert Carr2047fae2016-11-28 14:09:09 -08002932
2933 first = false;
2934 });
Mathias Agopian84300952012-11-21 16:02:13 -08002935 }
2936
2937
Mathias Agopian3559b072012-08-15 13:46:03 -07002938 /*
2939 * Perform our own transaction if needed
2940 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941
2942 if (mLayersAdded) {
2943 mLayersAdded = false;
2944 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002945 mVisibleRegionsDirty = true;
2946 }
2947
2948 // some layers might have been removed, so
2949 // we need to update the regions they're exposing.
2950 if (mLayersRemoved) {
2951 mLayersRemoved = false;
2952 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002953 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002954 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 // this layer is not visible anymore
2956 // TODO: we could traverse the tree from front to back and
2957 // compute the actual visible region
2958 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959 Region visibleReg;
2960 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002961 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002962 }
Robert Carr2047fae2016-11-28 14:09:09 -08002963 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 }
2965
2966 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002967
Vishnu Nairde19f852018-12-18 16:11:53 -08002968 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002969 updateInputWindows();
2970 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002971 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002972
Riley Andrews03414a12014-07-01 14:22:59 -07002973 updateCursorAsync();
2974}
2975
Robert Carr720e5062018-07-30 17:45:14 -07002976void SurfaceFlinger::updateInputWindows() {
2977 ATRACE_CALL();
2978
Vishnu Nairde19f852018-12-18 16:11:53 -08002979 if (mInputFlinger == nullptr) {
2980 return;
2981 }
2982
Robert Carr720e5062018-07-30 17:45:14 -07002983 Vector<InputWindowInfo> inputHandles;
2984
2985 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2986 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002987 // When calculating the screen bounds we ignore the transparent region since it may
2988 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002989 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002990 }
2991 });
2992 mInputFlinger->setInputWindows(inputHandles);
2993}
2994
chaviwfbe5d9c2018-12-26 12:23:37 -08002995void SurfaceFlinger::executeInputWindowCommands() {
2996 if (!mInputFlinger) {
2997 return;
2998 }
2999
3000 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3001 if (transferTouchFocusCommand.fromToken != nullptr &&
3002 transferTouchFocusCommand.toToken != nullptr &&
3003 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3004 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3005 transferTouchFocusCommand.toToken);
3006 }
3007 }
3008
3009 mInputWindowCommands.clear();
3010}
3011
Riley Andrews03414a12014-07-01 14:22:59 -07003012void SurfaceFlinger::updateCursorAsync()
3013{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003014 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003015 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003016 continue;
3017 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003019 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3020 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003021 }
3022 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003023}
3024
chaviw61626f22018-11-15 16:26:27 -08003025void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3026 if (layer->hasReadyFrame()) {
3027 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3028 if (layer->shouldPresentNow(expectedPresentTime)) {
3029 bool ignored = false;
3030 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3031 }
3032 }
3033 layer->releasePendingBuffer(systemTime());
3034}
3035
Mathias Agopian4fec8732012-06-29 14:12:52 -07003036void SurfaceFlinger::commitTransaction()
3037{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003038 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 for (const auto& l : mLayersPendingRemoval) {
3041 recordBufferingStats(l->getName().string(),
3042 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003043
3044 // We need to release the HWC layers when the Layer is removed
3045 // from the current state otherwise the HWC layer just continues
3046 // showing at its last configured state until we eventually
3047 // abandon the buffer queue.
3048 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003049 l->destroyHwcLayersForAllDisplays();
3050 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003051 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003052 }
3053 mLayersPendingRemoval.clear();
3054 }
3055
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003056 // If this transaction is part of a window animation then the next frame
3057 // we composite should be considered an animation as well.
3058 mAnimCompositionPending = mAnimTransactionPending;
3059
Mathias Agopian4fec8732012-06-29 14:12:52 -07003060 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003061 // clear the "changed" flags in current state
3062 mCurrentState.colorMatrixChanged = false;
3063
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 mDrawingState.traverseInZOrder([](Layer* layer) {
3065 layer->commitChildList();
3066 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003067 mTransactionPending = false;
3068 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003069 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Lloyd Pique32cbe282018-10-19 13:09:22 -07003072void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003073 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003074 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003075 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003076
Lloyd Pique32cbe282018-10-19 13:09:22 -07003077 auto display = displayDevice->getCompositionDisplay();
3078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079 Region aboveOpaqueLayers;
3080 Region aboveCoveredLayers;
3081 Region dirty;
3082
Mathias Agopian87baae12012-07-31 12:38:26 -07003083 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084
Robert Carr2047fae2016-11-28 14:09:09 -08003085 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003086 // start with the whole surface at its current location
3087 const Layer::State& s(layer->getDrawingState());
3088
Jesse Hall01e29052013-02-19 16:13:35 -08003089 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003090 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003091 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003092 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003093
Mathias Agopianab028732010-03-16 16:41:46 -07003094 /*
3095 * opaqueRegion: area of a surface that is fully opaque.
3096 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003098
3099 /*
3100 * visibleRegion: area of a surface that is visible on screen
3101 * and not fully transparent. This is essentially the layer's
3102 * footprint minus the opaque regions above it.
3103 * Areas covered by a translucent surface are considered visible.
3104 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003106
3107 /*
3108 * coveredRegion: area of a surface that is covered by all
3109 * visible regions above it (which includes the translucent areas).
3110 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003112
Jesse Halla8026d22012-09-25 13:25:04 -07003113 /*
3114 * transparentRegion: area of a surface that is hinted to be completely
3115 * transparent. This is only used to tell when the layer has no visible
3116 * non-transparent regions and can be removed from the layer list. It
3117 * does not affect the visibleRegion of this layer or any layers
3118 * beneath it. The hint may not be correct if apps don't respect the
3119 * SurfaceView restrictions (which, sadly, some don't).
3120 */
3121 Region transparentRegion;
3122
Mathias Agopianab028732010-03-16 16:41:46 -07003123
3124 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003125 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003126 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003130 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003131 if (!visibleRegion.isEmpty()) {
3132 // Remove the transparent area from the visible region
3133 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003134 if (tr.preserveRects()) {
3135 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003136 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003138 // transformation too complex, can't do the
3139 // transparent region optimization.
3140 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003141 }
Mathias Agopianab028732010-03-16 16:41:46 -07003142 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143
Mathias Agopianab028732010-03-16 16:41:46 -07003144 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003146 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003147 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003148 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003149 // the opaque region is the layer's footprint
3150 opaqueRegion = visibleRegion;
3151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 }
3154
Robert Carre5f4f692018-01-12 13:12:28 -08003155 if (visibleRegion.isEmpty()) {
3156 layer->clearVisibilityRegions();
3157 return;
3158 }
3159
Mathias Agopianab028732010-03-16 16:41:46 -07003160 // Clip the covered region to the visible region
3161 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3162
3163 // Update aboveCoveredLayers for next (lower) layer
3164 aboveCoveredLayers.orSelf(visibleRegion);
3165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 // subtract the opaque region covered by the layers above us
3167 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168
3169 // compute this layer's dirty region
3170 if (layer->contentDirty) {
3171 // we need to invalidate the whole region
3172 dirty = visibleRegion;
3173 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003174 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 layer->contentDirty = false;
3176 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003177 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003178 * the exposed region consists of two components:
3179 * 1) what's VISIBLE now and was COVERED before
3180 * 2) what's EXPOSED now less what was EXPOSED before
3181 *
3182 * note that (1) is conservative, we start with the whole
3183 * visible region but only keep what used to be covered by
3184 * something -- which mean it may have been exposed.
3185 *
3186 * (2) handles areas that were not covered by anything but got
3187 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003188 */
Mathias Agopianab028732010-03-16 16:41:46 -07003189 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003190 const Region oldVisibleRegion = layer->visibleRegion;
3191 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003192 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3193 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 }
3195 dirty.subtractSelf(aboveOpaqueLayers);
3196
3197 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003198 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199
Mathias Agopianab028732010-03-16 16:41:46 -07003200 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003202
Jesse Halla8026d22012-09-25 13:25:04 -07003203 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 layer->setVisibleRegion(visibleRegion);
3205 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003206 layer->setVisibleNonTransparentRegion(
3207 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003208 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209
Mathias Agopian87baae12012-07-31 12:38:26 -07003210 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211}
3212
Chia-I Wuab0c3192017-08-01 11:29:00 -07003213void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003214 for (const auto& [token, displayDevice] : mDisplays) {
3215 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003216 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003217 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003218 }
3219 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003220}
3221
Daniel Solomon42d04562019-01-20 21:03:19 -08003222void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3223 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3224 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3225 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3226 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3227 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3228 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3229 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3230 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3231 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3232 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3233 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3234 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3235}
3236
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003239 ALOGV("handlePageFlip");
3240
Brian Andersond6927fb2016-07-23 23:37:30 -07003241 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242
Mathias Agopian4fec8732012-06-29 14:12:52 -07003243 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003244 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003245 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003246
3247 // Store the set of layers that need updates. This set must not change as
3248 // buffers are being latched, as this could result in a deadlock.
3249 // Example: Two producers share the same command stream and:
3250 // 1.) Layer 0 is latched
3251 // 2.) Layer 0 gets a new frame
3252 // 2.) Layer 1 gets a new frame
3253 // 3.) Layer 1 is latched.
3254 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3255 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003256 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003257 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003259 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3260 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003261 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003262 } else {
3263 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003265 } else {
3266 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 }
Robert Carr2047fae2016-11-28 14:09:09 -08003268 });
3269
Lloyd Piquef2c79392018-12-20 16:23:33 -08003270 if (!mLayersWithQueuedFrames.empty()) {
3271 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3272 // writes to Layer current state. See also b/119481871
3273 Mutex::Autolock lock(mStateLock);
3274
3275 for (auto& layer : mLayersWithQueuedFrames) {
3276 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3277 layer->useSurfaceDamage();
3278 invalidateLayerStack(layer, dirty);
3279 if (layer->isBufferLatched()) {
3280 newDataLatched = true;
3281 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003282 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003283 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003284
Alec Mouri86770e52018-09-24 22:40:58 +00003285 // Clear the renderengine fence here...
3286 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3287 // clear instead of sp::clear.
3288 getBE().flushFence = Fence::NO_FENCE;
3289
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003290 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003291
Vishnu Nairde19f852018-12-18 16:11:53 -08003292 if (visibleRegions) {
3293 // Update input window info if the layer receives its first buffer.
3294 updateInputWindows();
3295 }
3296
Dan Stoza6b9454d2014-11-07 16:00:59 -08003297 // If we will need to wake up at some time in the future to deal with a
3298 // queued frame that shouldn't be displayed during this vsync period, wake
3299 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003300 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003301 signalLayerUpdate();
3302 }
3303
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003304 // enter boot animation on first buffer latch
3305 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3306 ALOGI("Enter boot animation");
3307 mBootStage = BootStage::BOOTANIMATION;
3308 }
3309
Dan Stoza6b9454d2014-11-07 16:00:59 -08003310 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003311 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003312}
3313
Mathias Agopianad456f92011-01-13 17:53:01 -08003314void SurfaceFlinger::invalidateHwcGeometry()
3315{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003316 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003317}
3318
Lloyd Pique32cbe282018-10-19 13:09:22 -07003319void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003320 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 auto display = displayDevice->getCompositionDisplay();
3322
Dan Stoza71433162014-02-04 16:22:36 -08003323 // We only need to actually compose the display if:
3324 // 1) It is being handled by hardware composer, which may need this to
3325 // keep its virtual display state machine in sync, or
3326 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003327 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003328 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003329 return;
3330 }
3331
Dan Stoza9e56aa02015-11-02 13:00:03 -08003332 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003333 base::unique_fd readyFence;
3334 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003335
3336 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003337 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338}
3339
Alec Mouri0f714832018-11-12 15:31:06 -08003340bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3341 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003342 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003343
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 auto display = displayDevice->getCompositionDisplay();
3345 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003346 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003347
3348 const Region bounds(displayState.bounds);
3349 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003350 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003351 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003352
Peiyong Lind3788632018-09-18 16:01:31 -07003353 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003355
Alec Mouri0f714832018-11-12 15:31:06 -08003356 renderengine::DisplaySettings clientCompositionDisplay;
3357 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3358 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003359
Dan Stoza9e56aa02015-11-02 13:00:03 -08003360 if (hasClientComposition) {
3361 ALOGV("hasClientComposition");
3362
Alec Mouri0f714832018-11-12 15:31:06 -08003363 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003364
3365 if (buf == nullptr) {
3366 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3367 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003368 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003369 return false;
3370 }
3371
Alec Mouri0f714832018-11-12 15:31:06 -08003372 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3373 clientCompositionDisplay.clip = displayState.scissor;
3374 const ui::Transform& displayTransform = displayState.transform;
3375 mat4 m;
3376 m[0][0] = displayTransform[0][0];
3377 m[0][1] = displayTransform[0][1];
3378 m[0][3] = displayTransform[0][2];
3379 m[1][0] = displayTransform[1][0];
3380 m[1][1] = displayTransform[1][1];
3381 m[1][3] = displayTransform[1][2];
3382 m[3][0] = displayTransform[2][0];
3383 m[3][1] = displayTransform[2][1];
3384 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003385
Alec Mouri0f714832018-11-12 15:31:06 -08003386 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003387
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003388 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003389 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003390 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003392 }
Alec Mouri0f714832018-11-12 15:31:06 -08003393 clientCompositionDisplay.outputDataspace = outputDataspace;
3394 clientCompositionDisplay.maxLuminance =
3395 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003396
Lloyd Pique441d5042018-10-18 16:49:51 -07003397 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003398 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003399 getHwComposer()
3400 .hasDisplayCapability(displayId,
3401 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003402
Peiyong Lind3788632018-09-18 16:01:31 -07003403 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003404 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3405 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003406 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003407 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003408 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003409
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 /*
3411 * and then, render the layers targeted at the framebuffer
3412 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003413
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003416 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003417 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003418 const Region viewportRegion(displayState.viewport);
3419 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003420 ALOGV("Layer: %s", layer->getName().string());
3421 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003423 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 case HWC2::Composition::Cursor:
3425 case HWC2::Composition::Device:
3426 case HWC2::Composition::Sideband:
3427 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003428 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003429 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003430 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003431 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003432 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 // never clear the very first layer since we're
3434 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003435 renderengine::LayerSettings layerSettings;
3436 Region dummyRegion;
3437 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3438 layerSettings);
3439
3440 if (prepared) {
3441 layerSettings.source.buffer.buffer = nullptr;
3442 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3443 layerSettings.alpha = half(0.0);
3444 layerSettings.disableBlending = true;
3445 clientCompositionLayers.push_back(layerSettings);
3446 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003447 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003448 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003449 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003450 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003451 renderengine::LayerSettings layerSettings;
3452 bool prepared =
3453 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3454 if (prepared) {
3455 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003456 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003457 break;
3458 }
3459 default:
3460 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003461 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003462 } else {
3463 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003464 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003465 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003466 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003467
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003468 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003469 clientCompositionDisplay.clearRegion = clearRegion;
3470 if (!debugRegion.isEmpty()) {
3471 Region::const_iterator it = debugRegion.begin();
3472 Region::const_iterator end = debugRegion.end();
3473 while (it != end) {
3474 const Rect& rect = *it++;
3475 renderengine::LayerSettings layerSettings;
3476 layerSettings.source.buffer.buffer = nullptr;
3477 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3478 layerSettings.geometry.boundaries = rect.toFloatRect();
3479 layerSettings.alpha = half(1.0);
3480 clientCompositionLayers.push_back(layerSettings);
3481 }
3482 }
3483 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3484 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003485 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003486 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487}
3488
Chia-I Wu28e3a252018-09-07 12:05:02 -07003489void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003490 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003491 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492}
3493
Dan Stoza7d89d062015-04-30 13:29:25 -07003494status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003495 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003496 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003497 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003498 const sp<Layer>& parent,
3499 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003500{
Dan Stoza7d89d062015-04-30 13:29:25 -07003501 // add this layer to the current state list
3502 {
3503 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003504 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003505 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3506 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003507 return NO_MEMORY;
3508 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003509 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003510 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003511 } else if (parent == nullptr) {
3512 lbc->onRemovedFromCurrentState();
3513 } else if (parent->isRemovedFromCurrentState()) {
3514 parent->addChild(lbc);
3515 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003516 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003517 parent->addChild(lbc);
3518 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003519
Yiwei Zhang243b3782018-05-15 17:40:04 -07003520 if (gbc != nullptr) {
3521 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3522 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3523 mMaxGraphicBufferProducerListSize,
3524 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3525 mGraphicBufferProducerList.size(),
3526 mMaxGraphicBufferProducerListSize, mNumLayers);
3527 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003528 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003529 }
3530
Mathias Agopian96f08192010-06-02 23:28:45 -07003531 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003532 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003533
Dan Stoza7d89d062015-04-30 13:29:25 -07003534 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003535}
3536
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003537uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003538 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003539}
3540
Mathias Agopian3f844832013-08-07 21:24:32 -07003541uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003542 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543}
3544
Mathias Agopian3f844832013-08-07 21:24:32 -07003545uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003546 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003547}
3548
3549uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003550 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003551 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003552 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003554 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555 }
3556 return old;
3557}
3558
Marissa Wall713b63f2018-10-17 15:42:43 -07003559bool SurfaceFlinger::flushTransactionQueues() {
3560 Mutex::Autolock _l(mStateLock);
3561 auto it = mTransactionQueues.begin();
3562 while (it != mTransactionQueues.end()) {
3563 auto& [applyToken, transactionQueue] = *it;
3564
3565 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003566 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3567 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003568 break;
3569 }
chaviw273171b2018-12-26 11:46:30 -08003570 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 transactionQueue.pop();
3572 }
3573
3574 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3575 }
3576 return mTransactionQueues.empty();
3577}
3578
chaviwca27f252018-02-06 16:46:39 -08003579bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3580 for (const ComposerState& state : states) {
3581 // Here we need to check that the interface we're given is indeed
3582 // one of our own. A malicious client could give us a nullptr
3583 // IInterface, or one of its own or even one of our own but a
3584 // different type. All these situations would cause us to crash.
3585 if (state.client == nullptr) {
3586 return true;
3587 }
3588
3589 sp<IBinder> binder = IInterface::asBinder(state.client);
3590 if (binder == nullptr) {
3591 return true;
3592 }
3593
3594 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3595 return true;
3596 }
3597 }
3598 return false;
3599}
3600
Marissa Wall17b4e452018-12-26 16:32:34 -08003601bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3602 const Vector<ComposerState>& states) {
3603 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3604 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3605 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3606 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3607 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3608 return false;
3609 }
3610
Marissa Wall713b63f2018-10-17 15:42:43 -07003611 for (const ComposerState& state : states) {
3612 const layer_state_t& s = state.state;
3613 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3614 continue;
3615 }
3616 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003617 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 }
3619 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003621}
3622
3623void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3624 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003625 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003626 const InputWindowCommands& inputWindowCommands,
3627 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003628 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003629 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003630
chaviwca27f252018-02-06 16:46:39 -08003631 if (containsAnyInvalidClientState(states)) {
3632 return;
3633 }
3634
Marissa Wall713b63f2018-10-17 15:42:43 -07003635 // If its TransactionQueue already has a pending TransactionState or if it is pending
3636 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003637 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3638 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003639 setTransactionFlags(eTransactionNeeded);
3640 return;
3641 }
3642
chaviw273171b2018-12-26 11:46:30 -08003643 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003644}
3645
3646void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003647 const Vector<DisplayState>& displays, uint32_t flags,
3648 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003649 uint32_t transactionFlags = 0;
3650
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003651 if (flags & eAnimation) {
3652 // For window updates that are part of an animation we must wait for
3653 // previous animation "frames" to be handled.
3654 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003655 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003656 if (CC_UNLIKELY(err != NO_ERROR)) {
3657 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003658 // caller after a few seconds.
3659 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3660 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003661 mAnimTransactionPending = false;
3662 break;
3663 }
3664 }
3665 }
3666
chaviwca27f252018-02-06 16:46:39 -08003667 for (const DisplayState& display : displays) {
3668 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003669 }
3670
Marissa Walle2ffb422018-10-12 11:33:52 -07003671 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003672 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003673 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003674 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003675 // If the state doesn't require a traversal and there are callbacks, send them now
3676 if (!(clientStateFlags & eTraversalNeeded)) {
3677 mTransactionCompletedThread.sendCallbacks();
3678 }
3679 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003680
chaviw273171b2018-12-26 11:46:30 -08003681 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3682
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003683 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3684 // anyway. This can be used as a flush mechanism for previous async transactions.
3685 // Empty animation transaction can be used to simulate back-pressure, so also force a
3686 // transaction for empty animation transactions.
3687 if (transactionFlags == 0 &&
3688 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003689 transactionFlags = eTransactionNeeded;
3690 }
3691
Mathias Agopian386aa982011-11-07 21:58:03 -08003692 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003693 if (mInterceptor->isEnabled()) {
3694 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003695 }
Irvel468051e2016-06-13 16:44:44 -07003696
Mathias Agopian386aa982011-11-07 21:58:03 -08003697 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003698 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3699 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003700 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003701
3702 // if this is a synchronous transaction, wait for it to take effect
3703 // before returning.
3704 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003705 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003706 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003707 if (flags & eAnimation) {
3708 mAnimTransactionPending = true;
3709 }
3710 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003711 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3712 if (CC_UNLIKELY(err != NO_ERROR)) {
3713 // just in case something goes wrong in SF, return to the
3714 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003715 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3716 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003717 break;
3718 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 }
3721}
3722
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003723uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3724 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3725 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003726
Mathias Agopiane57f2922012-08-09 16:29:12 -07003727 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003728 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3729
3730 const uint32_t what = s.what;
3731 if (what & DisplayState::eSurfaceChanged) {
3732 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3733 state.surface = s.surface;
3734 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003735 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003736 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003737 if (what & DisplayState::eLayerStackChanged) {
3738 if (state.layerStack != s.layerStack) {
3739 state.layerStack = s.layerStack;
3740 flags |= eDisplayTransactionNeeded;
3741 }
3742 }
3743 if (what & DisplayState::eDisplayProjectionChanged) {
3744 if (state.orientation != s.orientation) {
3745 state.orientation = s.orientation;
3746 flags |= eDisplayTransactionNeeded;
3747 }
3748 if (state.frame != s.frame) {
3749 state.frame = s.frame;
3750 flags |= eDisplayTransactionNeeded;
3751 }
3752 if (state.viewport != s.viewport) {
3753 state.viewport = s.viewport;
3754 flags |= eDisplayTransactionNeeded;
3755 }
3756 }
3757 if (what & DisplayState::eDisplaySizeChanged) {
3758 if (state.width != s.width) {
3759 state.width = s.width;
3760 flags |= eDisplayTransactionNeeded;
3761 }
3762 if (state.height != s.height) {
3763 state.height = s.height;
3764 flags |= eDisplayTransactionNeeded;
3765 }
3766 }
3767
Mathias Agopiane57f2922012-08-09 16:29:12 -07003768 return flags;
3769}
3770
Robert Carrd4ae7f32018-06-07 16:10:57 -07003771bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3772 IPCThreadState* ipc = IPCThreadState::self();
3773 const int pid = ipc->getCallingPid();
3774 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003775 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003776 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003777 return false;
3778 }
3779 return true;
3780}
3781
chaviwca27f252018-02-06 16:46:39 -08003782uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3783 const layer_state_t& s = composerState.state;
3784 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3785
Mathias Agopian13127d82013-03-05 17:47:11 -08003786 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003787 if (layer == nullptr) {
3788 return 0;
3789 }
3790
chaviw8b3871a2017-11-01 17:41:01 -07003791 uint32_t flags = 0;
3792
Garfield Tan8a3083e2018-12-03 13:21:07 -08003793 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003794 bool geometryAppliesWithResize =
3795 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003796
3797 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3798 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003799 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003800 layer->pushPendingState();
3801 }
3802
chaviw8b3871a2017-11-01 17:41:01 -07003803 if (what & layer_state_t::ePositionChanged) {
3804 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3805 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003806 }
chaviw8b3871a2017-11-01 17:41:01 -07003807 }
3808 if (what & layer_state_t::eLayerChanged) {
3809 // NOTE: index needs to be calculated before we update the state
3810 const auto& p = layer->getParent();
3811 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003812 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003813 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003814 mCurrentState.layersSortedByZ.removeAt(idx);
3815 mCurrentState.layersSortedByZ.add(layer);
3816 // we need traversal (state changed)
3817 // AND transaction (list changed)
3818 flags |= eTransactionNeeded|eTraversalNeeded;
3819 }
chaviw8b3871a2017-11-01 17:41:01 -07003820 } else {
3821 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003822 flags |= eTransactionNeeded|eTraversalNeeded;
3823 }
3824 }
chaviw8b3871a2017-11-01 17:41:01 -07003825 }
3826 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003827 // NOTE: index needs to be calculated before we update the state
3828 const auto& p = layer->getParent();
3829 if (p == nullptr) {
3830 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3831 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3832 mCurrentState.layersSortedByZ.removeAt(idx);
3833 mCurrentState.layersSortedByZ.add(layer);
3834 // we need traversal (state changed)
3835 // AND transaction (list changed)
3836 flags |= eTransactionNeeded|eTraversalNeeded;
3837 }
3838 } else {
3839 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3840 flags |= eTransactionNeeded|eTraversalNeeded;
3841 }
chaviw8b3871a2017-11-01 17:41:01 -07003842 }
3843 }
3844 if (what & layer_state_t::eSizeChanged) {
3845 if (layer->setSize(s.w, s.h)) {
3846 flags |= eTraversalNeeded;
3847 }
3848 }
3849 if (what & layer_state_t::eAlphaChanged) {
3850 if (layer->setAlpha(s.alpha))
3851 flags |= eTraversalNeeded;
3852 }
3853 if (what & layer_state_t::eColorChanged) {
3854 if (layer->setColor(s.color))
3855 flags |= eTraversalNeeded;
3856 }
Valerie Haued54efa2019-01-11 20:03:14 -08003857 if (what & layer_state_t::eColorAlphaChanged) {
3858 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eColorDataspaceChanged) {
3861 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3862 }
Peiyong Lind3788632018-09-18 16:01:31 -07003863 if (what & layer_state_t::eColorTransformChanged) {
3864 if (layer->setColorTransform(s.colorTransform)) {
3865 flags |= eTraversalNeeded;
3866 }
3867 }
chaviw8b3871a2017-11-01 17:41:01 -07003868 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003869 // TODO: b/109894387
3870 //
3871 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3872 // rotation. To see the problem observe that if we have a square parent, and a child
3873 // of the same size, then we rotate the child 45 degrees around it's center, the child
3874 // must now be cropped to a non rectangular 8 sided region.
3875 //
3876 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3877 // private API, and the WindowManager only uses rotation in one case, which is on a top
3878 // level layer in which cropping is not an issue.
3879 //
3880 // However given that abuse of rotation matrices could lead to surfaces extending outside
3881 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3882 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3883 // transformations.
3884 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003885 flags |= eTraversalNeeded;
3886 }
3887 if (what & layer_state_t::eTransparentRegionChanged) {
3888 if (layer->setTransparentRegionHint(s.transparentRegion))
3889 flags |= eTraversalNeeded;
3890 }
3891 if (what & layer_state_t::eFlagsChanged) {
3892 if (layer->setFlags(s.flags, s.mask))
3893 flags |= eTraversalNeeded;
3894 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003895 if (what & layer_state_t::eCropChanged_legacy) {
3896 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003897 flags |= eTraversalNeeded;
3898 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003899 if (what & layer_state_t::eCornerRadiusChanged) {
3900 if (layer->setCornerRadius(s.cornerRadius))
3901 flags |= eTraversalNeeded;
3902 }
chaviw8b3871a2017-11-01 17:41:01 -07003903 if (what & layer_state_t::eLayerStackChanged) {
3904 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3905 // We only allow setting layer stacks for top level layers,
3906 // everything else inherits layer stack from its parent.
3907 if (layer->hasParent()) {
3908 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3909 layer->getName().string());
3910 } else if (idx < 0) {
3911 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3912 "that also does not appear in the top level layer list. Something"
3913 " has gone wrong.", layer->getName().string());
3914 } else if (layer->setLayerStack(s.layerStack)) {
3915 mCurrentState.layersSortedByZ.removeAt(idx);
3916 mCurrentState.layersSortedByZ.add(layer);
3917 // we need traversal (state changed)
3918 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003919 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003920 }
3921 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003922 if (what & layer_state_t::eDeferTransaction_legacy) {
3923 if (s.barrierHandle_legacy != nullptr) {
3924 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3925 } else if (s.barrierGbp_legacy != nullptr) {
3926 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003927 if (authenticateSurfaceTextureLocked(gbp)) {
3928 const auto& otherLayer =
3929 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003930 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003931 } else {
3932 ALOGE("Attempt to defer transaction to to an"
3933 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003934 }
3935 }
chaviw8b3871a2017-11-01 17:41:01 -07003936 // We don't trigger a traversal here because if no other state is
3937 // changed, we don't want this to cause any more work
3938 }
3939 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003940 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003941 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003942 if (!hadParent) {
3943 mCurrentState.layersSortedByZ.remove(layer);
3944 }
chaviw8b3871a2017-11-01 17:41:01 -07003945 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003946 }
chaviw8b3871a2017-11-01 17:41:01 -07003947 }
3948 if (what & layer_state_t::eReparentChildren) {
3949 if (layer->reparentChildren(s.reparentHandle)) {
3950 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003951 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003952 }
chaviw8b3871a2017-11-01 17:41:01 -07003953 if (what & layer_state_t::eDetachChildren) {
3954 layer->detachChildren();
3955 }
3956 if (what & layer_state_t::eOverrideScalingModeChanged) {
3957 layer->setOverrideScalingMode(s.overrideScalingMode);
3958 // We don't trigger a traversal here because if no other state is
3959 // changed, we don't want this to cause any more work
3960 }
Marissa Wall61c58622018-07-18 10:12:20 -07003961 if (what & layer_state_t::eTransformChanged) {
3962 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3963 }
3964 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3965 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3966 flags |= eTraversalNeeded;
3967 }
3968 if (what & layer_state_t::eCropChanged) {
3969 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3970 }
Marissa Wall861616d2018-10-22 12:52:23 -07003971 if (what & layer_state_t::eFrameChanged) {
3972 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3973 }
Marissa Wall61c58622018-07-18 10:12:20 -07003974 if (what & layer_state_t::eBufferChanged) {
3975 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3976 }
3977 if (what & layer_state_t::eAcquireFenceChanged) {
3978 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eDataspaceChanged) {
3981 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eHdrMetadataChanged) {
3984 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3987 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3988 }
3989 if (what & layer_state_t::eApiChanged) {
3990 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3991 }
3992 if (what & layer_state_t::eSidebandStreamChanged) {
3993 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3994 }
Robert Carr720e5062018-07-30 17:45:14 -07003995 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003996 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3997 layer->setInputInfo(s.inputInfo);
3998 flags |= eTraversalNeeded;
3999 } else {
4000 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4001 }
Robert Carr720e5062018-07-30 17:45:14 -07004002 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004003 if (what & layer_state_t::eMetadataChanged) {
4004 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4005 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004006 std::vector<sp<CallbackHandle>> callbackHandles;
4007 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4008 mTransactionCompletedThread.run();
4009 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4010 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4011 }
4012 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004013 if (what & layer_state_t::eCachedBufferChanged) {
4014 sp<GraphicBuffer> buffer =
4015 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4016 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4017 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004018 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4019 // Do not put anything that updates layer state or modifies flags after
4020 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004021 return flags;
4022}
4023
chaviw273171b2018-12-26 11:46:30 -08004024uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4025 uint32_t flags = 0;
4026 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4027 flags |= eTraversalNeeded;
4028 }
4029
4030 mInputWindowCommands.merge(inputWindowCommands);
4031 return flags;
4032}
4033
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004034status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4035 uint32_t h, PixelFormat format, uint32_t flags,
4036 LayerMetadata metadata, sp<IBinder>* handle,
4037 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004038 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004039 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004040 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004041 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004042 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004043
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 status_t result = NO_ERROR;
4045
4046 sp<Layer> layer;
4047
Cody Northropbc755282017-03-31 12:00:08 -06004048 String8 uniqueName = getUniqueLayerName(name);
4049
Mathias Agopian3165cc22012-08-08 19:42:09 -07004050 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004051 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004052 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4053 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004054
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004056 case ISurfaceComposerClient::eFXSurfaceBufferState:
4057 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4058 break;
chaviw13fdc492017-06-27 12:40:18 -07004059 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004060 // check if buffer size is set for color layer.
4061 if (w > 0 || h > 0) {
4062 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4063 int(w), int(h));
4064 return BAD_VALUE;
4065 }
4066
chaviw13fdc492017-06-27 12:40:18 -07004067 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004068 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004069 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004070 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004071 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004072 // check if buffer size is set for container layer.
4073 if (w > 0 || h > 0) {
4074 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4075 int(w), int(h));
4076 return BAD_VALUE;
4077 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004078 result = createContainerLayer(client,
4079 uniqueName, w, h, flags,
4080 handle, &layer);
4081 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004082 default:
4083 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 break;
4085 }
4086
Dan Stoza7d89d062015-04-30 13:29:25 -07004087 if (result != NO_ERROR) {
4088 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004090
Chia-I Wuab0c3192017-08-01 11:29:00 -07004091 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4092 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004093 if (metadata.has(METADATA_WINDOW_TYPE)) {
4094 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4095 if (windowType == 441731) {
4096 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4097 layer->setPrimaryDisplayOnly();
4098 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004099 }
4100
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004101 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004102
Robert Carrb89ea9d2018-12-10 13:01:14 -08004103 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4104 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4105 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004106 if (result != NO_ERROR) {
4107 return result;
4108 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004109 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004110
4111 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004112 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113}
4114
Cody Northropbc755282017-03-31 12:00:08 -06004115String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4116{
4117 bool matchFound = true;
4118 uint32_t dupeCounter = 0;
4119
4120 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4121 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4122
Dan Stoza436ccf32018-06-21 12:10:12 -07004123 // Grab the state lock since we're accessing mCurrentState
4124 Mutex::Autolock lock(mStateLock);
4125
Cody Northropbc755282017-03-31 12:00:08 -06004126 // Loop over layers until we're sure there is no matching name
4127 while (matchFound) {
4128 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004129 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004130 if (layer->getName() == uniqueName) {
4131 matchFound = true;
4132 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4133 }
4134 });
4135 }
4136
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004137 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4138 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004139
4140 return uniqueName;
4141}
4142
Marissa Wallfd668622018-05-10 10:21:13 -07004143status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4144 uint32_t w, uint32_t h, uint32_t flags,
4145 PixelFormat& format, sp<IBinder>* handle,
4146 sp<IGraphicBufferProducer>* gbp,
4147 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004149 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 case PIXEL_FORMAT_TRANSPARENT:
4151 case PIXEL_FORMAT_TRANSLUCENT:
4152 format = PIXEL_FORMAT_RGBA_8888;
4153 break;
4154 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004155 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 break;
4157 }
4158
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004159 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004160 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004161 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004162 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004163 *handle = layer->getHandle();
4164 *gbp = layer->getProducer();
4165 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004166 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004167
Marissa Wallfd668622018-05-10 10:21:13 -07004168 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004169 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004170}
4171
Marissa Wall61c58622018-07-18 10:12:20 -07004172status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4173 uint32_t w, uint32_t h, uint32_t flags,
4174 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004175 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004176 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004177 *handle = layer->getHandle();
4178 *outLayer = layer;
4179
4180 return NO_ERROR;
4181}
4182
chaviw13fdc492017-06-27 12:40:18 -07004183status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004184 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004185 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004187 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004189 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004190}
4191
Robert Carr6b3f6c52018-08-13 13:05:17 -07004192status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4193 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4194 sp<IBinder>* handle, sp<Layer>* outLayer)
4195{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004196 *outLayer =
4197 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004198 *handle = (*outLayer)->getHandle();
4199 return NO_ERROR;
4200}
4201
4202
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004203void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004204 mLayersPendingRemoval.add(layer);
4205 mLayersRemoved = true;
4206 setTransactionFlags(eTransactionNeeded);
4207}
4208
Robert Carr695d5282018-12-18 15:27:58 -08004209void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004210{
Robert Carr2e102c92018-10-23 12:11:15 -07004211 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004212 // If a layer has a parent, we allow it to out-live it's handle
4213 // with the idea that the parent holds a reference and will eventually
4214 // be cleaned up. However no one cleans up the top-level so we do so
4215 // here.
4216 if (layer->getParent() == nullptr) {
4217 mCurrentState.layersSortedByZ.remove(layer);
4218 }
4219 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004220 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004221}
4222
Mathias Agopianb60314a2012-04-10 22:09:54 -07004223// ---------------------------------------------------------------------------
4224
Andy McFadden13a082e2012-08-24 10:16:42 -07004225void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 const auto display = getDefaultDisplayDeviceLocked();
4227 if (!display) return;
4228
4229 const sp<IBinder> token = display->getDisplayToken().promote();
4230 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004231
Jesse Hall01e29052013-02-19 16:13:35 -08004232 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004233 Vector<ComposerState> state;
4234 Vector<DisplayState> displays;
4235 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004236 d.what = DisplayState::eDisplayProjectionChanged |
4237 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004239 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004240 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004241 d.frame.makeInvalid();
4242 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004243 d.width = 0;
4244 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004245 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004246 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004247
Dominik Laskowskie9774092018-12-11 10:04:24 -08004248 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004249
Dominik Laskowski83b88212018-12-11 13:34:06 -08004250 const nsecs_t vsyncPeriod = getVsyncPeriod();
4251 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004252
Brian Andersond0010582017-03-07 13:20:31 -08004253 // Use phase of 0 since phase is not known.
4254 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004256 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004257}
4258
4259void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004260 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004261 postMessageAsync(
4262 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004263}
4264
Dominik Laskowskie9774092018-12-11 10:04:24 -08004265void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004266 if (display->isVirtual()) {
4267 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004268 return;
4269 }
4270
Dominik Laskowski075d3172018-05-24 15:50:06 -07004271 const auto displayId = display->getId();
4272 LOG_ALWAYS_FATAL_IF(!displayId);
4273
Dominik Laskowski34157762018-10-31 13:07:19 -07004274 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275
4276 int currentMode = display->getPowerMode();
4277 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004278 return;
4279 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 display->setPowerMode(mode);
4282
Lloyd Pique4dccc412018-01-22 17:21:36 -08004283 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004285 }
4286
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004287 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004288 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004289 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004291 if (mUseScheduler) {
4292 mScheduler->onScreenAcquired(mAppConnectionHandle);
4293 } else {
4294 mEventThread->onScreenAcquired();
4295 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004296 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004299 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004300 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004301 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004302
4303 struct sched_param param = {0};
4304 param.sched_priority = 1;
4305 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4306 ALOGW("Couldn't set SCHED_FIFO on display on");
4307 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004308 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004309 // Turn off the display
4310 struct sched_param param = {0};
4311 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4312 ALOGW("Couldn't set SCHED_OTHER on display off");
4313 }
4314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004316 if (mUseScheduler) {
4317 mScheduler->disableHardwareVsync(true);
4318 } else {
4319 disableHardwareVsync(true); // also cancels any in-progress resync
4320 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004321 if (mUseScheduler) {
4322 mScheduler->onScreenReleased(mAppConnectionHandle);
4323 } else {
4324 mEventThread->onScreenReleased();
4325 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004326 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004327
Dominik Laskowski075d3172018-05-24 15:50:06 -07004328 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004329 mVisibleRegionsDirty = true;
4330 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004331 } else if (mode == HWC_POWER_MODE_DOZE ||
4332 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004333 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004334 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004335 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004336 if (mUseScheduler) {
4337 mScheduler->onScreenAcquired(mAppConnectionHandle);
4338 } else {
4339 mEventThread->onScreenAcquired();
4340 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004341 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004342 }
4343 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4344 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004346 if (mUseScheduler) {
4347 mScheduler->disableHardwareVsync(true);
4348 } else {
4349 disableHardwareVsync(true); // also cancels any in-progress resync
4350 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004351 if (mUseScheduler) {
4352 mScheduler->onScreenReleased(mAppConnectionHandle);
4353 } else {
4354 mEventThread->onScreenReleased();
4355 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004356 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004357 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004358 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004359 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004360 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004361 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004363 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004364 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004365 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004366 // Update refresh rate stats.
4367 mRefreshRateStats->setPowerMode(mode);
4368 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004369 }
4370
Dominik Laskowski34157762018-10-31 13:07:19 -07004371 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004372}
4373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004375 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004376 const auto display = getDisplayDevice(displayToken);
4377 if (!display) {
4378 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4379 displayToken.get());
4380 } else if (display->isVirtual()) {
4381 ALOGW("Attempt to set power mode %d for virtual display", mode);
4382 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004383 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004384 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004386}
4387
4388// ---------------------------------------------------------------------------
4389
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4391 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004392 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004393
Mathias Agopianbd115332013-04-18 16:41:04 -07004394 IPCThreadState* ipc = IPCThreadState::self();
4395 const int pid = ipc->getCallingPid();
4396 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004397
Mathias Agopianbd115332013-04-18 16:41:04 -07004398 if ((uid != AID_SHELL) &&
4399 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004400 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4401 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004403 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004404 // (this would indicate SF is stuck, but we want to be able to
4405 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004406 status_t err = mStateLock.timedLock(s2ns(1));
4407 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004408 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result,
4410 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4411 "(no locks held)\n",
4412 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004413 }
4414
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417 static const std::unordered_map<std::string, Dumper> dumpers = {
4418 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4419 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4420 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4421 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4422 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4423 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4424 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4425 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4426 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4427 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4428 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4429 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4430 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004431 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004432 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4433 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004434
Dominik Laskowskic2867142019-01-21 11:33:38 -08004435 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4438 (it->second)(args, asProto, result);
4439 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004440 if (asProto) {
4441 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4442 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4443 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004445 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004446 }
4447
Mathias Agopian9795c422009-08-26 16:36:26 -07004448 if (locked) {
4449 mStateLock.unlock();
4450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004451 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
4454}
4455
Dominik Laskowskic2867142019-01-21 11:33:38 -08004456void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004457 mCurrentState.traverseInZOrder(
4458 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004459}
4460
Dominik Laskowskic2867142019-01-21 11:33:38 -08004461void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004462 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463
Dominik Laskowskic2867142019-01-21 11:33:38 -08004464 if (args.size() > 1) {
4465 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004466 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004467 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004468 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004469 }
Robert Carr2047fae2016-11-28 14:09:09 -08004470 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 } else {
4472 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004473 }
4474}
4475
Dominik Laskowskic2867142019-01-21 11:33:38 -08004476void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004477 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004478 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004479 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004480 }
Robert Carr2047fae2016-11-28 14:09:09 -08004481 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004482
Svetoslavd85084b2014-03-20 10:28:31 -07004483 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004484}
4485
Dominik Laskowskic2867142019-01-21 11:33:38 -08004486void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4487 mTimeStats->parseArgs(asProto, args, result);
4488}
4489
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490// This should only be called from the main thread. Otherwise it would need
4491// the lock and should use mCurrentState rather than mDrawingState.
4492void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004493 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004494 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004495 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004496
4497 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004501 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004502
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004503 if (isLayerTripleBufferingDisabled())
4504 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004505
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4507 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4508 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4509 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4510 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4511 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004512 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004513}
4514
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004515void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004516 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004517 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004518 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004519 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004520
4521 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4522
4523 if (mUseScheduler) {
4524 mScheduler->dump(mAppConnectionHandle, result);
4525 } else {
4526 mEventThread->dump(result);
4527 }
4528}
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4531 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004532 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4533 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004534 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004535 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004537 }
David Sodman4a36e932017-11-07 14:29:47 -08004538 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004539 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004540 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4542 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004543}
4544
Dan Stozae77c7662016-05-13 11:37:28 -07004545void SurfaceFlinger::recordBufferingStats(const char* layerName,
4546 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004547 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4548 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004549 for (const auto& segment : history) {
4550 if (!segment.usedThirdBuffer) {
4551 stats.twoBufferTime += segment.totalTime;
4552 }
4553 if (segment.occupancyAverage < 1.0f) {
4554 stats.doubleBufferedTime += segment.totalTime;
4555 } else if (segment.occupancyAverage < 2.0f) {
4556 stats.tripleBufferedTime += segment.totalTime;
4557 }
4558 ++stats.numSegments;
4559 stats.totalTime += segment.totalTime;
4560 }
4561}
4562
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4564 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004565
4566 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4567 const size_t count = currentLayers.size();
4568 for (size_t i=0 ; i<count ; i++) {
4569 currentLayers[i]->dumpFrameEvents(result);
4570 }
4571}
4572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004574 result.append("Buffering stats:\n");
4575 result.append(" [Layer name] <Active time> <Two buffer> "
4576 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004577 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004578 typedef std::tuple<std::string, float, float, float> BufferTuple;
4579 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004580 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004581 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004582 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004583 if (stats.numSegments == 0) {
4584 continue;
4585 }
4586 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4587 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4588 stats.totalTime;
4589 float doubleBufferRatio = static_cast<float>(
4590 stats.doubleBufferedTime) / stats.totalTime;
4591 float tripleBufferRatio = static_cast<float>(
4592 stats.tripleBufferedTime) / stats.totalTime;
4593 sorted.insert({activeTime, {name, twoBufferRatio,
4594 doubleBufferRatio, tripleBufferRatio}});
4595 }
4596 for (const auto& sortedPair : sorted) {
4597 float activeTime = sortedPair.first;
4598 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4600 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004601 }
4602 result.append("\n");
4603}
4604
Yiwei Zhang5434a782018-12-05 18:06:32 -08004605void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004606 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004607 const auto displayId = display->getId();
4608 if (!displayId) {
4609 continue;
4610 }
4611 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004612 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004613 continue;
4614 }
4615
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result,
4617 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4618 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 uint8_t port;
4620 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004621 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004622 result.append("no identification data\n");
4623 continue;
4624 }
4625
4626 if (!isEdid(data)) {
4627 result.append("unknown identification data: ");
4628 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 }
4631 result.append("\n");
4632 continue;
4633 }
4634
4635 const auto edid = parseEdid(data);
4636 if (!edid) {
4637 result.append("invalid EDID: ");
4638 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 }
4641 result.append("\n");
4642 continue;
4643 }
4644
Yiwei Zhang5434a782018-12-05 18:06:32 -08004645 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004646 result.append(edid->displayName.data(), edid->displayName.length());
4647 result.append("\"\n");
4648 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649}
4650
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4652 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4653 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4654 StringAppendF(&result, "DisplayColorSetting: %s\n",
4655 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004656
4657 // TODO: print out if wide-color mode is active or not
4658
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004659 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004660 const auto displayId = display->getId();
4661 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004662 continue;
4663 }
4664
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004666 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004667 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004669 }
4670
Lloyd Pique32cbe282018-10-19 13:09:22 -07004671 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, " Current color mode: %s (%d)\n",
4673 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004674 }
4675 result.append("\n");
4676}
4677
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004679 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004680 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4681 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004682 continue;
4683 }
4684
Dominik Laskowski05275f12018-11-01 15:03:24 -07004685 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004686 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4687 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004688 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 compositionInfo.dump(result, nullptr);
4690 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004691 }
4692 }
David Sodman7e4ae112018-02-09 15:02:28 -08004693}
4694
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004695LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004696 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004697 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4698 const State& state = useDrawing ? mDrawingState : mCurrentState;
4699 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004700 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004701 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004702 });
4703
4704 return layersProto;
4705}
4706
Lloyd Pique32cbe282018-10-19 13:09:22 -07004707LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004708 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004709
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004710 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004711 resolution->set_w(displayDevice.getWidth());
4712 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004713
Lloyd Pique32cbe282018-10-19 13:09:22 -07004714 auto display = displayDevice.getCompositionDisplay();
4715 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004716
Lloyd Pique32cbe282018-10-19 13:09:22 -07004717 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4718 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4719 layersProto.set_global_transform(displayState.orientation);
4720
4721 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004722 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004723 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004724 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004725 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004726 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004727 }
4728 });
4729
4730 return layersProto;
4731}
4732
Dominik Laskowskic2867142019-01-21 11:33:38 -08004733void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4734 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004735 Colorizer colorizer(colorize);
4736
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737 // figure out if we're stuck somewhere
4738 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004740 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4741
4742 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004743 * Dump library configuration.
4744 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745
4746 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004747 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004749 appendSfConfigString(result);
4750 appendUiConfigString(result);
4751 appendGuiConfigString(result);
4752 result.append("\n");
4753
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004754 result.append("\nDisplay identification data:\n");
4755 dumpDisplayIdentificationData(result);
4756
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004757 result.append("\nWide-Color information:\n");
4758 dumpWideColorInfo(result);
4759
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004760 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004761 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004762 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004763 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004764 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004765
Andy McFadden41d67d72014-04-25 16:58:34 -07004766 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004767 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004768 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004769 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004770 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004771
Dan Stozab90cf072015-03-05 11:05:59 -08004772 dumpStaticScreenStats(result);
4773 result.append("\n");
4774
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004776
Dan Stozae77c7662016-05-13 11:37:28 -07004777 dumpBufferingStats(result);
4778
Andy McFadden4803b742012-09-24 19:07:20 -07004779 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780 * Dump the visible layer list
4781 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004782 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4784 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4785 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004786 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004787
Chia-I Wu2f884132018-09-13 15:17:58 -07004788 {
4789 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4790 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004791 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004792 result.append("\n");
4793 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794
David Sodman7e4ae112018-02-09 15:02:28 -08004795 result.append("\nFrame-Composition information:\n");
4796 dumpFrameCompositionInfo(result);
4797 result.append("\n");
4798
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004800 * Dump Display state
4801 */
4802
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004806 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004807 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004808 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004809 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004810
4811 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004812 * Dump SurfaceFlinger global state
4813 */
4814
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004815 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004816 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004818
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004819 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
Dominik Laskowski075d3172018-05-24 15:50:06 -07004821 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004822 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4823 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004824 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4825 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004826 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result,
4828 " transaction-flags : %08x\n"
4829 " gpu_to_cpu_unsupported : %d\n",
4830 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004831
Dominik Laskowski075d3172018-05-24 15:50:06 -07004832 if (const auto displayId = getInternalDisplayId();
4833 displayId && getHwComposer().isConnected(*displayId)) {
4834 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004835 StringAppendF(&result,
4836 " refresh-rate : %f fps\n"
4837 " x-dpi : %f\n"
4838 " y-dpi : %f\n",
4839 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4840 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004842
Yiwei Zhang5434a782018-12-05 18:06:32 -08004843 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004844
Dan Stozae22aec72016-08-01 13:20:59 -07004845 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004846 * Tracing state
4847 */
4848 mTracing.dump(result);
4849 result.append("\n");
4850
4851 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004852 * HWC layer minidump
4853 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004854 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004855 const auto displayId = display->getId();
4856 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004857 continue;
4858 }
4859
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004861 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004862 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004863 result.append("\n");
4864 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004865
4866 /*
4867 * Dump HWComposer state
4868 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004870 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004871 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004872 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004873 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004875
4876 /*
4877 * Dump gralloc state
4878 */
4879 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4880 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004881
4882 /*
4883 * Dump VrFlinger state if in use.
4884 */
4885 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4886 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004888 result.append("\n");
4889 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004890
4891 /**
4892 * Scheduler dump state.
4893 */
4894 if (mUseScheduler) {
4895 result.append("\nScheduler state:\n");
4896 result.append(mScheduler->doDump() + "\n");
4897 result.append(mRefreshRateStats->doDump() + "\n");
4898 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004899}
4900
Dominik Laskowski075d3172018-05-24 15:50:06 -07004901const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004902 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004903 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004904 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004905 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004906 }
4907 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004908
Dominik Laskowski34157762018-10-31 13:07:19 -07004909 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004910 static const Vector<sp<Layer>> empty;
4911 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004912}
4913
Keun young Park63f165f2012-08-31 10:53:36 -07004914bool SurfaceFlinger::startDdmConnection()
4915{
4916 void* libddmconnection_dso =
4917 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4918 if (!libddmconnection_dso) {
4919 return false;
4920 }
4921 void (*DdmConnection_start)(const char* name);
4922 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004923 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004924 if (!DdmConnection_start) {
4925 dlclose(libddmconnection_dso);
4926 return false;
4927 }
4928 (*DdmConnection_start)(getServiceName());
4929 return true;
4930}
4931
Chia-I Wu28f320b2018-05-03 11:02:56 -07004932void SurfaceFlinger::updateColorMatrixLocked() {
4933 mat4 colorMatrix;
4934 if (mGlobalSaturationFactor != 1.0f) {
4935 // Rec.709 luma coefficients
4936 float3 luminance{0.213f, 0.715f, 0.072f};
4937 luminance *= 1.0f - mGlobalSaturationFactor;
4938 mat4 saturationMatrix = mat4(
4939 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4940 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4941 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4942 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4943 );
4944 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4945 } else {
4946 colorMatrix = mClientColorMatrix * mDaltonizer();
4947 }
4948
4949 if (mCurrentState.colorMatrix != colorMatrix) {
4950 mCurrentState.colorMatrix = colorMatrix;
4951 mCurrentState.colorMatrixChanged = true;
4952 setTransactionFlags(eTransactionNeeded);
4953 }
4954}
4955
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004956status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957#pragma clang diagnostic push
4958#pragma clang diagnostic error "-Wswitch-enum"
4959 switch (static_cast<ISurfaceComposerTag>(code)) {
4960 // These methods should at minimum make sure that the client requested
4961 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004962 case BOOT_FINISHED:
4963 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964 case CREATE_DISPLAY:
4965 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004966 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 case GET_ACTIVE_COLOR_MODE:
4968 case GET_ANIMATION_FRAME_STATS:
4969 case GET_HDR_CAPABILITIES:
4970 case SET_ACTIVE_CONFIG:
4971 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004972 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004973 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004974 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004975 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4976 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004977 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4978 IPCThreadState* ipc = IPCThreadState::self();
4979 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4980 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004981 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
Robert Carr1db73f62016-12-21 12:58:51 -08004983 return OK;
4984 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004985 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004986 IPCThreadState* ipc = IPCThreadState::self();
4987 const int pid = ipc->getCallingPid();
4988 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004989 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4990 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004991 return PERMISSION_DENIED;
4992 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004993 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004995 // Used by apps to hook Choreographer to SurfaceFlinger.
4996 case CREATE_DISPLAY_EVENT_CONNECTION:
4997 // The following calls are currently used by clients that do not
4998 // request necessary permissions. However, they do not expose any secret
4999 // information, so it is OK to pass them.
5000 case AUTHENTICATE_SURFACE:
5001 case GET_ACTIVE_CONFIG:
5002 case GET_BUILT_IN_DISPLAY:
5003 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005004 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005005 case GET_DISPLAY_CONFIGS:
5006 case GET_DISPLAY_STATS:
5007 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5008 // Calling setTransactionState is safe, because you need to have been
5009 // granted a reference to Client* and Handle* to do anything with it.
5010 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005011 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005012 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005013 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005014 case GET_PROTECTED_CONTENT_SUPPORT:
5015 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005016 case UNCACHE_BUFFER:
5017 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005018 return OK;
5019 }
5020 case CAPTURE_LAYERS:
5021 case CAPTURE_SCREEN: {
5022 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005023 IPCThreadState* ipc = IPCThreadState::self();
5024 const int pid = ipc->getCallingPid();
5025 const int uid = ipc->getCallingUid();
5026 if ((uid != AID_GRAPHICS) &&
5027 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5028 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5029 return PERMISSION_DENIED;
5030 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005031 return OK;
5032 }
5033 // The following codes are deprecated and should never be allowed to access SF.
5034 case CONNECT_DISPLAY_UNUSED:
5035 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5036 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5037 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005040
5041 // These codes are used for the IBinder protocol to either interrogate the recipient
5042 // side of the transaction for its canonical interface descriptor or to dump its state.
5043 // We let them pass by default.
5044 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5045 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5046 code == IBinder::SYSPROPS_TRANSACTION) {
5047 return OK;
5048 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005049 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005051 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5053 return OK;
5054 }
5055 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5056 return PERMISSION_DENIED;
5057#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005058}
5059
Ana Krulec13be8ad2018-08-21 02:43:56 +00005060status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5061 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005062 status_t credentialCheck = CheckTransactCodeCredentials(code);
5063 if (credentialCheck != OK) {
5064 return credentialCheck;
5065 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005067 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5068 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005069 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005070 IPCThreadState* ipc = IPCThreadState::self();
5071 const int uid = ipc->getCallingUid();
5072 if (CC_UNLIKELY(uid != AID_SYSTEM
5073 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005074 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005075 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005076 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005077 return PERMISSION_DENIED;
5078 }
5079 int n;
5080 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005081 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005082 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005083 return NO_ERROR;
5084 case 1002: // SHOW_UPDATES
5085 n = data.readInt32();
5086 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005087 invalidateHwcGeometry();
5088 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005089 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005091 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005092 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005094 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005095 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005096 setTransactionFlags(
5097 eTransactionNeeded|
5098 eDisplayTransactionNeeded|
5099 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005100 return NO_ERROR;
5101 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005102 case 1006:{ // send empty update
5103 signalRefresh();
5104 return NO_ERROR;
5105 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005106 case 1008: // toggle use of hw composer
5107 n = data.readInt32();
5108 mDebugDisableHWC = n ? 1 : 0;
5109 invalidateHwcGeometry();
5110 repaintEverything();
5111 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005112 case 1009: // toggle use of transform hint
5113 n = data.readInt32();
5114 mDebugDisableTransformHint = n ? 1 : 0;
5115 invalidateHwcGeometry();
5116 repaintEverything();
5117 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005119 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 reply->writeInt32(0);
5121 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005122 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005123 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005124 return NO_ERROR;
5125 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005126 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005127 if (!display) {
5128 return NAME_NOT_FOUND;
5129 }
5130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005131 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005132 return NO_ERROR;
5133 }
5134 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005135 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005136 // daltonize
5137 n = data.readInt32();
5138 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005139 case 1:
5140 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5141 break;
5142 case 2:
5143 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5144 break;
5145 case 3:
5146 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5147 break;
5148 default:
5149 mDaltonizer.setType(ColorBlindnessType::None);
5150 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005151 }
5152 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005153 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005154 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005155 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005156 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005157
5158 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005159 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005160 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005161 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005162 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005163 // apply a color matrix
5164 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005165 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005166 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005167 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005168 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005170 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005173 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005174 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005175
5176 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5177 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005178 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005179 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5180 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5181 }
5182
Chia-I Wu28f320b2018-05-03 11:02:56 -07005183 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005184 return NO_ERROR;
5185 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005186 // This is an experimental interface
5187 // Needs to be shifted to proper binder interface when we productize
5188 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005189 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005190 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005191 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005192 return NO_ERROR;
5193 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005194 case 1017: {
5195 n = data.readInt32();
5196 mForceFullDamage = static_cast<bool>(n);
5197 return NO_ERROR;
5198 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005199 case 1018: { // Modify Choreographer's phase offset
5200 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005201 if (mUseScheduler) {
5202 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5203 } else {
5204 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5205 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005206 return NO_ERROR;
5207 }
5208 case 1019: { // Modify SurfaceFlinger's phase offset
5209 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005210 if (mUseScheduler) {
5211 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5212 } else {
5213 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5214 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005215 return NO_ERROR;
5216 }
Irvel468051e2016-06-13 16:44:44 -07005217 case 1020: { // Layer updates interceptor
5218 n = data.readInt32();
5219 if (n) {
5220 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005221 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005222 }
5223 else{
5224 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005225 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005226 }
5227 return NO_ERROR;
5228 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005229 case 1021: { // Disable HWC virtual displays
5230 n = data.readInt32();
5231 mUseHwcVirtualDisplays = !n;
5232 return NO_ERROR;
5233 }
Romain Guy0147a172017-06-01 13:53:56 -07005234 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005235 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005236 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005237
Chia-I Wu28f320b2018-05-03 11:02:56 -07005238 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005239 return NO_ERROR;
5240 }
Romain Guy54f154a2017-10-24 21:40:32 +01005241 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005242 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005243 invalidateHwcGeometry();
5244 repaintEverything();
5245 return NO_ERROR;
5246 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005247 // Deprecate, use 1030 to check whether the device is color managed.
5248 case 1024: {
5249 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005250 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005251 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005252 n = data.readInt32();
5253 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005254 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005255 mTracing.enable();
5256 doTracing("tracing.enable");
5257 reply->writeInt32(NO_ERROR);
5258 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005259 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005260 status_t err = mTracing.disable();
5261 reply->writeInt32(err);
5262 }
5263 return NO_ERROR;
5264 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005265 case 1026: { // Get layer tracing status
5266 reply->writeBool(mTracing.isEnabled());
5267 return NO_ERROR;
5268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005269 // Is a DisplayColorSetting supported?
5270 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005271 const auto display = getDefaultDisplayDevice();
5272 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005273 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005274 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005275
5276 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5277 switch (setting) {
5278 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005279 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005280 break;
5281 case DisplayColorSetting::UNMANAGED:
5282 reply->writeBool(true);
5283 break;
5284 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005285 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005286 break;
5287 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005288 reply->writeBool(
5289 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 break;
5291 }
5292 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005293 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005294 // Is VrFlinger active?
5295 case 1028: {
5296 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005297 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005298 return NO_ERROR;
5299 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005300 // Is device color managed?
5301 case 1030: {
5302 reply->writeBool(useColorManagement);
5303 return NO_ERROR;
5304 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005305 // Override default composition data space
5306 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5307 // && adb shell stop zygote && adb shell start zygote
5308 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5309 // adb shell stop zygote && adb shell start zygote
5310 case 1031: {
5311 Mutex::Autolock _l(mStateLock);
5312 n = data.readInt32();
5313 if (n) {
5314 n = data.readInt32();
5315 if (n) {
5316 Dataspace dataspace = static_cast<Dataspace>(n);
5317 if (!validateCompositionDataspace(dataspace)) {
5318 return BAD_VALUE;
5319 }
5320 mDefaultCompositionDataspace = dataspace;
5321 }
5322 n = data.readInt32();
5323 if (n) {
5324 Dataspace dataspace = static_cast<Dataspace>(n);
5325 if (!validateCompositionDataspace(dataspace)) {
5326 return BAD_VALUE;
5327 }
5328 mWideColorGamutCompositionDataspace = dataspace;
5329 }
5330 } else {
5331 // restore composition data space.
5332 mDefaultCompositionDataspace = defaultCompositionDataspace;
5333 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5334 }
5335 return NO_ERROR;
5336 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005337 }
5338 }
5339 return err;
5340}
5341
Steven Thomas6d8110b2017-08-31 18:24:21 -07005342void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005343 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005344 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005345}
5346
Ana Krulec7d1d6832018-12-27 11:10:09 -08005347void SurfaceFlinger::repaintEverythingForHWC() {
5348 mRepaintEverything = true;
5349 mEventQueue->invalidateForHWC();
5350}
5351
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005352// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5353class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005354public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5356 ~WindowDisconnector() {
5357 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005358 }
5359
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360private:
5361 ANativeWindow* mWindow;
5362 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005363};
5364
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005365status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005366 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5367 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005368 uint32_t reqWidth, uint32_t reqHeight,
5369 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005370 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005371 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005372
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005373 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005374
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005375 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5376
Chia-I Wu20261cb2018-08-23 12:55:44 -07005377 sp<DisplayDevice> display;
5378 {
5379 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005380
Chia-I Wu20261cb2018-08-23 12:55:44 -07005381 display = getDisplayDeviceLocked(displayToken);
5382 if (!display) return BAD_VALUE;
5383
Chia-I Wucb023152018-08-28 12:57:23 -07005384 // set the requested width/height to the logical display viewport size
5385 // by default
5386 if (reqWidth == 0 || reqHeight == 0) {
5387 reqWidth = uint32_t(display->getViewport().width());
5388 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005389 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005390 }
5391
Peiyong Lin0e003c92018-09-17 11:09:51 -07005392 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5393 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005394
5395 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005396 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005397 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5398 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005399}
5400
5401status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005402 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5403 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005404 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005405 ATRACE_CALL();
5406
5407 class LayerRenderArea : public RenderArea {
5408 public:
Robert Carr578038f2018-03-09 12:25:24 -08005409 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005410 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5411 bool childrenOnly)
5412 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005413 mLayer(layer),
5414 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005415 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005416 mFlinger(flinger),
5417 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005418 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005419 Rect getBounds() const override {
5420 const Layer::State& layerState(mLayer->getDrawingState());
5421 return mLayer->getBufferSize(layerState);
5422 }
Marissa Wall61c58622018-07-18 10:12:20 -07005423 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005424 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005425 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005426 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005427 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005428 }
chaviwa76b2712017-09-20 12:02:26 -07005429 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005430 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005431 Rect getSourceCrop() const override {
5432 if (mCrop.isEmpty()) {
5433 return getBounds();
5434 } else {
5435 return mCrop;
5436 }
5437 }
Robert Carr578038f2018-03-09 12:25:24 -08005438 class ReparentForDrawing {
5439 public:
5440 const sp<Layer>& oldParent;
5441 const sp<Layer>& newParent;
5442
5443 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5444 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005445 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005446 }
Robert Carr15eae092018-03-23 13:43:53 -07005447 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005448 };
5449
5450 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005451 const Rect sourceCrop = getSourceCrop();
5452 // no need to check rotation because there is none
5453 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5454 sourceCrop.height() != getReqHeight();
5455
Robert Carr578038f2018-03-09 12:25:24 -08005456 if (!mChildrenOnly) {
5457 mTransform = mLayer->getTransform().inverse();
5458 drawLayers();
5459 } else {
5460 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005461 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005462 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5463 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005464
5465 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5466 drawLayers();
5467 }
5468 }
chaviwa76b2712017-09-20 12:02:26 -07005469
chaviwa76b2712017-09-20 12:02:26 -07005470 private:
chaviw7206d492017-11-10 16:16:12 -08005471 const sp<Layer> mLayer;
5472 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005473
5474 // In the "childrenOnly" case we reparent the children to a screenshot
5475 // layer which has no properties set and which does not draw.
5476 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005477 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005478 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005479
5480 SurfaceFlinger* mFlinger;
5481 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005482 };
5483
5484 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5485 auto parent = layerHandle->owner.promote();
5486
Robert Carr2e102c92018-10-23 12:11:15 -07005487 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005488 ALOGE("captureLayers called with a removed parent");
5489 return NAME_NOT_FOUND;
5490 }
5491
Robert Carr578038f2018-03-09 12:25:24 -08005492 const int uid = IPCThreadState::self()->getCallingUid();
5493 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005494 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005495 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5496 return PERMISSION_DENIED;
5497 }
5498
chaviw7206d492017-11-10 16:16:12 -08005499 Rect crop(sourceCrop);
5500 if (sourceCrop.width() <= 0) {
5501 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005502 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005503 }
5504
5505 if (sourceCrop.height() <= 0) {
5506 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005507 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005508 }
5509
5510 int32_t reqWidth = crop.width() * frameScale;
5511 int32_t reqHeight = crop.height() * frameScale;
5512
Chia-I Wu20261cb2018-08-23 12:55:44 -07005513 // really small crop or frameScale
5514 if (reqWidth <= 0) {
5515 reqWidth = 1;
5516 }
5517 if (reqHeight <= 0) {
5518 reqHeight = 1;
5519 }
5520
Peiyong Lin0e003c92018-09-17 11:09:51 -07005521 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005522
Robert Carr578038f2018-03-09 12:25:24 -08005523 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005524 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5525 if (!layer->isVisible()) {
5526 return;
Robert Carr578038f2018-03-09 12:25:24 -08005527 } else if (childrenOnly && layer == parent.get()) {
5528 return;
chaviwa76b2712017-09-20 12:02:26 -07005529 }
5530 visitor(layer);
5531 });
5532 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005533 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005534}
5535
5536status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5537 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005538 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005539 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005540 bool useIdentityTransform) {
5541 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005542
Peiyong Lin0e003c92018-09-17 11:09:51 -07005543 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005544 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5545 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005546 *outBuffer =
5547 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5548 static_cast<android_pixel_format>(reqPixelFormat), 1,
5549 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005550
5551 // This mutex protects syncFd and captureResult for communication of the return values from the
5552 // main thread back to this Binder thread
5553 std::mutex captureMutex;
5554 std::condition_variable captureCondition;
5555 std::unique_lock<std::mutex> captureLock(captureMutex);
5556 int syncFd = -1;
5557 std::optional<status_t> captureResult;
5558
Robert Carr03480e22018-01-04 16:02:06 -08005559 const int uid = IPCThreadState::self()->getCallingUid();
5560 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5561
Dominik Laskowski8c001672018-05-30 16:52:06 -07005562 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005563 // If there is a refresh pending, bug out early and tell the binder thread to try again
5564 // after the refresh.
5565 if (mRefreshPending) {
5566 ATRACE_NAME("Skipping screenshot for now");
5567 std::unique_lock<std::mutex> captureLock(captureMutex);
5568 captureResult = std::make_optional<status_t>(EAGAIN);
5569 captureCondition.notify_one();
5570 return;
5571 }
5572
5573 status_t result = NO_ERROR;
5574 int fd = -1;
5575 {
5576 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005577 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005578 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5579 useIdentityTransform, forSystem, &fd);
5580 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005581 }
5582
5583 {
5584 std::unique_lock<std::mutex> captureLock(captureMutex);
5585 syncFd = fd;
5586 captureResult = std::make_optional<status_t>(result);
5587 captureCondition.notify_one();
5588 }
5589 });
5590
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005591 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005592 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005593 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 while (*captureResult == EAGAIN) {
5595 captureResult.reset();
5596 result = postMessageAsync(message);
5597 if (result != NO_ERROR) {
5598 return result;
5599 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005600 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 }
5602 result = *captureResult;
5603 }
5604
5605 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005606 sync_wait(syncFd, -1);
5607 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005608 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005609
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005610 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005611}
5612
chaviwa76b2712017-09-20 12:02:26 -07005613void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005614 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005615 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5616 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005618
chaviwa76b2712017-09-20 12:02:26 -07005619 const auto reqWidth = renderArea.getReqWidth();
5620 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005621 const auto sourceCrop = renderArea.getSourceCrop();
5622 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005623
Alec Mouri0f714832018-11-12 15:31:06 -08005624 renderengine::DisplaySettings clientCompositionDisplay;
5625 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005626
Alec Mouri0f714832018-11-12 15:31:06 -08005627 // assume that bounds are never offset, and that they are the same as the
5628 // buffer bounds.
5629 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5630 ui::Transform transform = renderArea.getTransform();
5631 mat4 m;
5632 m[0][0] = transform[0][0];
5633 m[0][1] = transform[0][1];
5634 m[0][3] = transform[0][2];
5635 m[1][0] = transform[1][0];
5636 m[1][1] = transform[1][1];
5637 m[1][3] = transform[1][2];
5638 m[3][0] = transform[2][0];
5639 m[3][1] = transform[2][1];
5640 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005641
Alec Mouri0f714832018-11-12 15:31:06 -08005642 clientCompositionDisplay.globalTransform = m;
5643 mat4 rotMatrix;
5644 // Displacement for repositioning the clipping rectangle after rotating it
5645 // with the rotation hint.
5646 int displacementX = 0;
5647 int displacementY = 0;
5648 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5649 switch (rotation) {
5650 case ui::Transform::ROT_90:
5651 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5652 displacementX = reqWidth;
5653 break;
5654 case ui::Transform::ROT_180:
5655 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5656 displacementX = reqWidth;
5657 displacementY = reqHeight;
5658 break;
5659 case ui::Transform::ROT_270:
5660 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5661 displacementY = reqHeight;
5662 break;
5663 default:
5664 break;
5665 }
5666 // We need to transform the clipping window into the right spot.
5667 // First, rotate the clipping rectangle by the rotation hint to get the
5668 // right orientation
5669 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5670 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5671 const vec4 rotClipTL = rotMatrix * clipTL;
5672 const vec4 rotClipBR = rotMatrix * clipBR;
5673 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5674 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5675 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5676 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5677
5678 // Now reposition the clipping rectangle with the displacement vector
5679 // computed above.
5680 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5681
5682 clientCompositionDisplay.clip =
5683 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5684 newClipRight + displacementX, newClipBottom + displacementY);
5685
5686 // We need to perform the same transformation in layer space, so propagate
5687 // it to the global transform.
5688 mat4 clipTransform = displacementMat * rotMatrix;
5689 clientCompositionDisplay.globalTransform *= clipTransform;
5690 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5691 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005692
chaviw50da5042018-04-09 13:49:37 -07005693 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005694
Alec Mouri0f714832018-11-12 15:31:06 -08005695 renderengine::LayerSettings fillLayer;
5696 fillLayer.source.buffer.buffer = nullptr;
5697 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5698 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5699 fillLayer.alpha = half(alpha);
5700 clientCompositionLayers.push_back(fillLayer);
5701
5702 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005703 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005704 renderengine::LayerSettings layerSettings;
5705 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5706 layerSettings);
5707 if (prepared) {
5708 clientCompositionLayers.push_back(layerSettings);
5709 }
chaviwa76b2712017-09-20 12:02:26 -07005710 });
Alec Mouri0f714832018-11-12 15:31:06 -08005711
5712 clientCompositionDisplay.clearRegion = clearRegion;
5713 base::unique_fd drawFence;
5714 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5715 &drawFence);
5716
5717 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005718}
5719
chaviwa76b2712017-09-20 12:02:26 -07005720status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5721 TraverseLayersFunction traverseLayers,
5722 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005723 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005724 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005725 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005726 ATRACE_CALL();
5727
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005728 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005729
5730 traverseLayers([&](Layer* layer) {
5731 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5732 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005733
Robert Carr03480e22018-01-04 16:02:06 -08005734 // We allow the system server to take screenshots of secure layers for
5735 // use in situations like the Screen-rotation animation and place
5736 // the impetus on WindowManager to not persist them.
5737 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005738 ALOGW("FB is protected: PERMISSION_DENIED");
5739 return PERMISSION_DENIED;
5740 }
Alec Mouri0f714832018-11-12 15:31:06 -08005741 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005742 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005743}
5744
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005745// ---------------------------------------------------------------------------
5746
Dan Stoza412903f2017-04-27 13:42:17 -07005747void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5748 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005749}
5750
Dan Stoza412903f2017-04-27 13:42:17 -07005751void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5752 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005753}
5754
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005755void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005756 const LayerVector::Visitor& visitor) {
5757 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005758 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005759 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005760 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005761 continue;
5762 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005763 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005764 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005765 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005766 return;
5767 }
chaviwa76b2712017-09-20 12:02:26 -07005768 if (!layer->isVisible()) {
5769 return;
5770 }
5771 visitor(layer);
5772 });
5773 }
5774}
5775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005776}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005777
Lloyd Pique074e8122018-07-26 12:57:23 -07005778
Mathias Agopian3f844832013-08-07 21:24:32 -07005779#if defined(__gl_h_)
5780#error "don't include gl/gl.h in this file"
5781#endif
5782
5783#if defined(__gl2_h_)
5784#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005785#endif