blob: 4c1b267397e816c8342a73b1e0a26e7a03313880 [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
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
500 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 const auto internalDisplayId = getInternalDisplayIdLocked();
503 if (!internalDisplayId) {
504 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505 }
506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800507 std::vector<PhysicalDisplayId> displayIds;
508 displayIds.reserve(mPhysicalDisplayTokens.size());
509 displayIds.push_back(internalDisplayId->value);
510
511 for (const auto& [id, token] : mPhysicalDisplayTokens) {
512 if (id != *internalDisplayId) {
513 displayIds.push_back(id.value);
514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700516
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800517 return displayIds;
518}
519
520sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
521 Mutex::Autolock lock(mStateLock);
522 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523}
524
Ady Abraham37965d42018-11-01 13:43:32 -0700525status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
526 if (!outGetColorManagement) {
527 return BAD_VALUE;
528 }
529 *outGetColorManagement = useColorManagement;
530 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700531}
532
Lloyd Pique441d5042018-10-18 16:49:51 -0700533HWComposer& SurfaceFlinger::getHwComposer() const {
534 return mCompositionEngine->getHwComposer();
535}
536
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700537renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
538 return mCompositionEngine->getRenderEngine();
539}
540
Lloyd Pique70d91362018-10-18 16:02:55 -0700541compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
542 return *mCompositionEngine.get();
543}
544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545void SurfaceFlinger::bootFinished()
546{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700547 if (mStartPropertySetThread->join() != NO_ERROR) {
548 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550 const nsecs_t now = systemTime();
551 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000552 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553
554 // wait patiently for the window manager death
555 const String16 name("window");
556 sp<IBinder> window(defaultServiceManager()->getService(name));
557 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700558 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 }
Robert Carr720e5062018-07-30 17:45:14 -0700560 sp<IBinder> input(defaultServiceManager()->getService(
561 String16("inputflinger")));
562 if (input == nullptr) {
563 ALOGE("Failed to link to input service");
564 } else {
565 mInputFlinger = interface_cast<IInputFlinger>(input);
566 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567
Steven Thomas050b2c82017-03-06 11:45:16 -0800568 if (mVrFlinger) {
569 mVrFlinger->OnBootFinished();
570 }
571
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700573 // formerly we would just kill the process, but we now ask it to exit so it
574 // can choose where to stop the animation.
575 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700576
577 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
578 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
579 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700580
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 postMessageAsync(new LambdaMessage([this] {
582 readPersistentProperties();
583 mBootStage = BootStage::FINISHED;
584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
617
Ana Krulec757f63a2019-01-25 10:46:18 -0800618 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621
Dominik Laskowski83b88212018-12-11 13:34:06 -0800622 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800626 mScheduler = getFactory().createScheduler(
627 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
628
Ana Krulec757f63a2019-01-25 10:46:18 -0800629 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
630 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
631 mPhaseOffsets->setRefreshRateType(
632 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700633
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800635 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800636 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 impl::EventThread::InterceptVSyncsCallback());
638 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800640 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 mInterceptor->saveVSyncEvent(timestamp);
642 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800643
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700645 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
646 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 } else {
648 mEventThreadSource =
649 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800650 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 mEventThread =
652 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 impl::EventThread::InterceptVSyncsCallback(),
654 "appEventThread");
655 mSfEventThreadSource =
656 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800657 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700658
659 mSFEventThread =
660 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700661 [this](nsecs_t timestamp) {
662 mInterceptor->saveVSyncEvent(timestamp);
663 },
664 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800665 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700666 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668
Steven Thomasb02664d2017-07-26 18:48:28 -0700669 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700670 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700671 renderEngineFeature |= (useColorManagement ?
672 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700673 renderEngineFeature |= (useContextPriority ?
674 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700675
676 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700677 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700678 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700679 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700680
681 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
682 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700683 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
684 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700706 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
707 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700709 .value_or(0),
710 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 if (!mVrFlinger) {
712 ALOGE("Failed to start vrflinger");
713 }
714 }
715
Lloyd Pique90c115d2018-09-18 21:39:42 -0700716 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800717 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700718
Mathias Agopian92a979a2012-08-02 18:32:23 -0700719 // initialize our drawing state
720 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700721
Andy McFadden13a082e2012-08-24 10:16:42 -0700722 // set initial conditions (e.g. unblank default device)
723 initializeDisplays();
724
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700725 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700726
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700728
729 const bool presentFenceReliable =
730 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
731 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Ana Krulec7d1d6832018-12-27 11:10:09 -0800737 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800738 mScheduler->setExpiredIdleTimerCallback([this]() {
739 mPhaseOffsets->setRefreshRateType(
740 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
741 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
742 mVsyncModulator.setPhaseOffsets(early, gl, late);
743 setRefreshRateTo(60.f /* fps */);
744 });
745 mScheduler->setResetIdleTimerCallback([this]() {
746 mPhaseOffsets->setRefreshRateType(
747 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
748 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
749 mVsyncModulator.setPhaseOffsets(early, gl, late);
750 setRefreshRateTo(90.f /* fps */);
751 });
Ana Krulecb43429d2019-01-09 14:28:51 -0800752 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
753 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800754 }
755
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700757}
758
Romain Guy11d63f42017-07-20 12:47:14 -0700759void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700760 Mutex::Autolock _l(mStateLock);
761
Romain Guy11d63f42017-07-20 12:47:14 -0700762 char value[PROPERTY_VALUE_MAX];
763
764 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800765 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700766 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800767 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100768
769 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700770 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700771}
772
Mathias Agopiana67e4182012-06-19 17:26:12 -0700773void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800774 // Start boot animation service by setting a property mailbox
775 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700778 if (mStartPropertySetThread->join() != NO_ERROR) {
779 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800780 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800792
Jamie Gennis582270d2011-08-17 18:19:00 -0700793bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800794 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800795 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800796 return authenticateSurfaceTextureLocked(bufferProducer);
797}
798
799bool SurfaceFlinger::authenticateSurfaceTextureLocked(
800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800801 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800802 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800803}
804
Brian Anderson6b376712017-04-04 10:51:39 -0700805status_t SurfaceFlinger::getSupportedFrameTimestamps(
806 std::vector<FrameEvent>* outSupported) const {
807 *outSupported = {
808 FrameEvent::REQUESTED_PRESENT,
809 FrameEvent::ACQUIRE,
810 FrameEvent::LATCH,
811 FrameEvent::FIRST_REFRESH_START,
812 FrameEvent::LAST_REFRESH_START,
813 FrameEvent::GPU_COMPOSITION_DONE,
814 FrameEvent::DEQUEUE_READY,
815 FrameEvent::RELEASE,
816 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700817 ConditionalLock _l(mStateLock,
818 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700819 if (!getHwComposer().hasCapability(
820 HWC2::Capability::PresentFenceIsNotReliable)) {
821 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
822 }
823 return NO_ERROR;
824}
825
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700826status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
827 Vector<DisplayInfo>* configs) {
828 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 return BAD_VALUE;
830 }
831
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800832 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
833
834 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700835 if (!displayId) {
836 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700837 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 // TODO: Not sure if display density should handled by SF any longer
840 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700843 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800844 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 }
847 return density;
848 }
849 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700850 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700852 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853 return getDensityFromProperty("ro.sf.lcd_density"); }
854 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700857
Dominik Laskowski075d3172018-05-24 15:50:06 -0700858 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 DisplayInfo info = DisplayInfo();
860
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861 float xdpi = hwConfig->getDpiX();
862 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700864 info.w = hwConfig->getWidth();
865 info.h = hwConfig->getHeight();
866 // Default display viewport to display width and height
867 info.viewportW = info.w;
868 info.viewportH = info.h;
869
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800870 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 // The density of the device is provided by a build property
872 float density = Density::getBuildDensity() / 160.0f;
873 if (density == 0) {
874 // the build doesn't provide a density -- this is wrong!
875 // use xdpi instead
876 ALOGE("ro.sf.lcd_density must be defined as a build property");
877 density = xdpi / 160.0f;
878 }
879 if (Density::getEmuDensity()) {
880 // if "qemu.sf.lcd_density" is specified, it overrides everything
881 xdpi = ydpi = density = Density::getEmuDensity();
882 density /= 160.0f;
883 }
884 info.density = density;
885
886 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887 const auto display = getDefaultDisplayDeviceLocked();
888 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700889
890 // This is for screenrecord
891 const Rect viewport = display->getViewport();
892 if (viewport.isValid()) {
893 info.viewportW = uint32_t(viewport.getWidth());
894 info.viewportH = uint32_t(viewport.getHeight());
895 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 } else {
897 // TODO: where should this value come from?
898 static const int TV_DENSITY = 213;
899 info.density = TV_DENSITY / 160.0f;
900 info.orientation = 0;
901 }
902
Dan Stoza7f7da322014-05-02 15:26:25 -0700903 info.xdpi = xdpi;
904 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800906 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907
Andy McFadden91b2ca82014-06-13 14:04:23 -0700908 // This is how far in advance a buffer must be queued for
909 // presentation at a given time. If you want a buffer to appear
910 // on the screen at time N, you must submit the buffer before
911 // (N - presentationDeadline).
912 //
913 // Normally it's one full refresh period (to give SF a chance to
914 // latch the buffer), but this can be reduced by configuring a
915 // DispSync offset. Any additional delays introduced by the hardware
916 // composer or panel must be accounted for here.
917 //
918 // We add an additional 1ms to allow for processing time and
919 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800920 info.presentationDeadline =
921 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700922
923 // All non-virtual displays are currently considered secure.
924 info.secure = true;
925
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800926 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700927 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800928 std::swap(info.w, info.h);
929 }
930
Michael Wright28f24d02016-07-12 13:30:53 -0700931 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700932 }
933
Dan Stoza7f7da322014-05-02 15:26:25 -0700934 return NO_ERROR;
935}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
938 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700939 return BAD_VALUE;
940 }
941
Ana Krulece588e312018-09-18 12:32:24 -0700942 if (mUseScheduler) {
943 mScheduler->getDisplayStatInfo(stats);
944 } else {
945 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
946 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
947 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700948 return NO_ERROR;
949}
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
952 const auto display = getDisplayDevice(displayToken);
953 if (!display) {
954 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800955 return BAD_VALUE;
956 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700957
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700959}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700960
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
962 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800963 postMessageAsync(new LambdaMessage(
964 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800965 return NO_ERROR;
966}
967
968status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
969 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800970 postMessageSync(new LambdaMessage(
971 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800972 return NO_ERROR;
973}
974
975void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
976 Vector<DisplayInfo> configs;
977 getDisplayConfigs(displayToken, &configs);
978 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
979 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
980 return;
981 }
982
983 const auto display = getDisplayDevice(displayToken);
984 if (!display) {
985 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
986 displayToken.get());
987 return;
988 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 ALOGW("Attempt to set active config %d for virtual display", mode);
991 return;
992 }
993 int currentDisplayPowerMode = display->getPowerMode();
994 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
995 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700996 return;
997 }
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001000 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001001 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002 return;
1003 }
Ana Krulecb43429d2019-01-09 14:28:51 -08001004 if (mUseScheduler) {
1005 mRefreshRateStats->setConfigMode(mode);
1006 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001007
Dominik Laskowski075d3172018-05-24 15:50:06 -07001008 const auto displayId = display->getId();
1009 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001013
Ana Krulec7d1d6832018-12-27 11:10:09 -08001014 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001015 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001016}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1019 Vector<ColorMode>* outColorModes) {
1020 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001021 return BAD_VALUE;
1022 }
1023
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001025 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001026 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1027
1028 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1029 if (!displayId) {
1030 return NAME_NOT_FOUND;
1031 }
1032
Dominik Laskowski075d3172018-05-24 15:50:06 -07001033 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001034 }
Michael Wright28f24d02016-07-12 13:30:53 -07001035 outColorModes->clear();
1036 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1037
1038 return NO_ERROR;
1039}
1040
Daniel Solomon42d04562019-01-20 21:03:19 -08001041status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1042 ui::DisplayPrimaries &primaries) {
1043 if (!displayToken) {
1044 return BAD_VALUE;
1045 }
1046
1047 // Currently we only support this API for a single internal display.
1048 if (getInternalDisplayToken() != displayToken) {
1049 return BAD_VALUE;
1050 }
1051
1052 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1053 return NO_ERROR;
1054}
1055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1057 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001058 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001059 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001060 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001061}
1062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001064 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065 Vector<ColorMode> modes;
1066 getDisplayColorModes(displayToken, &modes);
1067 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1068 if (mode < ColorMode::NATIVE || !exists) {
1069 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1070 decodeColorMode(mode).c_str(), mode, displayToken.get());
1071 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001072 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073 const auto display = getDisplayDevice(displayToken);
1074 if (!display) {
1075 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1076 decodeColorMode(mode).c_str(), mode, displayToken.get());
1077 } else if (display->isVirtual()) {
1078 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1079 decodeColorMode(mode).c_str(), mode);
1080 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001081 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1082 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 }
1084 }));
1085
Michael Wright28f24d02016-07-12 13:30:53 -07001086 return NO_ERROR;
1087}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001088
Svetoslavd85084b2014-03-20 10:28:31 -07001089status_t SurfaceFlinger::clearAnimationFrameStats() {
1090 Mutex::Autolock _l(mStateLock);
1091 mAnimFrameTracker.clearStats();
1092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1096 Mutex::Autolock _l(mStateLock);
1097 mAnimFrameTracker.getStats(outStats);
1098 return NO_ERROR;
1099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1102 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001103 Mutex::Autolock _l(mStateLock);
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 const auto display = getDisplayDeviceLocked(displayToken);
1106 if (!display) {
1107 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001108 return BAD_VALUE;
1109 }
1110
Peiyong Linfb069302018-04-25 14:34:31 -07001111 // At this point the DisplayDeivce should already be set up,
1112 // meaning the luminance information is already queried from
1113 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001115 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1116 capabilities.getDesiredMaxLuminance(),
1117 capabilities.getDesiredMaxAverageLuminance(),
1118 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001119
1120 return NO_ERROR;
1121}
1122
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001123status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1124 ui::PixelFormat* outFormat,
1125 ui::Dataspace* outDataspace,
1126 uint8_t* outComponentMask) const {
1127 if (!outFormat || !outDataspace || !outComponentMask) {
1128 return BAD_VALUE;
1129 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001130 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001131 if (!display || !display->getId()) {
1132 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1133 return BAD_VALUE;
1134 }
1135 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1136 outDataspace, outComponentMask);
1137}
1138
Kevin DuBois74e53772018-11-19 10:52:38 -08001139status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1140 bool enable, uint8_t componentMask,
1141 uint64_t maxFrames) const {
1142 const auto display = getDisplayDevice(displayToken);
1143 if (!display || !display->getId()) {
1144 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1145 return BAD_VALUE;
1146 }
1147
1148 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1149 componentMask, maxFrames);
1150}
1151
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001152status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1153 uint64_t maxFrames, uint64_t timestamp,
1154 DisplayedFrameStats* outStats) const {
1155 const auto display = getDisplayDevice(displayToken);
1156 if (!display || !display->getId()) {
1157 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1158 return BAD_VALUE;
1159 }
1160
1161 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1162 outStats);
1163}
1164
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001165status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1166 if (!outSupported) {
1167 return BAD_VALUE;
1168 }
1169 *outSupported = getRenderEngine().supportsProtectedContent();
1170 return NO_ERROR;
1171}
1172
Marissa Wallebc2c052019-01-16 19:16:55 -08001173status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1174 int32_t* outBufferId) {
1175 if (!outBufferId) {
1176 return BAD_VALUE;
1177 }
1178 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1179 return NO_ERROR;
1180}
1181
1182status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1183 mBufferStateLayerCache.release(token, bufferId);
1184 return NO_ERROR;
1185}
1186
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001187status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1188 bool* outIsWideColorDisplay) const {
1189 if (!displayToken || !outIsWideColorDisplay) {
1190 return BAD_VALUE;
1191 }
1192 Mutex::Autolock _l(mStateLock);
1193 const auto display = getDisplayDeviceLocked(displayToken);
1194 if (!display) {
1195 return BAD_VALUE;
1196 }
1197 *outIsWideColorDisplay = display->hasWideColorGamut();
1198 return NO_ERROR;
1199}
1200
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001201status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001202 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204
Chia-I Wu90f669f2017-10-05 14:24:41 -07001205 if (mInjectVSyncs == enable) {
1206 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001207 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208
Dominik Laskowski83b88212018-12-11 13:34:06 -08001209 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001210
Ana Krulec98b5b242018-08-10 15:03:23 -07001211 // TODO(akrulec): Part of the Injector should be refactored, so that it
1212 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001213 if (enable) {
1214 ALOGV("VSync Injections enabled");
1215 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001216 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001217 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001218 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001219 impl::EventThread::InterceptVSyncsCallback(),
1220 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001222 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001223 } else {
1224 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001225 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001226 }
1227
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001229 }));
1230
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001231 return NO_ERROR;
1232}
1233
1234status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235 Mutex::Autolock _l(mStateLock);
1236
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001237 if (!mInjectVSyncs) {
1238 ALOGE("VSync Injections not enabled");
1239 return BAD_VALUE;
1240 }
1241 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1242 ALOGV("Injecting VSync inside SurfaceFlinger");
1243 mVSyncInjector->onInjectSyncEvent(when);
1244 }
1245 return NO_ERROR;
1246}
1247
Lloyd Pique755e3192018-01-31 16:46:15 -08001248status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1249 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001250 // Try to acquire a lock for 1s, fail gracefully
1251 const status_t err = mStateLock.timedLock(s2ns(1));
1252 const bool locked = (err == NO_ERROR);
1253 if (!locked) {
1254 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1255 return TIMED_OUT;
1256 }
1257
1258 outLayers->clear();
1259 mCurrentState.traverseInZOrder([&](Layer* layer) {
1260 outLayers->push_back(layer->getLayerDebugInfo());
1261 });
1262
1263 mStateLock.unlock();
1264 return NO_ERROR;
1265}
1266
Peiyong Linc6780972018-10-28 15:24:08 -07001267status_t SurfaceFlinger::getCompositionPreference(
1268 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1269 Dataspace* outWideColorGamutDataspace,
1270 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001271 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001272 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001273 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001274 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001275 return NO_ERROR;
1276}
1277
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001278// ----------------------------------------------------------------------------
1279
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001280sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1281 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001282 auto resyncCallback = makeResyncCallback([this] {
1283 Mutex::Autolock lock(mStateLock);
1284 return getVsyncPeriod();
1285 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 if (mUseScheduler) {
1288 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001289 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001290 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001291 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001292 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001293 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001294 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001295 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001296 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001297 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001298 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001299 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001300}
1301
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001302// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303
1304void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001305 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001306}
1307
1308void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001309 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001310}
1311
1312void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001313 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314}
1315
1316void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001317 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001318 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001319}
1320
1321status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001322 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324}
1325
1326status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001327 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001328 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001329 if (res == NO_ERROR) {
1330 msg->wait();
1331 }
1332 return res;
1333}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001335void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001336 do {
1337 waitForEvent();
1338 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001339}
1340
Dominik Laskowski83b88212018-12-11 13:34:06 -08001341nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001342 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001343 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1344 return 0;
1345 }
1346
1347 const auto config = getHwComposer().getActiveConfig(*displayId);
1348 return config ? config->getVsyncPeriod() : 0;
1349}
1350
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351void SurfaceFlinger::enableHardwareVsync() {
1352 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001354 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001357 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358}
1359
Dominik Laskowski83b88212018-12-11 13:34:06 -08001360void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001361 Mutex::Autolock _l(mHWVsyncLock);
1362
Jesse Hall948fe0c2013-10-14 12:56:09 -07001363 if (makeAvailable) {
1364 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001365 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1366 if (mUseScheduler) {
1367 mScheduler->makeHWSyncAvailable(true);
1368 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001369 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001370 // Hardware vsync is not currently available, so abort the resync
1371 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001372 return;
1373 }
1374
Dominik Laskowski83b88212018-12-11 13:34:06 -08001375 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001376 return;
1377 }
1378
Ana Krulece588e312018-09-18 12:32:24 -07001379 if (mUseScheduler) {
1380 mScheduler->setVsyncPeriod(period);
1381 } else {
1382 mPrimaryDispSync->reset();
1383 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384
Ana Krulece588e312018-09-18 12:32:24 -07001385 if (!mPrimaryHWVsyncEnabled) {
1386 mPrimaryDispSync->beginResync();
1387 mEventControlThread->setVsyncEnabled(true);
1388 mPrimaryHWVsyncEnabled = true;
1389 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001390 }
1391}
1392
Jesse Hall948fe0c2013-10-14 12:56:09 -07001393void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001394 Mutex::Autolock _l(mHWVsyncLock);
1395 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001396 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001397 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001398 mPrimaryHWVsyncEnabled = false;
1399 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001400 if (makeUnavailable) {
1401 mHWVsyncAvailable = false;
1402 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001403}
1404
Dominik Laskowski83b88212018-12-11 13:34:06 -08001405void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001406 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001407
Dan Stoza57164302017-05-08 14:03:54 -07001408 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001409 const nsecs_t last = lastResyncTime.exchange(now);
1410
1411 if (now - last > kIgnoreDelay) {
1412 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001413 }
1414}
1415
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001416void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1417 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001418 ATRACE_NAME("SF onVsync");
1419
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 return;
1424 }
1425
Dominik Laskowski075d3172018-05-24 15:50:06 -07001426 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001427 return;
1428 }
1429
Dominik Laskowski075d3172018-05-24 15:50:06 -07001430 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001431 // For now, we don't do anything with external display vsyncs.
1432 return;
1433 }
1434
Ana Krulece588e312018-09-18 12:32:24 -07001435 if (mUseScheduler) {
1436 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001437 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001438 bool needsHwVsync = false;
1439 { // Scope for the lock
1440 Mutex::Autolock _l(mHWVsyncLock);
1441 if (mPrimaryHWVsyncEnabled) {
1442 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1443 }
1444 }
1445
1446 if (needsHwVsync) {
1447 enableHardwareVsync();
1448 } else {
1449 disableHardwareVsync(false);
1450 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001451 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001452}
1453
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001454void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001455 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1456 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001457}
1458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001459// TODO(b/123715322): Fix thread safety.
1460void SurfaceFlinger::setRefreshRateTo(float newFps) NO_THREAD_SAFETY_ANALYSIS {
1461 const auto display = getDefaultDisplayDeviceLocked();
1462 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001463 return;
1464 }
1465 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1466 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1467 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1468 // refresh cycle.
1469
1470 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001471 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001472 if (currentVsyncPeriod == 0) {
1473 return;
1474 }
1475 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1476 // floating numbers.
1477 const float currentFps = 1e9 / currentVsyncPeriod;
1478 if (std::abs(currentFps - newFps) <= 1) {
1479 return;
1480 }
1481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001482 auto configs = getHwComposer().getConfigs(*display->getId());
Ana Krulec7d1d6832018-12-27 11:10:09 -08001483 for (int i = 0; i < configs.size(); i++) {
1484 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1485 if (vsyncPeriod == 0) {
1486 continue;
1487 }
1488 const float fps = 1e9 / vsyncPeriod;
1489 // TODO(b/113612090): There should be a better way at determining which config
1490 // has the right refresh rate.
1491 if (std::abs(fps - newFps) <= 1) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001492 const sp<IBinder> token = display->getDisplayToken().promote();
1493 LOG_ALWAYS_FATAL_IF(token == nullptr);
1494
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495 // This is posted in async function to avoid deadlock when getDisplayDevice
1496 // requires mStateLock.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001497 setActiveConfigAsync(token, i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001498 ATRACE_INT("FPS", newFps);
1499 }
1500 }
1501}
1502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001504 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001505 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001506 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001507
Lloyd Piqueba04e622017-12-14 17:11:26 -08001508 // Ignore events that do not have the right sequenceId.
1509 if (sequenceId != getBE().mComposerSequenceId) {
1510 return;
1511 }
1512
Steven Thomasb02664d2017-07-26 18:48:28 -07001513 // Only lock if we're not on the main thread. This function is normally
1514 // called on a hwbinder thread, but for the primary display it's called on
1515 // the main thread with the state lock already held, so don't attempt to
1516 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001517 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001518
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001519 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001520
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001521 if (std::this_thread::get_id() == mMainThreadId) {
1522 // Process all pending hot plug events immediately if we are on the main thread.
1523 processDisplayHotplugEventsLocked();
1524 }
1525
Lloyd Piqueba04e622017-12-14 17:11:26 -08001526 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001527}
1528
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001529void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001530 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001531 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001533 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001534 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001535}
1536
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001537void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001538 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001540 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001541 getHwComposer().setVsyncEnabled(*displayId,
1542 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1543 }
Mathias Agopian86303202012-07-24 22:46:10 -07001544}
1545
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001547void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001548 if (mUseScheduler) {
1549 mScheduler->disableHardwareVsync(true);
1550 } else {
1551 disableHardwareVsync(true);
1552 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553 // Clear the drawing state so that the logic inside of
1554 // handleTransactionLocked will fire. It will determine the delta between
1555 // mCurrentState and mDrawingState and re-apply all changes when we make the
1556 // transition.
1557 mDrawingState.displays.clear();
1558 mDisplays.clear();
1559}
1560
Steven Thomas050b2c82017-03-06 11:45:16 -08001561void SurfaceFlinger::updateVrFlinger() {
1562 if (!mVrFlinger)
1563 return;
1564 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001566 return;
1567 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568
Lloyd Pique441d5042018-10-18 16:49:51 -07001569 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 ALOGE("Vr flinger is only supported for remote hardware composer"
1571 " service connections. Ignoring request to transition to vr"
1572 " flinger.");
1573 mVrFlingerRequestsDisplay = false;
1574 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001575 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001576
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578
Steven Thomas0123ac62018-07-12 11:32:34 -07001579 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001580 LOG_ALWAYS_FATAL_IF(!display);
1581 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001582 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1583 // called below. Clear the reference now so we don't accidentally use it
1584 // later.
1585 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001586
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001589 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001590
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001592 // Delete the current instance before creating the new one
1593 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1594 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1595 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1596 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001597
Lloyd Pique441d5042018-10-18 16:49:51 -07001598 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001599 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001600
1601 if (vrFlingerRequestsDisplay) {
1602 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001603 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001604
1605 mVisibleRegionsDirty = true;
1606 invalidateHwcGeometry();
1607
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001608 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001609 display = getDefaultDisplayDeviceLocked();
1610 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001611 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001612
Steven Thomasb02664d2017-07-26 18:48:28 -07001613 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001614 const nsecs_t vsyncPeriod = getVsyncPeriod();
1615 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001616
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001617 // The present fences returned from vr_hwc are not an accurate
1618 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001619 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001620 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1621 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001622 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001624 !hasSyncFramework);
1625 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001626
Steven Thomasb02664d2017-07-26 18:48:28 -07001627 // Use phase of 0 since phase is not known.
1628 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001629 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001630 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001631
Dominik Laskowski83b88212018-12-11 13:34:06 -08001632 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001633
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001634 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001635 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001636}
1637
Mathias Agopian4fec8732012-06-29 14:12:52 -07001638void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001639 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001640 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001641 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001642 if (mUseScheduler) {
1643 // This call is made each time SF wakes up and creates a new frame.
1644 mScheduler->incrementFrameCounter();
1645 }
Dan Stoza50182882016-07-08 12:02:20 -07001646 bool frameMissed = !mHadClientComposition &&
1647 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 (mPreviousPresentFence->getSignalTime() ==
1649 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001650 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001651 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001652 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001653 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001654 if (mPropagateBackpressure) {
1655 signalLayerUpdate();
1656 break;
1657 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001658 }
Dan Stoza50182882016-07-08 12:02:20 -07001659
Steven Thomas050b2c82017-03-06 11:45:16 -08001660 // Now that we're going to make it to the handleMessageTransaction()
1661 // call below it's safe to call updateVrFlinger(), which will
1662 // potentially trigger a display handoff.
1663 updateVrFlinger();
1664
Dan Stoza6b9454d2014-11-07 16:00:59 -08001665 bool refreshNeeded = handleMessageTransaction();
1666 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001667 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001668 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001669 // Signal a refresh if a transaction modified the window state,
1670 // a new buffer was latched, or if HWC has requested a full
1671 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001672 signalRefresh();
1673 }
1674 break;
1675 }
1676 case MessageQueue::REFRESH: {
1677 handleMessageRefresh();
1678 break;
1679 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001680 }
1681}
1682
Dan Stoza6b9454d2014-11-07 16:00:59 -08001683bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001684 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001685
1686 // Apply any ready transactions in the queues if there are still transactions that have not been
1687 // applied, wake up during the next vsync period and check again
1688 bool transactionNeeded = false;
1689 if (!flushTransactionQueues()) {
1690 transactionNeeded = true;
1691 }
1692
Mathias Agopian4fec8732012-06-29 14:12:52 -07001693 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001694 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001695 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001696
1697 if (transactionNeeded) {
1698 setTransactionFlags(eTransactionNeeded);
1699 }
1700
1701 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702}
1703
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001706
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001707 mRefreshPending = false;
1708
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001709 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001710 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001711 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001712 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001713 for (const auto& [token, display] : mDisplays) {
1714 beginFrame(display);
1715 prepareFrame(display);
1716 doDebugFlashRegions(display, repaintEverything);
1717 doComposition(display, repaintEverything);
1718 }
1719
Adrian Roos1e1a1282017-11-01 19:05:31 +01001720 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001721 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001722
1723 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001724 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001725
Dan Stozabfbffeb2016-07-21 14:49:33 -07001726 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001727 for (const auto& [token, displayDevice] : mDisplays) {
1728 auto display = displayDevice->getCompositionDisplay();
1729 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001730 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001731 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001732 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001733
Alec Mouri86770e52018-09-24 22:40:58 +00001734 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001735 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001736 if (mHadClientComposition) {
1737 base::unique_fd flushFence(getRenderEngine().flush());
1738 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1739 getBE().flushFence = new Fence(std::move(flushFence));
1740 } else {
1741 // Cleanup for hygiene.
1742 getBE().flushFence = Fence::NO_FENCE;
1743 }
1744 }
1745
Jorim Jaggi90535212018-05-23 23:44:06 +02001746 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001747
David Sodman7e4ae112018-02-09 15:02:28 -08001748 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001749 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001750 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001751 compositionInfo.hwc.hwcLayer = nullptr;
1752 }
David Sodmanba340492018-08-05 21:51:33 -07001753 }
David Sodman7e4ae112018-02-09 15:02:28 -08001754
1755 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001757
David Sodmanfa9b2af2017-12-24 13:28:59 -08001758
1759bool SurfaceFlinger::handleMessageInvalidate() {
1760 ATRACE_CALL();
1761 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001762}
1763
David Sodman79bba0e2018-08-05 18:07:49 -07001764void SurfaceFlinger::calculateWorkingSet() {
1765 ATRACE_CALL();
1766 ALOGV(__FUNCTION__);
1767
David Sodman79bba0e2018-08-05 18:07:49 -07001768 // build the h/w work list
1769 if (CC_UNLIKELY(mGeometryInvalid)) {
1770 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001771 for (const auto& [token, displayDevice] : mDisplays) {
1772 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001773 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 if (!displayId) {
1775 continue;
1776 }
David Sodman79bba0e2018-08-05 18:07:49 -07001777
Lloyd Pique32cbe282018-10-19 13:09:22 -07001778 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001779 for (size_t i = 0; i < currentLayers.size(); i++) {
1780 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001781
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 if (!layer->hasHwcLayer(*displayId)) {
1783 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1784 layer->forceClientComposition(*displayId);
1785 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001786 }
1787 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001788
Lloyd Pique32cbe282018-10-19 13:09:22 -07001789 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001790 if (mDebugDisableHWC || mDebugRegion) {
1791 layer->forceClientComposition(*displayId);
1792 }
David Sodman79bba0e2018-08-05 18:07:49 -07001793 }
1794 }
1795 }
1796
1797 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 for (const auto& [token, displayDevice] : mDisplays) {
1799 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001800 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001802 continue;
1803 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001804 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001805
1806 if (mDrawingState.colorMatrixChanged) {
1807 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001810 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001811 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001812 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1813 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001814 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1817 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001818 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001819 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 }
1821
Peiyong Lind3788632018-09-18 16:01:31 -07001822 // TODO(b/111562338) remove when composer 2.3 is shipped.
1823 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001824 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001825 }
1826
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001827 if (layer->getRoundedCornerState().radius > 0.0f) {
1828 layer->forceClientComposition(*displayId);
1829 }
1830
Dominik Laskowski075d3172018-05-24 15:50:06 -07001831 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001832 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001833 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001834 continue;
1835 }
1836
Lloyd Pique32cbe282018-10-19 13:09:22 -07001837 const auto& displayState = display->getState();
1838 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1839 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001840 }
1841
Peiyong Lin13effd12018-07-24 17:01:47 -07001842 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001843 ColorMode colorMode;
1844 Dataspace dataSpace;
1845 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001846 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001847 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001848 }
1849 }
1850
1851 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001852
1853 for (const auto& [token, display] : mDisplays) {
1854 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001855 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001856 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001857
1858 if (displayId) {
1859 if (!layer->setHwcLayer(*displayId)) {
1860 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1861 }
1862 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001863 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001864
Dominik Laskowski05275f12018-11-01 15:03:24 -07001865 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001866 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1867 }
1868 }
David Sodman79bba0e2018-08-05 18:07:49 -07001869}
1870
Lloyd Pique32cbe282018-10-19 13:09:22 -07001871void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1872 bool repaintEverything) {
1873 auto display = displayDevice->getCompositionDisplay();
1874 const auto& displayState = display->getState();
1875
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876 // is debugging enabled
1877 if (CC_LIKELY(!mDebugRegion))
1878 return;
1879
Lloyd Pique32cbe282018-10-19 13:09:22 -07001880 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001881 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08001882 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001883 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001884 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001885 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001886 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001887
Alec Mouri0f714832018-11-12 15:31:06 -08001888 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889 }
1890 }
1891
Lloyd Pique32cbe282018-10-19 13:09:22 -07001892 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893
1894 if (mDebugRegion > 1) {
1895 usleep(mDebugRegion * 1000);
1896 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001897
Lloyd Pique32cbe282018-10-19 13:09:22 -07001898 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899}
1900
Adrian Roos1e1a1282017-11-01 19:05:31 +01001901void SurfaceFlinger::doTracing(const char* where) {
1902 ATRACE_CALL();
1903 ATRACE_NAME(where);
1904 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001905 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001906 }
1907}
1908
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001909void SurfaceFlinger::logLayerStats() {
1910 ATRACE_CALL();
1911 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001912 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913 if (display->isPrimary()) {
1914 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001916 }
1917 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001918
1919 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001920 }
1921}
1922
David Sodman2b406362017-12-15 13:33:47 -08001923void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 ATRACE_CALL();
1926 ALOGV("preComposition");
1927
David Sodman2b406362017-12-15 13:33:47 -08001928 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1929
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001931 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001932 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933 needExtraInvalidate = true;
1934 }
Robert Carr2047fae2016-11-28 14:09:09 -08001935 });
1936
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 if (needExtraInvalidate) {
1938 signalLayerUpdate();
1939 }
1940}
1941
Ana Krulece588e312018-09-18 12:32:24 -07001942void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1943 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Update queue of past composite+present times and determine the
1945 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001948 while (!getBE().mCompositePresentTimes.empty()) {
1949 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 // Cached values should have been updated before calling this method,
1951 // which helps avoid duplicate syscalls.
1952 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1953 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1954 break;
1955 }
1956 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001957 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 }
1959
1960 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001961 while (getBE().mCompositePresentTimes.size() > 16) {
1962 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963 }
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001966}
1967
Ana Krulece588e312018-09-18 12:32:24 -07001968void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1969 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // Integer division and modulo round toward 0 not -inf, so we need to
1971 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001972 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1973 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1974 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
Ana Krulec757f63a2019-01-25 10:46:18 -08001976 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001977 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001978 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001979 }
1980
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 // Snap the latency to a value that removes scheduling jitter from the
1982 // composition and present times, which often have >1ms of jitter.
1983 // Reducing jitter is important if an app attempts to extrapolate
1984 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001985 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001987 nsecs_t bias = stats.vsyncPeriod / 2;
1988 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1989 nsecs_t snappedCompositeToPresentLatency =
1990 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991
David Sodman99974d22017-11-28 12:04:33 -08001992 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001993 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1994 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001995 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001996}
1997
Ady Abraham8164d482019-01-11 14:47:59 -08001998// debug patch for b/119477596 - add stack guards to catch stack
1999// corruptions and disable clang optimizations.
2000// The code below is temporary and planned to be removed once stack
2001// corruptions are found.
2002#pragma clang optimize off
2003class StackGuard {
2004public:
2005 StackGuard(const char* name, const char* func, int line) {
2006 guarders.reserve(MIN_CAPACITY);
2007 guarders.push_back({this, name, func, line});
2008 validate();
2009 }
2010 ~StackGuard() {
2011 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2012 if (i->guard == this) {
2013 guarders.erase(i);
2014 break;
2015 }
2016 }
2017 }
2018
2019 static void validate() {
2020 for (const auto& guard : guarders) {
2021 if (guard.guard->cookie != COOKIE_VALUE) {
2022 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2023 CallStack stack(LOG_TAG);
2024 abort();
2025 }
2026 }
2027 }
2028
2029private:
2030 uint64_t cookie = COOKIE_VALUE;
2031 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2032 static constexpr size_t MIN_CAPACITY = 16;
2033
2034 struct GuarderElement {
2035 StackGuard* guard;
2036 const char* name;
2037 const char* func;
2038 int line;
2039 };
2040
2041 static std::vector<GuarderElement> guarders;
2042};
2043std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2044
2045#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2046
2047#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002048void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002049{
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 ATRACE_CALL();
2052 ALOGV("postComposition");
2053
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002055 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002056 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002057 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002058 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002059 }
Ady Abraham8164d482019-01-11 14:47:59 -08002060 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002061
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002062 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002063 const auto displayDevice = getDefaultDisplayDeviceLocked();
2064 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065
David Sodman73beded2017-11-15 11:56:06 -08002066 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002067 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002068 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2069
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002071 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002072 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2073 ->getRenderSurface()
2074 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002075 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076 } else {
2077 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2078 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079
Ady Abraham8164d482019-01-11 14:47:59 -08002080 ASSERT_ON_STACK_GUARD();
2081
David Sodman73beded2017-11-15 11:56:06 -08002082 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002083 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2084 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002085 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002086 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002087 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002088
Ana Krulece588e312018-09-18 12:32:24 -07002089 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002090 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002091 if (mUseScheduler) {
2092 mScheduler->getDisplayStatInfo(&stats);
2093 } else {
2094 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2095 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2096 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002097
Ady Abraham8164d482019-01-11 14:47:59 -08002098 ASSERT_ON_STACK_GUARD();
2099
David Sodman2b406362017-12-15 13:33:47 -08002100 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 // when we started doing work for this frame, but that should be okay
2102 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002103 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002104 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002105 DEFINE_STACK_GUARD(compositorTiming);
2106
Brian Andersond0010582017-03-07 13:20:31 -08002107 {
David Sodman99974d22017-11-28 12:04:33 -08002108 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002110 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002111
2112 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002113 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002114
Robert Carr2047fae2016-11-28 14:09:09 -08002115 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002116 bool frameLatched =
2117 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2118 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002119 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002120 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002121 recordBufferingStats(layer->getName().string(),
2122 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002123 }
Ady Abraham8164d482019-01-11 14:47:59 -08002124 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002125 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002127 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002129 if (mUseScheduler) {
2130 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002132 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002133 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2134 enableHardwareVsync();
2135 } else {
2136 disableHardwareVsync(false);
2137 }
Ady Abraham8164d482019-01-11 14:47:59 -08002138 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002139 }
2140 }
2141
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002142 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002143 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2144 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002145 if (mUseScheduler) {
2146 mScheduler->enableHardwareVsync();
2147 } else {
2148 enableHardwareVsync();
2149 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002150 }
2151 }
2152
Ady Abraham8164d482019-01-11 14:47:59 -08002153 ASSERT_ON_STACK_GUARD();
2154
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002155 if (mAnimCompositionPending) {
2156 mAnimCompositionPending = false;
2157
Brian Anderson4e606e32017-03-16 15:34:57 -07002158 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002160 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002161
2162 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 // The HWC doesn't support present fences, so use the refresh
2165 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002166 const nsecs_t presentTime =
2167 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002168 DEFINE_STACK_GUARD(presentTime);
2169
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002170 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002172 }
2173 mAnimFrameTracker.advanceFrame();
2174 }
Dan Stozab90cf072015-03-05 11:05:59 -08002175
Ady Abraham8164d482019-01-11 14:47:59 -08002176 ASSERT_ON_STACK_GUARD();
2177
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002178 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002179 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002180 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002181 }
2182
Ady Abraham8164d482019-01-11 14:47:59 -08002183 ASSERT_ON_STACK_GUARD();
2184
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002185 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002186
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
2188
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2190 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002191 return;
2192 }
2193
2194 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002195 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002196 if (mHasPoweredOff) {
2197 mHasPoweredOff = false;
2198 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002199 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002200 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002201 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002202 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002203 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2204 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002205 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002206 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002207 }
David Sodman4a36e932017-11-07 14:29:47 -08002208 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002209
2210 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002211 }
David Sodman4a36e932017-11-07 14:29:47 -08002212 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002213 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002214
2215 {
2216 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002217 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002218 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002219 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002220 if (refillCount > 0) {
2221 const size_t offset = mTexturePool.size();
2222 mTexturePool.resize(mTexturePoolSize);
2223 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2224 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2225 }
Ady Abraham8164d482019-01-11 14:47:59 -08002226 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002227 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002228
Marissa Wallfda30bb2018-10-12 11:34:28 -07002229 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002230 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002231
2232 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002233}
Ady Abraham8164d482019-01-11 14:47:59 -08002234#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002235
2236void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 ATRACE_CALL();
2238 ALOGV("rebuildLayerStacks");
2239
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002240 // We need to clear these out now as these may be holding on to a
2241 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2242 // also holds a reference. When the set of visible layers is recomputed,
2243 // some layers may be destroyed if the only thing keeping them alive was
2244 // that list of visible layers associated with each display. The layer
2245 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2246 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2247 for (const auto& [token, display] : mDisplays) {
2248 getBE().mCompositionInfo[token].clear();
2249 }
2250
Mathias Agopiancd60f992012-08-16 16:28:27 -07002251 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002253 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002254 mVisibleRegionsDirty = false;
2255 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002256
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002257 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const auto& displayDevice = pair.second;
2259 auto display = displayDevice->getCompositionDisplay();
2260 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002261 Region opaqueRegion;
2262 Region dirtyRegion;
2263 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002264 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 const ui::Transform& tr = displayState.transform;
2266 const Rect bounds = displayState.bounds;
2267 if (displayState.isEnabled) {
2268 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002271 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002272 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002273 if (display->belongsInOutput(layer->getLayerStack(),
2274 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002275 Region drawRegion(tr.transform(
2276 layer->visibleNonTransparentRegion));
2277 drawRegion.andSelf(bounds);
2278 if (!drawRegion.isEmpty()) {
2279 layersSortedByZ.add(layer);
2280 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002281 // Clear out the HWC layer if this layer was
2282 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002284 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002285 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002286 // WM changes display->layerStack upon sleep/awake.
2287 // Here we make sure we delete the HWC layers even if
2288 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002289 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002290 }
2291
2292 // If a layer is not going to get a release fence because
2293 // it is invisible, but it is also going to release its
2294 // old buffer, add it to the list of layers needing
2295 // fences.
2296 if (hwcLayerDestroyed) {
2297 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2298 mLayersWithQueuedFrames.cend(), layer);
2299 if (found != mLayersWithQueuedFrames.cend()) {
2300 layersNeedingFences.add(layer);
2301 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002302 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002303 });
2304 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002305 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2306 displayDevice->setLayersNeedingFences(layersNeedingFences);
2307
2308 Region undefinedRegion{bounds};
2309 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2310
2311 display->editState().undefinedRegion = undefinedRegion;
2312 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002313 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002314 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002315}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002319// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002321// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322// The returned HDR data space is one of
2323// - Dataspace::UNKNOWN
2324// - Dataspace::BT2020_HLG
2325// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2327 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002328 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 *outHdrDataSpace = Dataspace::UNKNOWN;
2330
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002332 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 case Dataspace::V0_SCRGB:
2334 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002335 case Dataspace::BT2020:
2336 case Dataspace::BT2020_ITU:
2337 case Dataspace::BT2020_LINEAR:
2338 case Dataspace::DISPLAY_BT2020:
2339 bestDataSpace = Dataspace::DISPLAY_BT2020;
2340 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002342 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 case Dataspace::BT2020_PQ:
2345 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002347 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002348 case Dataspace::BT2020_HLG:
2349 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002350 // When there's mixed PQ content and HLG content, we set the HDR
2351 // data space to be BT2020_PQ and convert HLG to PQ.
2352 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2353 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002354 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355 break;
2356 default:
2357 break;
2358 }
Romain Guy54f154a2017-10-24 21:40:32 +01002359 }
2360
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002361 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002362}
2363
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002364// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2366 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2368 *outMode = ColorMode::NATIVE;
2369 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002370 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002372 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002373
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002377 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2378
Peiyong Lindfde5112018-06-05 10:58:41 -07002379 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002380 const bool isHdr =
2381 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002382 if (isHdr) {
2383 bestDataSpace = hdrDataSpace;
2384 }
2385
Chia-I Wu0d711262018-05-21 15:19:35 -07002386 RenderIntent intent;
2387 switch (mDisplayColorSetting) {
2388 case DisplayColorSetting::MANAGED:
2389 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002390 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002391 break;
2392 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002393 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002394 break;
2395 default: // vendor display color setting
2396 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2397 break;
2398 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002399
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002400 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002401}
2402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2404 auto display = displayDevice->getCompositionDisplay();
2405 const auto& displayState = display->getState();
2406
Alec Mouri0f714832018-11-12 15:31:06 -08002407 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2409 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002410
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 // If nothing has changed (!dirty), don't recompose.
2412 // If something changed, but we don't currently have any visible layers,
2413 // and didn't when we last did a composition, then skip it this time.
2414 // The second rule does two things:
2415 // - When all layers are removed from a display, we'll emit one black
2416 // frame, then nothing more until we get new layers.
2417 // - When a display is created with a private layer stack, we won't
2418 // emit any black frames until a layer is added to the layer stack.
2419 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 const char flagPrefix[] = {'-', '+'};
2422 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2424 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2425 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2426 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002427
Lloyd Pique31cb2942018-10-19 17:23:03 -07002428 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002432 }
2433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2436 auto display = displayDevice->getCompositionDisplay();
2437 const auto& displayState = display->getState();
2438
2439 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 return;
David Sodman2b406362017-12-15 13:33:47 -08002441 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002442
Lloyd Pique31cb2942018-10-19 17:23:03 -07002443 status_t result = display->getRenderSurface()->prepareFrame(
2444 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002447}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002450 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 ALOGV("doComposition");
2452
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 auto display = displayDevice->getCompositionDisplay();
2454 const auto& displayState = display->getState();
2455
2456 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002458 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002459
David Sodmanfa9b2af2017-12-24 13:28:59 -08002460 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002462
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002464 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002465 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002467}
2468
David Sodmanfa9b2af2017-12-24 13:28:59 -08002469void SurfaceFlinger::postFrame()
2470{
2471 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 const auto display = getDefaultDisplayDeviceLocked();
2473 if (display && getHwComposer().isConnected(*display->getId())) {
2474 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2476 logFrameStats();
2477 }
2478 }
2479}
2480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002482 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002484
Lloyd Pique32cbe282018-10-19 13:09:22 -07002485 auto display = displayDevice->getCompositionDisplay();
2486 const auto& displayState = display->getState();
2487 const auto displayId = display->getId();
2488
David Sodmanfa9b2af2017-12-24 13:28:59 -08002489 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002490
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 if (displayId) {
2493 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002494 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002495 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002496 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002497 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002498
Chia-I Wu7b549592017-11-15 09:14:57 -08002499 // The layer buffer from the previous frame (if any) is released
2500 // by HWC only when the release fence from this frame (if any) is
2501 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 if (displayId && layer->hasHwcLayer(*displayId)) {
2503 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2504 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002505 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002506
2507 // If the layer was client composited in the previous frame, we
2508 // need to merge with the previous client target acquire fence.
2509 // Since we do not track that, always merge with the current
2510 // client target acquire fence when it is available, even though
2511 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002512 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002513 releaseFence =
2514 Fence::merge("LayerRelease", releaseFence,
2515 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002516 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002517
David Sodman15094112018-10-11 09:39:37 -07002518 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 }
Chia-I Wu83806892017-11-16 10:50:20 -08002520
2521 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002523 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002524 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002526 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002527 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002528 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002529 }
2530 }
2531
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (displayId) {
2533 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002534 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536}
2537
Mathias Agopian87baae12012-07-31 12:38:26 -07002538void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539{
Mathias Agopian841cde52012-03-01 15:44:37 -08002540 ATRACE_CALL();
2541
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002542 // here we keep a copy of the drawing state (that is the state that's
2543 // going to be overwritten by handleTransactionLocked()) outside of
2544 // mStateLock so that the side-effects of the State assignment
2545 // don't happen with mStateLock held (which can cause deadlocks).
2546 State drawingState(mDrawingState);
2547
Mathias Agopianca4d3602011-05-19 15:38:14 -07002548 Mutex::Autolock _l(mStateLock);
2549 const nsecs_t now = systemTime();
2550 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551
Mathias Agopianca4d3602011-05-19 15:38:14 -07002552 // Here we're guaranteed that some transaction flags are set
2553 // so we can call handleTransactionLocked() unconditionally.
2554 // We call getTransactionFlags(), which will also clear the flags,
2555 // with mStateLock held to guarantee that mCurrentState won't change
2556 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002557
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002558 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002559 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002560 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002561
Mathias Agopianca4d3602011-05-19 15:38:14 -07002562 mLastTransactionTime = systemTime() - now;
2563 mDebugInTransaction = 0;
2564 invalidateHwcGeometry();
2565 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002566}
2567
Lloyd Piqueba04e622017-12-14 17:11:26 -08002568void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2569 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 const std::optional<DisplayIdentificationInfo> info =
2571 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002574 continue;
2575 }
2576
Lloyd Piqueba04e622017-12-14 17:11:26 -08002577 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002579 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 mPhysicalDisplayTokens[info->id] = new BBinder();
2581 DisplayDeviceState state;
2582 state.displayId = info->id;
2583 state.isSecure = true; // All physical displays are currently considered secure.
2584 state.displayName = info->name;
2585 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2586 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002587 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002589 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2592 if (index >= 0) {
2593 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2594 mInterceptor->saveDisplayDeletion(state.sequenceId);
2595 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002596 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598 }
2599
2600 processDisplayChangesLocked();
2601 }
2602
2603 mPendingHotplugEvents.clear();
2604}
2605
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002606void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002607 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002608 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2609 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002610 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002611 mEventThread->onHotplugReceived(displayId, connected);
2612 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002613 }
2614}
2615
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002618 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 const sp<IGraphicBufferProducer>& producer) {
2620 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002621 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002623 creationArgs.isSecure = state.isSecure;
2624 creationArgs.displaySurface = dispSurface;
2625 creationArgs.hasWideColorGamut = false;
2626 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002627
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002628 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 creationArgs.isPrimary = isInternalDisplay;
2630
2631 if (useColorManagement && displayId) {
2632 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002634 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002635 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002637
Dominik Laskowski7e045462018-05-30 13:02:02 -07002638 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002640 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641 }
tangrobin6753a022018-08-10 10:58:54 +08002642 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 if (displayId) {
2645 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002648 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649
Lloyd Pique90c115d2018-09-18 21:39:42 -07002650 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002652 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654 // Make sure that composition can never be stalled by a virtual display
2655 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002656 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002657 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2659 }
2660
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 creationArgs.displayInstallOrientation =
2662 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002663
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002665 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Lloyd Pique90c115d2018-09-18 21:39:42 -07002667 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668
2669 if (maxFrameBufferAcquiredBuffers >= 3) {
2670 nativeWindowSurface->preallocateBuffers();
2671 }
2672
2673 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002674 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002675 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002677 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002678 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002679 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2680 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 if (!state.isVirtual()) {
2682 LOG_ALWAYS_FATAL_IF(!displayId);
2683 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002684 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002685
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 display->setLayerStack(state.layerStack);
2687 display->setProjection(state.orientation, state.viewport, state.frame);
2688 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691}
2692
Lloyd Pique347200f2017-12-14 17:00:15 -08002693void SurfaceFlinger::processDisplayChangesLocked() {
2694 // here we take advantage of Vector's copy-on-write semantics to
2695 // improve performance by skipping the transaction entirely when
2696 // know that the lists are identical
2697 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2698 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2699 if (!curr.isIdenticalTo(draw)) {
2700 mVisibleRegionsDirty = true;
2701 const size_t cc = curr.size();
2702 size_t dc = draw.size();
2703
2704 // find the displays that were removed
2705 // (ie: in drawing state but not in current state)
2706 // also handle displays that changed
2707 // (ie: displays that are in both lists)
2708 for (size_t i = 0; i < dc;) {
2709 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2710 if (j < 0) {
2711 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002713 // Save display ID before disconnecting.
2714 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002715 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002716
2717 if (!display->isVirtual()) {
2718 LOG_ALWAYS_FATAL_IF(!displayId);
2719 dispatchDisplayHotplugEvent(displayId->value, false);
2720 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002722
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 } else {
2725 // this display is in both lists. see if something changed.
2726 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2729 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2730 if (state_binder != draw_binder) {
2731 // changing the surface is like destroying and
2732 // recreating the DisplayDevice, so we just remove it
2733 // from the drawing state, so that it get re-added
2734 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002736 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002738 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 mDrawingState.displays.removeItemsAt(i);
2740 dc--;
2741 // at this point we must loop to the next item
2742 continue;
2743 }
2744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 }
2749 if ((state.orientation != draw[i].orientation) ||
2750 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002751 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 }
2753 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 }
2756 }
2757 }
2758 ++i;
2759 }
2760
2761 // find displays that were added
2762 // (ie: in current state but not in drawing state)
2763 for (size_t i = 0; i < cc; i++) {
2764 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2765 const DisplayDeviceState& state(curr[i]);
2766
Lloyd Pique542307f2018-10-19 13:24:08 -07002767 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 sp<IGraphicBufferProducer> producer;
2769 sp<IGraphicBufferProducer> bqProducer;
2770 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002771 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002774 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 // Virtual displays without a surface are dormant:
2776 // they have external state (layer stack, projection,
2777 // etc.) but no internal state (i.e. a DisplayDevice).
2778 if (state.surface != nullptr) {
2779 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 int width = 0;
2782 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2783 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2784 int height = 0;
2785 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2786 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2787 int intFormat = 0;
2788 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2789 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002790 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002791
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 displayId =
2793 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 }
2795
2796 // TODO: Plumb requested format back up to consumer
2797
2798 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002800 bqProducer, bqConsumer,
2801 state.displayName);
2802
2803 dispSurface = vds;
2804 producer = vds;
2805 }
2806 } else {
2807 ALOGE_IF(state.surface != nullptr,
2808 "adding a supported display, but rendering "
2809 "surface is provided (%p), ignoring it",
2810 state.surface.get());
2811
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 displayId = state.displayId;
2813 LOG_ALWAYS_FATAL_IF(!displayId);
2814 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002815 producer = bqProducer;
2816 }
2817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002818 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002819 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002820 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002821 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002823 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002824 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002825 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002826 }
2827 }
2828 }
2829 }
2830 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002831
2832 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002833}
2834
Mathias Agopian87baae12012-07-31 12:38:26 -07002835void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002836{
Dan Stoza7dde5992015-05-22 09:51:44 -07002837 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002838 mCurrentState.traverseInZOrder([](Layer* layer) {
2839 layer->notifyAvailableFrames();
2840 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002841
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 /*
2843 * Traversal of the children
2844 * (perform the transaction for each of them if needed)
2845 */
2846
Robert Carr720e5062018-07-30 17:45:14 -07002847 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002848 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002849 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002851 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852
2853 const uint32_t flags = layer->doTransaction(0);
2854 if (flags & Layer::eVisibleRegion)
2855 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002856
2857 if (flags & Layer::eInputInfoChanged) {
2858 inputChanged = true;
2859 }
Robert Carr2047fae2016-11-28 14:09:09 -08002860 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 }
2862
2863 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002864 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 */
2866
Mathias Agopiane57f2922012-08-09 16:29:12 -07002867 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002868 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002869 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002870 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002872 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002873 // The transform hint might have changed for some layers
2874 // (either because a display has changed, or because a layer
2875 // as changed).
2876 //
2877 // Walk through all the layers in currentLayers,
2878 // and update their transform hint.
2879 //
2880 // If a layer is visible only on a single display, then that
2881 // display is used to calculate the hint, otherwise we use the
2882 // default display.
2883 //
2884 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2885 // the hint is set before we acquire a buffer from the surface texture.
2886 //
2887 // NOTE: layer transactions have taken place already, so we use their
2888 // drawing state. However, SurfaceFlinger's own transaction has not
2889 // happened yet, so we must use the current state layer list
2890 // (soon to become the drawing state list).
2891 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002892 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002893 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002894 bool first = true;
2895 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002896 // NOTE: we rely on the fact that layers are sorted by
2897 // layerStack first (so we don't have to traverse the list
2898 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002900 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002901 currentlayerStack = layerStack;
2902 // figure out if this layerstack is mirrored
2903 // (more than one display) if so, pick the default display,
2904 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 hintDisplay = nullptr;
2906 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002907 if (display->getCompositionDisplay()
2908 ->belongsInOutput(layer->getLayerStack(),
2909 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002910 if (hintDisplay) {
2911 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002912 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002913 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002915 }
2916 }
2917 }
2918 }
Chet Haase91d25932013-04-11 15:24:55 -07002919
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002920 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002921 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2922 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002923
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002924 // could be null when this layer is using a layerStack
2925 // that is not visible on any display. Also can occur at
2926 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002928 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002929
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002930 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002931 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 if (hintDisplay) {
2933 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002934 }
Robert Carr2047fae2016-11-28 14:09:09 -08002935
2936 first = false;
2937 });
Mathias Agopian84300952012-11-21 16:02:13 -08002938 }
2939
2940
Mathias Agopian3559b072012-08-15 13:46:03 -07002941 /*
2942 * Perform our own transaction if needed
2943 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002944
2945 if (mLayersAdded) {
2946 mLayersAdded = false;
2947 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002948 mVisibleRegionsDirty = true;
2949 }
2950
2951 // some layers might have been removed, so
2952 // we need to update the regions they're exposing.
2953 if (mLayersRemoved) {
2954 mLayersRemoved = false;
2955 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002956 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002958 // this layer is not visible anymore
2959 // TODO: we could traverse the tree from front to back and
2960 // compute the actual visible region
2961 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002962 Region visibleReg;
2963 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002964 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002965 }
Robert Carr2047fae2016-11-28 14:09:09 -08002966 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967 }
2968
2969 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002970
Vishnu Nairde19f852018-12-18 16:11:53 -08002971 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002972 updateInputWindows();
2973 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002974 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002975
Riley Andrews03414a12014-07-01 14:22:59 -07002976 updateCursorAsync();
2977}
2978
Robert Carr720e5062018-07-30 17:45:14 -07002979void SurfaceFlinger::updateInputWindows() {
2980 ATRACE_CALL();
2981
Vishnu Nairde19f852018-12-18 16:11:53 -08002982 if (mInputFlinger == nullptr) {
2983 return;
2984 }
2985
Robert Carr720e5062018-07-30 17:45:14 -07002986 Vector<InputWindowInfo> inputHandles;
2987
2988 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2989 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002990 // When calculating the screen bounds we ignore the transparent region since it may
2991 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002992 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002993 }
2994 });
2995 mInputFlinger->setInputWindows(inputHandles);
2996}
2997
chaviwfbe5d9c2018-12-26 12:23:37 -08002998void SurfaceFlinger::executeInputWindowCommands() {
2999 if (!mInputFlinger) {
3000 return;
3001 }
3002
3003 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3004 if (transferTouchFocusCommand.fromToken != nullptr &&
3005 transferTouchFocusCommand.toToken != nullptr &&
3006 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3007 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3008 transferTouchFocusCommand.toToken);
3009 }
3010 }
3011
3012 mInputWindowCommands.clear();
3013}
3014
Riley Andrews03414a12014-07-01 14:22:59 -07003015void SurfaceFlinger::updateCursorAsync()
3016{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003017 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003018 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003019 continue;
3020 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3023 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003024 }
3025 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003026}
3027
chaviw61626f22018-11-15 16:26:27 -08003028void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3029 if (layer->hasReadyFrame()) {
3030 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3031 if (layer->shouldPresentNow(expectedPresentTime)) {
3032 bool ignored = false;
3033 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3034 }
3035 }
3036 layer->releasePendingBuffer(systemTime());
3037}
3038
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039void SurfaceFlinger::commitTransaction()
3040{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003041 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003042 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 for (const auto& l : mLayersPendingRemoval) {
3044 recordBufferingStats(l->getName().string(),
3045 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003046
3047 // We need to release the HWC layers when the Layer is removed
3048 // from the current state otherwise the HWC layer just continues
3049 // showing at its last configured state until we eventually
3050 // abandon the buffer queue.
3051 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003052 l->destroyHwcLayersForAllDisplays();
3053 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003054 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055 }
3056 mLayersPendingRemoval.clear();
3057 }
3058
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003059 // If this transaction is part of a window animation then the next frame
3060 // we composite should be considered an animation as well.
3061 mAnimCompositionPending = mAnimTransactionPending;
3062
Mathias Agopian4fec8732012-06-29 14:12:52 -07003063 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003064 // clear the "changed" flags in current state
3065 mCurrentState.colorMatrixChanged = false;
3066
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 mDrawingState.traverseInZOrder([](Layer* layer) {
3068 layer->commitChildList();
3069 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003070 mTransactionPending = false;
3071 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073}
3074
Lloyd Pique32cbe282018-10-19 13:09:22 -07003075void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003076 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003077 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003079
Lloyd Pique32cbe282018-10-19 13:09:22 -07003080 auto display = displayDevice->getCompositionDisplay();
3081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 Region aboveOpaqueLayers;
3083 Region aboveCoveredLayers;
3084 Region dirty;
3085
Mathias Agopian87baae12012-07-31 12:38:26 -07003086 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Robert Carr2047fae2016-11-28 14:09:09 -08003088 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 // start with the whole surface at its current location
3090 const Layer::State& s(layer->getDrawingState());
3091
Jesse Hall01e29052013-02-19 16:13:35 -08003092 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003093 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003094 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003095 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003096
Mathias Agopianab028732010-03-16 16:41:46 -07003097 /*
3098 * opaqueRegion: area of a surface that is fully opaque.
3099 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003101
3102 /*
3103 * visibleRegion: area of a surface that is visible on screen
3104 * and not fully transparent. This is essentially the layer's
3105 * footprint minus the opaque regions above it.
3106 * Areas covered by a translucent surface are considered visible.
3107 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003109
3110 /*
3111 * coveredRegion: area of a surface that is covered by all
3112 * visible regions above it (which includes the translucent areas).
3113 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003115
Jesse Halla8026d22012-09-25 13:25:04 -07003116 /*
3117 * transparentRegion: area of a surface that is hinted to be completely
3118 * transparent. This is only used to tell when the layer has no visible
3119 * non-transparent regions and can be removed from the layer list. It
3120 * does not affect the visibleRegion of this layer or any layers
3121 * beneath it. The hint may not be correct if apps don't respect the
3122 * SurfaceView restrictions (which, sadly, some don't).
3123 */
3124 Region transparentRegion;
3125
Mathias Agopianab028732010-03-16 16:41:46 -07003126
3127 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003128 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003129 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003133 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003134 if (!visibleRegion.isEmpty()) {
3135 // Remove the transparent area from the visible region
3136 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003137 if (tr.preserveRects()) {
3138 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003139 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003140 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003141 // transformation too complex, can't do the
3142 // transparent region optimization.
3143 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 }
Mathias Agopianab028732010-03-16 16:41:46 -07003145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146
Mathias Agopianab028732010-03-16 16:41:46 -07003147 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003149 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003150 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003151 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003152 // the opaque region is the layer's footprint
3153 opaqueRegion = visibleRegion;
3154 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
3156 }
3157
Robert Carre5f4f692018-01-12 13:12:28 -08003158 if (visibleRegion.isEmpty()) {
3159 layer->clearVisibilityRegions();
3160 return;
3161 }
3162
Mathias Agopianab028732010-03-16 16:41:46 -07003163 // Clip the covered region to the visible region
3164 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3165
3166 // Update aboveCoveredLayers for next (lower) layer
3167 aboveCoveredLayers.orSelf(visibleRegion);
3168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 // subtract the opaque region covered by the layers above us
3170 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171
3172 // compute this layer's dirty region
3173 if (layer->contentDirty) {
3174 // we need to invalidate the whole region
3175 dirty = visibleRegion;
3176 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003177 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 layer->contentDirty = false;
3179 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003180 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003181 * the exposed region consists of two components:
3182 * 1) what's VISIBLE now and was COVERED before
3183 * 2) what's EXPOSED now less what was EXPOSED before
3184 *
3185 * note that (1) is conservative, we start with the whole
3186 * visible region but only keep what used to be covered by
3187 * something -- which mean it may have been exposed.
3188 *
3189 * (2) handles areas that were not covered by anything but got
3190 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003191 */
Mathias Agopianab028732010-03-16 16:41:46 -07003192 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003193 const Region oldVisibleRegion = layer->visibleRegion;
3194 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003195 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3196 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 }
3198 dirty.subtractSelf(aboveOpaqueLayers);
3199
3200 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003201 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202
Mathias Agopianab028732010-03-16 16:41:46 -07003203 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003205
Jesse Halla8026d22012-09-25 13:25:04 -07003206 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 layer->setVisibleRegion(visibleRegion);
3208 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003209 layer->setVisibleNonTransparentRegion(
3210 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003211 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212
Mathias Agopian87baae12012-07-31 12:38:26 -07003213 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214}
3215
Chia-I Wuab0c3192017-08-01 11:29:00 -07003216void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003217 for (const auto& [token, displayDevice] : mDisplays) {
3218 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003219 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003220 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003221 }
3222 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003223}
3224
Daniel Solomon42d04562019-01-20 21:03:19 -08003225void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3226 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3227 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3228 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3229 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3230 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3231 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3232 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3233 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3234 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3235 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3236 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3237 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3238}
3239
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003242 ALOGV("handlePageFlip");
3243
Brian Andersond6927fb2016-07-23 23:37:30 -07003244 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245
Mathias Agopian4fec8732012-06-29 14:12:52 -07003246 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003248 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003249
3250 // Store the set of layers that need updates. This set must not change as
3251 // buffers are being latched, as this could result in a deadlock.
3252 // Example: Two producers share the same command stream and:
3253 // 1.) Layer 0 is latched
3254 // 2.) Layer 0 gets a new frame
3255 // 2.) Layer 1 gets a new frame
3256 // 3.) Layer 1 is latched.
3257 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3258 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003259 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003260 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003262 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3263 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003264 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003265 } else {
3266 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003268 } else {
3269 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003270 }
Robert Carr2047fae2016-11-28 14:09:09 -08003271 });
3272
Lloyd Piquef2c79392018-12-20 16:23:33 -08003273 if (!mLayersWithQueuedFrames.empty()) {
3274 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3275 // writes to Layer current state. See also b/119481871
3276 Mutex::Autolock lock(mStateLock);
3277
3278 for (auto& layer : mLayersWithQueuedFrames) {
3279 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3280 layer->useSurfaceDamage();
3281 invalidateLayerStack(layer, dirty);
3282 if (layer->isBufferLatched()) {
3283 newDataLatched = true;
3284 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003285 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003286 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003287
Alec Mouri86770e52018-09-24 22:40:58 +00003288 // Clear the renderengine fence here...
3289 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3290 // clear instead of sp::clear.
3291 getBE().flushFence = Fence::NO_FENCE;
3292
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003293 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003294
Vishnu Nairde19f852018-12-18 16:11:53 -08003295 if (visibleRegions) {
3296 // Update input window info if the layer receives its first buffer.
3297 updateInputWindows();
3298 }
3299
Dan Stoza6b9454d2014-11-07 16:00:59 -08003300 // If we will need to wake up at some time in the future to deal with a
3301 // queued frame that shouldn't be displayed during this vsync period, wake
3302 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003303 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003304 signalLayerUpdate();
3305 }
3306
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003307 // enter boot animation on first buffer latch
3308 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3309 ALOGI("Enter boot animation");
3310 mBootStage = BootStage::BOOTANIMATION;
3311 }
3312
Dan Stoza6b9454d2014-11-07 16:00:59 -08003313 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003314 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315}
3316
Mathias Agopianad456f92011-01-13 17:53:01 -08003317void SurfaceFlinger::invalidateHwcGeometry()
3318{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003319 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003320}
3321
Lloyd Pique32cbe282018-10-19 13:09:22 -07003322void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003323 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003324 auto display = displayDevice->getCompositionDisplay();
3325
Dan Stoza71433162014-02-04 16:22:36 -08003326 // We only need to actually compose the display if:
3327 // 1) It is being handled by hardware composer, which may need this to
3328 // keep its virtual display state machine in sync, or
3329 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003331 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003332 return;
3333 }
3334
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003336 base::unique_fd readyFence;
3337 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003338
3339 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003340 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341}
3342
Alec Mouri0f714832018-11-12 15:31:06 -08003343bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3344 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003345 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003346
Lloyd Pique32cbe282018-10-19 13:09:22 -07003347 auto display = displayDevice->getCompositionDisplay();
3348 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003349 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003350
3351 const Region bounds(displayState.bounds);
3352 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003353 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003354 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003355
Peiyong Lind3788632018-09-18 16:01:31 -07003356 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003357 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003358
Alec Mouri0f714832018-11-12 15:31:06 -08003359 renderengine::DisplaySettings clientCompositionDisplay;
3360 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3361 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003362
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 if (hasClientComposition) {
3364 ALOGV("hasClientComposition");
3365
Alec Mouri0f714832018-11-12 15:31:06 -08003366 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003367
3368 if (buf == nullptr) {
3369 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3370 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003371 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003372 return false;
3373 }
3374
Alec Mouri0f714832018-11-12 15:31:06 -08003375 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3376 clientCompositionDisplay.clip = displayState.scissor;
3377 const ui::Transform& displayTransform = displayState.transform;
3378 mat4 m;
3379 m[0][0] = displayTransform[0][0];
3380 m[0][1] = displayTransform[0][1];
3381 m[0][3] = displayTransform[0][2];
3382 m[1][0] = displayTransform[1][0];
3383 m[1][1] = displayTransform[1][1];
3384 m[1][3] = displayTransform[1][2];
3385 m[3][0] = displayTransform[2][0];
3386 m[3][1] = displayTransform[2][1];
3387 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003388
Alec Mouri0f714832018-11-12 15:31:06 -08003389 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003390
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003391 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003392 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003393 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003394 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003395 }
Alec Mouri0f714832018-11-12 15:31:06 -08003396 clientCompositionDisplay.outputDataspace = outputDataspace;
3397 clientCompositionDisplay.maxLuminance =
3398 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003399
Lloyd Pique441d5042018-10-18 16:49:51 -07003400 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003401 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003402 getHwComposer()
3403 .hasDisplayCapability(displayId,
3404 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003405
Peiyong Lind3788632018-09-18 16:01:31 -07003406 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003407 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3408 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003409 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003410 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003411 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003412
Mathias Agopian85d751c2012-08-29 16:59:24 -07003413 /*
3414 * and then, render the layers targeted at the framebuffer
3415 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416
Dan Stoza9e56aa02015-11-02 13:00:03 -08003417 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003418 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003419 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003420 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003421 const Region viewportRegion(displayState.viewport);
3422 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003423 ALOGV("Layer: %s", layer->getName().string());
3424 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003425 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003426 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 case HWC2::Composition::Cursor:
3428 case HWC2::Composition::Device:
3429 case HWC2::Composition::Sideband:
3430 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003431 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003432 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003433 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003434 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003435 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003436 // never clear the very first layer since we're
3437 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003438 renderengine::LayerSettings layerSettings;
3439 Region dummyRegion;
3440 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3441 layerSettings);
3442
3443 if (prepared) {
3444 layerSettings.source.buffer.buffer = nullptr;
3445 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3446 layerSettings.alpha = half(0.0);
3447 layerSettings.disableBlending = true;
3448 clientCompositionLayers.push_back(layerSettings);
3449 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003450 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003452 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003453 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003454 renderengine::LayerSettings layerSettings;
3455 bool prepared =
3456 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3457 if (prepared) {
3458 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003459 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003460 break;
3461 }
3462 default:
3463 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003464 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003465 } else {
3466 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003467 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003468 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003469 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003470
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003471 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003472 clientCompositionDisplay.clearRegion = clearRegion;
3473 if (!debugRegion.isEmpty()) {
3474 Region::const_iterator it = debugRegion.begin();
3475 Region::const_iterator end = debugRegion.end();
3476 while (it != end) {
3477 const Rect& rect = *it++;
3478 renderengine::LayerSettings layerSettings;
3479 layerSettings.source.buffer.buffer = nullptr;
3480 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3481 layerSettings.geometry.boundaries = rect.toFloatRect();
3482 layerSettings.alpha = half(1.0);
3483 clientCompositionLayers.push_back(layerSettings);
3484 }
3485 }
3486 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3487 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003488 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003489 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490}
3491
Chia-I Wu28e3a252018-09-07 12:05:02 -07003492void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003493 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003494 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495}
3496
Dan Stoza7d89d062015-04-30 13:29:25 -07003497status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003498 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003499 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003500 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003501 const sp<Layer>& parent,
3502 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003503{
Dan Stoza7d89d062015-04-30 13:29:25 -07003504 // add this layer to the current state list
3505 {
3506 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003507 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003508 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3509 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003510 return NO_MEMORY;
3511 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003512 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003513 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003514 } else if (parent == nullptr) {
3515 lbc->onRemovedFromCurrentState();
3516 } else if (parent->isRemovedFromCurrentState()) {
3517 parent->addChild(lbc);
3518 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003519 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003520 parent->addChild(lbc);
3521 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003522
Yiwei Zhang243b3782018-05-15 17:40:04 -07003523 if (gbc != nullptr) {
3524 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3525 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3526 mMaxGraphicBufferProducerListSize,
3527 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3528 mGraphicBufferProducerList.size(),
3529 mMaxGraphicBufferProducerListSize, mNumLayers);
3530 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003531 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003532 }
3533
Mathias Agopian96f08192010-06-02 23:28:45 -07003534 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003535 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003536
Dan Stoza7d89d062015-04-30 13:29:25 -07003537 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003538}
3539
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003540uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003541 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003542}
3543
Mathias Agopian3f844832013-08-07 21:24:32 -07003544uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003545 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546}
3547
Mathias Agopian3f844832013-08-07 21:24:32 -07003548uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003549 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003550}
3551
3552uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003553 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003554 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003555 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003557 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003558 }
3559 return old;
3560}
3561
Marissa Wall713b63f2018-10-17 15:42:43 -07003562bool SurfaceFlinger::flushTransactionQueues() {
3563 Mutex::Autolock _l(mStateLock);
3564 auto it = mTransactionQueues.begin();
3565 while (it != mTransactionQueues.end()) {
3566 auto& [applyToken, transactionQueue] = *it;
3567
3568 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003569 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3570 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 break;
3572 }
chaviw273171b2018-12-26 11:46:30 -08003573 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003574 transactionQueue.pop();
3575 }
3576
3577 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3578 }
3579 return mTransactionQueues.empty();
3580}
3581
chaviwca27f252018-02-06 16:46:39 -08003582bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3583 for (const ComposerState& state : states) {
3584 // Here we need to check that the interface we're given is indeed
3585 // one of our own. A malicious client could give us a nullptr
3586 // IInterface, or one of its own or even one of our own but a
3587 // different type. All these situations would cause us to crash.
3588 if (state.client == nullptr) {
3589 return true;
3590 }
3591
3592 sp<IBinder> binder = IInterface::asBinder(state.client);
3593 if (binder == nullptr) {
3594 return true;
3595 }
3596
3597 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3598 return true;
3599 }
3600 }
3601 return false;
3602}
3603
Marissa Wall17b4e452018-12-26 16:32:34 -08003604bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3605 const Vector<ComposerState>& states) {
3606 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3607 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3608 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3609 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3610 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3611 return false;
3612 }
3613
Marissa Wall713b63f2018-10-17 15:42:43 -07003614 for (const ComposerState& state : states) {
3615 const layer_state_t& s = state.state;
3616 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3617 continue;
3618 }
3619 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003621 }
3622 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003623 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003624}
3625
3626void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3627 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003628 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003629 const InputWindowCommands& inputWindowCommands,
3630 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003631 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003632 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003633
chaviwca27f252018-02-06 16:46:39 -08003634 if (containsAnyInvalidClientState(states)) {
3635 return;
3636 }
3637
Marissa Wall713b63f2018-10-17 15:42:43 -07003638 // If its TransactionQueue already has a pending TransactionState or if it is pending
3639 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003640 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3641 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003642 setTransactionFlags(eTransactionNeeded);
3643 return;
3644 }
3645
chaviw273171b2018-12-26 11:46:30 -08003646 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003647}
3648
3649void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003650 const Vector<DisplayState>& displays, uint32_t flags,
3651 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003652 uint32_t transactionFlags = 0;
3653
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003654 if (flags & eAnimation) {
3655 // For window updates that are part of an animation we must wait for
3656 // previous animation "frames" to be handled.
3657 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003658 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003659 if (CC_UNLIKELY(err != NO_ERROR)) {
3660 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003661 // caller after a few seconds.
3662 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3663 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003664 mAnimTransactionPending = false;
3665 break;
3666 }
3667 }
3668 }
3669
chaviwca27f252018-02-06 16:46:39 -08003670 for (const DisplayState& display : displays) {
3671 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003672 }
3673
Marissa Walle2ffb422018-10-12 11:33:52 -07003674 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003675 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003676 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003677 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003678 // If the state doesn't require a traversal and there are callbacks, send them now
3679 if (!(clientStateFlags & eTraversalNeeded)) {
3680 mTransactionCompletedThread.sendCallbacks();
3681 }
3682 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003683
chaviw273171b2018-12-26 11:46:30 -08003684 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3685
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003686 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3687 // anyway. This can be used as a flush mechanism for previous async transactions.
3688 // Empty animation transaction can be used to simulate back-pressure, so also force a
3689 // transaction for empty animation transactions.
3690 if (transactionFlags == 0 &&
3691 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003692 transactionFlags = eTransactionNeeded;
3693 }
3694
Mathias Agopian386aa982011-11-07 21:58:03 -08003695 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003696 if (mInterceptor->isEnabled()) {
3697 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003698 }
Irvel468051e2016-06-13 16:44:44 -07003699
Mathias Agopian386aa982011-11-07 21:58:03 -08003700 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003701 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3702 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003703 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003704
3705 // if this is a synchronous transaction, wait for it to take effect
3706 // before returning.
3707 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003708 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003709 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003710 if (flags & eAnimation) {
3711 mAnimTransactionPending = true;
3712 }
3713 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003714 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3715 if (CC_UNLIKELY(err != NO_ERROR)) {
3716 // just in case something goes wrong in SF, return to the
3717 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003718 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3719 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003720 break;
3721 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
3724}
3725
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003726uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3727 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3728 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003729
Mathias Agopiane57f2922012-08-09 16:29:12 -07003730 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003731 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3732
3733 const uint32_t what = s.what;
3734 if (what & DisplayState::eSurfaceChanged) {
3735 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3736 state.surface = s.surface;
3737 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003738 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003739 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003740 if (what & DisplayState::eLayerStackChanged) {
3741 if (state.layerStack != s.layerStack) {
3742 state.layerStack = s.layerStack;
3743 flags |= eDisplayTransactionNeeded;
3744 }
3745 }
3746 if (what & DisplayState::eDisplayProjectionChanged) {
3747 if (state.orientation != s.orientation) {
3748 state.orientation = s.orientation;
3749 flags |= eDisplayTransactionNeeded;
3750 }
3751 if (state.frame != s.frame) {
3752 state.frame = s.frame;
3753 flags |= eDisplayTransactionNeeded;
3754 }
3755 if (state.viewport != s.viewport) {
3756 state.viewport = s.viewport;
3757 flags |= eDisplayTransactionNeeded;
3758 }
3759 }
3760 if (what & DisplayState::eDisplaySizeChanged) {
3761 if (state.width != s.width) {
3762 state.width = s.width;
3763 flags |= eDisplayTransactionNeeded;
3764 }
3765 if (state.height != s.height) {
3766 state.height = s.height;
3767 flags |= eDisplayTransactionNeeded;
3768 }
3769 }
3770
Mathias Agopiane57f2922012-08-09 16:29:12 -07003771 return flags;
3772}
3773
Robert Carrd4ae7f32018-06-07 16:10:57 -07003774bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3775 IPCThreadState* ipc = IPCThreadState::self();
3776 const int pid = ipc->getCallingPid();
3777 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003778 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003779 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003780 return false;
3781 }
3782 return true;
3783}
3784
chaviwca27f252018-02-06 16:46:39 -08003785uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3786 const layer_state_t& s = composerState.state;
3787 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3788
Mathias Agopian13127d82013-03-05 17:47:11 -08003789 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003790 if (layer == nullptr) {
3791 return 0;
3792 }
3793
chaviw8b3871a2017-11-01 17:41:01 -07003794 uint32_t flags = 0;
3795
Garfield Tan8a3083e2018-12-03 13:21:07 -08003796 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003797 bool geometryAppliesWithResize =
3798 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003799
3800 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3801 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003802 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003803 layer->pushPendingState();
3804 }
3805
chaviw8b3871a2017-11-01 17:41:01 -07003806 if (what & layer_state_t::ePositionChanged) {
3807 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3808 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003809 }
chaviw8b3871a2017-11-01 17:41:01 -07003810 }
3811 if (what & layer_state_t::eLayerChanged) {
3812 // NOTE: index needs to be calculated before we update the state
3813 const auto& p = layer->getParent();
3814 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003815 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003816 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003817 mCurrentState.layersSortedByZ.removeAt(idx);
3818 mCurrentState.layersSortedByZ.add(layer);
3819 // we need traversal (state changed)
3820 // AND transaction (list changed)
3821 flags |= eTransactionNeeded|eTraversalNeeded;
3822 }
chaviw8b3871a2017-11-01 17:41:01 -07003823 } else {
3824 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003825 flags |= eTransactionNeeded|eTraversalNeeded;
3826 }
3827 }
chaviw8b3871a2017-11-01 17:41:01 -07003828 }
3829 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003830 // NOTE: index needs to be calculated before we update the state
3831 const auto& p = layer->getParent();
3832 if (p == nullptr) {
3833 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3834 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3835 mCurrentState.layersSortedByZ.removeAt(idx);
3836 mCurrentState.layersSortedByZ.add(layer);
3837 // we need traversal (state changed)
3838 // AND transaction (list changed)
3839 flags |= eTransactionNeeded|eTraversalNeeded;
3840 }
3841 } else {
3842 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3843 flags |= eTransactionNeeded|eTraversalNeeded;
3844 }
chaviw8b3871a2017-11-01 17:41:01 -07003845 }
3846 }
3847 if (what & layer_state_t::eSizeChanged) {
3848 if (layer->setSize(s.w, s.h)) {
3849 flags |= eTraversalNeeded;
3850 }
3851 }
3852 if (what & layer_state_t::eAlphaChanged) {
3853 if (layer->setAlpha(s.alpha))
3854 flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eColorChanged) {
3857 if (layer->setColor(s.color))
3858 flags |= eTraversalNeeded;
3859 }
Valerie Haued54efa2019-01-11 20:03:14 -08003860 if (what & layer_state_t::eColorAlphaChanged) {
3861 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3862 }
3863 if (what & layer_state_t::eColorDataspaceChanged) {
3864 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3865 }
Peiyong Lind3788632018-09-18 16:01:31 -07003866 if (what & layer_state_t::eColorTransformChanged) {
3867 if (layer->setColorTransform(s.colorTransform)) {
3868 flags |= eTraversalNeeded;
3869 }
3870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003872 // TODO: b/109894387
3873 //
3874 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3875 // rotation. To see the problem observe that if we have a square parent, and a child
3876 // of the same size, then we rotate the child 45 degrees around it's center, the child
3877 // must now be cropped to a non rectangular 8 sided region.
3878 //
3879 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3880 // private API, and the WindowManager only uses rotation in one case, which is on a top
3881 // level layer in which cropping is not an issue.
3882 //
3883 // However given that abuse of rotation matrices could lead to surfaces extending outside
3884 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3885 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3886 // transformations.
3887 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003888 flags |= eTraversalNeeded;
3889 }
3890 if (what & layer_state_t::eTransparentRegionChanged) {
3891 if (layer->setTransparentRegionHint(s.transparentRegion))
3892 flags |= eTraversalNeeded;
3893 }
3894 if (what & layer_state_t::eFlagsChanged) {
3895 if (layer->setFlags(s.flags, s.mask))
3896 flags |= eTraversalNeeded;
3897 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003898 if (what & layer_state_t::eCropChanged_legacy) {
3899 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003900 flags |= eTraversalNeeded;
3901 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003902 if (what & layer_state_t::eCornerRadiusChanged) {
3903 if (layer->setCornerRadius(s.cornerRadius))
3904 flags |= eTraversalNeeded;
3905 }
chaviw8b3871a2017-11-01 17:41:01 -07003906 if (what & layer_state_t::eLayerStackChanged) {
3907 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3908 // We only allow setting layer stacks for top level layers,
3909 // everything else inherits layer stack from its parent.
3910 if (layer->hasParent()) {
3911 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3912 layer->getName().string());
3913 } else if (idx < 0) {
3914 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3915 "that also does not appear in the top level layer list. Something"
3916 " has gone wrong.", layer->getName().string());
3917 } else if (layer->setLayerStack(s.layerStack)) {
3918 mCurrentState.layersSortedByZ.removeAt(idx);
3919 mCurrentState.layersSortedByZ.add(layer);
3920 // we need traversal (state changed)
3921 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003922 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003923 }
3924 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003925 if (what & layer_state_t::eDeferTransaction_legacy) {
3926 if (s.barrierHandle_legacy != nullptr) {
3927 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3928 } else if (s.barrierGbp_legacy != nullptr) {
3929 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003930 if (authenticateSurfaceTextureLocked(gbp)) {
3931 const auto& otherLayer =
3932 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003933 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003934 } else {
3935 ALOGE("Attempt to defer transaction to to an"
3936 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003937 }
3938 }
chaviw8b3871a2017-11-01 17:41:01 -07003939 // We don't trigger a traversal here because if no other state is
3940 // changed, we don't want this to cause any more work
3941 }
3942 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003943 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003944 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003945 if (!hadParent) {
3946 mCurrentState.layersSortedByZ.remove(layer);
3947 }
chaviw8b3871a2017-11-01 17:41:01 -07003948 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003949 }
chaviw8b3871a2017-11-01 17:41:01 -07003950 }
3951 if (what & layer_state_t::eReparentChildren) {
3952 if (layer->reparentChildren(s.reparentHandle)) {
3953 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003954 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003955 }
chaviw8b3871a2017-11-01 17:41:01 -07003956 if (what & layer_state_t::eDetachChildren) {
3957 layer->detachChildren();
3958 }
3959 if (what & layer_state_t::eOverrideScalingModeChanged) {
3960 layer->setOverrideScalingMode(s.overrideScalingMode);
3961 // We don't trigger a traversal here because if no other state is
3962 // changed, we don't want this to cause any more work
3963 }
Marissa Wall61c58622018-07-18 10:12:20 -07003964 if (what & layer_state_t::eTransformChanged) {
3965 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3966 }
3967 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3968 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3969 flags |= eTraversalNeeded;
3970 }
3971 if (what & layer_state_t::eCropChanged) {
3972 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3973 }
Marissa Wall861616d2018-10-22 12:52:23 -07003974 if (what & layer_state_t::eFrameChanged) {
3975 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3976 }
Marissa Wall61c58622018-07-18 10:12:20 -07003977 if (what & layer_state_t::eBufferChanged) {
3978 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eAcquireFenceChanged) {
3981 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eDataspaceChanged) {
3984 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eHdrMetadataChanged) {
3987 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3988 }
3989 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3990 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3991 }
3992 if (what & layer_state_t::eApiChanged) {
3993 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3994 }
3995 if (what & layer_state_t::eSidebandStreamChanged) {
3996 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3997 }
Robert Carr720e5062018-07-30 17:45:14 -07003998 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003999 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4000 layer->setInputInfo(s.inputInfo);
4001 flags |= eTraversalNeeded;
4002 } else {
4003 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4004 }
Robert Carr720e5062018-07-30 17:45:14 -07004005 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004006 if (what & layer_state_t::eMetadataChanged) {
4007 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4008 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004009 std::vector<sp<CallbackHandle>> callbackHandles;
4010 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4011 mTransactionCompletedThread.run();
4012 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4013 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4014 }
4015 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004016 if (what & layer_state_t::eCachedBufferChanged) {
4017 sp<GraphicBuffer> buffer =
4018 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4019 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4020 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004021 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4022 // Do not put anything that updates layer state or modifies flags after
4023 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004024 return flags;
4025}
4026
chaviw273171b2018-12-26 11:46:30 -08004027uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4028 uint32_t flags = 0;
4029 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4030 flags |= eTraversalNeeded;
4031 }
4032
4033 mInputWindowCommands.merge(inputWindowCommands);
4034 return flags;
4035}
4036
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004037status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4038 uint32_t h, PixelFormat format, uint32_t flags,
4039 LayerMetadata metadata, sp<IBinder>* handle,
4040 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004041 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004042 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004043 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004045 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004046
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004047 status_t result = NO_ERROR;
4048
4049 sp<Layer> layer;
4050
Cody Northropbc755282017-03-31 12:00:08 -06004051 String8 uniqueName = getUniqueLayerName(name);
4052
Mathias Agopian3165cc22012-08-08 19:42:09 -07004053 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004054 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004055 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4056 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004057
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004059 case ISurfaceComposerClient::eFXSurfaceBufferState:
4060 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4061 break;
chaviw13fdc492017-06-27 12:40:18 -07004062 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004063 // check if buffer size is set for color layer.
4064 if (w > 0 || h > 0) {
4065 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4066 int(w), int(h));
4067 return BAD_VALUE;
4068 }
4069
chaviw13fdc492017-06-27 12:40:18 -07004070 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004071 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004072 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004073 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004074 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004075 // check if buffer size is set for container layer.
4076 if (w > 0 || h > 0) {
4077 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4078 int(w), int(h));
4079 return BAD_VALUE;
4080 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004081 result = createContainerLayer(client,
4082 uniqueName, w, h, flags,
4083 handle, &layer);
4084 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004085 default:
4086 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 break;
4088 }
4089
Dan Stoza7d89d062015-04-30 13:29:25 -07004090 if (result != NO_ERROR) {
4091 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004092 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004093
Chia-I Wuab0c3192017-08-01 11:29:00 -07004094 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4095 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004096 if (metadata.has(METADATA_WINDOW_TYPE)) {
4097 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4098 if (windowType == 441731) {
4099 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4100 layer->setPrimaryDisplayOnly();
4101 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004102 }
4103
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004104 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004105
Robert Carrb89ea9d2018-12-10 13:01:14 -08004106 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4107 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4108 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004109 if (result != NO_ERROR) {
4110 return result;
4111 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004112 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004113
4114 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004115 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116}
4117
Cody Northropbc755282017-03-31 12:00:08 -06004118String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4119{
4120 bool matchFound = true;
4121 uint32_t dupeCounter = 0;
4122
4123 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4124 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4125
Dan Stoza436ccf32018-06-21 12:10:12 -07004126 // Grab the state lock since we're accessing mCurrentState
4127 Mutex::Autolock lock(mStateLock);
4128
Cody Northropbc755282017-03-31 12:00:08 -06004129 // Loop over layers until we're sure there is no matching name
4130 while (matchFound) {
4131 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004132 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004133 if (layer->getName() == uniqueName) {
4134 matchFound = true;
4135 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4136 }
4137 });
4138 }
4139
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004140 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4141 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004142
4143 return uniqueName;
4144}
4145
Marissa Wallfd668622018-05-10 10:21:13 -07004146status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4147 uint32_t w, uint32_t h, uint32_t flags,
4148 PixelFormat& format, sp<IBinder>* handle,
4149 sp<IGraphicBufferProducer>* gbp,
4150 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004152 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 case PIXEL_FORMAT_TRANSPARENT:
4154 case PIXEL_FORMAT_TRANSLUCENT:
4155 format = PIXEL_FORMAT_RGBA_8888;
4156 break;
4157 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004158 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159 break;
4160 }
4161
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004162 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004163 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004164 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004165 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004166 *handle = layer->getHandle();
4167 *gbp = layer->getProducer();
4168 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004170
Marissa Wallfd668622018-05-10 10:21:13 -07004171 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004172 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173}
4174
Marissa Wall61c58622018-07-18 10:12:20 -07004175status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4176 uint32_t w, uint32_t h, uint32_t flags,
4177 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004178 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004179 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004180 *handle = layer->getHandle();
4181 *outLayer = layer;
4182
4183 return NO_ERROR;
4184}
4185
chaviw13fdc492017-06-27 12:40:18 -07004186status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004187 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004188 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004190 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004191 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004192 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004193}
4194
Robert Carr6b3f6c52018-08-13 13:05:17 -07004195status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4196 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4197 sp<IBinder>* handle, sp<Layer>* outLayer)
4198{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004199 *outLayer =
4200 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004201 *handle = (*outLayer)->getHandle();
4202 return NO_ERROR;
4203}
4204
4205
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004206void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004207 mLayersPendingRemoval.add(layer);
4208 mLayersRemoved = true;
4209 setTransactionFlags(eTransactionNeeded);
4210}
4211
Robert Carr695d5282018-12-18 15:27:58 -08004212void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004213{
Robert Carr2e102c92018-10-23 12:11:15 -07004214 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004215 // If a layer has a parent, we allow it to out-live it's handle
4216 // with the idea that the parent holds a reference and will eventually
4217 // be cleaned up. However no one cleans up the top-level so we do so
4218 // here.
4219 if (layer->getParent() == nullptr) {
4220 mCurrentState.layersSortedByZ.remove(layer);
4221 }
4222 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004223 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004224}
4225
Mathias Agopianb60314a2012-04-10 22:09:54 -07004226// ---------------------------------------------------------------------------
4227
Andy McFadden13a082e2012-08-24 10:16:42 -07004228void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004229 const auto display = getDefaultDisplayDeviceLocked();
4230 if (!display) return;
4231
4232 const sp<IBinder> token = display->getDisplayToken().promote();
4233 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004234
Jesse Hall01e29052013-02-19 16:13:35 -08004235 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004236 Vector<ComposerState> state;
4237 Vector<DisplayState> displays;
4238 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004239 d.what = DisplayState::eDisplayProjectionChanged |
4240 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004241 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004242 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004243 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004244 d.frame.makeInvalid();
4245 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004246 d.width = 0;
4247 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004248 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004249 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004250
Dominik Laskowskie9774092018-12-11 10:04:24 -08004251 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004252
Dominik Laskowski83b88212018-12-11 13:34:06 -08004253 const nsecs_t vsyncPeriod = getVsyncPeriod();
4254 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004255
Brian Andersond0010582017-03-07 13:20:31 -08004256 // Use phase of 0 since phase is not known.
4257 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004258 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004259 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004260}
4261
4262void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004263 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004264 postMessageAsync(
4265 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004266}
4267
Dominik Laskowskie9774092018-12-11 10:04:24 -08004268void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004269 if (display->isVirtual()) {
4270 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004271 return;
4272 }
4273
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 const auto displayId = display->getId();
4275 LOG_ALWAYS_FATAL_IF(!displayId);
4276
Dominik Laskowski34157762018-10-31 13:07:19 -07004277 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278
4279 int currentMode = display->getPowerMode();
4280 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 return;
4282 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284 display->setPowerMode(mode);
4285
Lloyd Pique4dccc412018-01-22 17:21:36 -08004286 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004287 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004288 }
4289
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004290 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004291 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004294 if (mUseScheduler) {
4295 mScheduler->onScreenAcquired(mAppConnectionHandle);
4296 } else {
4297 mEventThread->onScreenAcquired();
4298 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004299 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004302 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004303 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004304 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004305
4306 struct sched_param param = {0};
4307 param.sched_priority = 1;
4308 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4309 ALOGW("Couldn't set SCHED_FIFO on display on");
4310 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004311 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004312 // Turn off the display
4313 struct sched_param param = {0};
4314 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4315 ALOGW("Couldn't set SCHED_OTHER on display off");
4316 }
4317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004319 if (mUseScheduler) {
4320 mScheduler->disableHardwareVsync(true);
4321 } else {
4322 disableHardwareVsync(true); // also cancels any in-progress resync
4323 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004324 if (mUseScheduler) {
4325 mScheduler->onScreenReleased(mAppConnectionHandle);
4326 } else {
4327 mEventThread->onScreenReleased();
4328 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004329 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004330
Dominik Laskowski075d3172018-05-24 15:50:06 -07004331 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004332 mVisibleRegionsDirty = true;
4333 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004334 } else if (mode == HWC_POWER_MODE_DOZE ||
4335 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004336 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004337 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004339 if (mUseScheduler) {
4340 mScheduler->onScreenAcquired(mAppConnectionHandle);
4341 } else {
4342 mEventThread->onScreenAcquired();
4343 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004344 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004345 }
4346 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4347 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004348 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004349 if (mUseScheduler) {
4350 mScheduler->disableHardwareVsync(true);
4351 } else {
4352 disableHardwareVsync(true); // also cancels any in-progress resync
4353 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004354 if (mUseScheduler) {
4355 mScheduler->onScreenReleased(mAppConnectionHandle);
4356 } else {
4357 mEventThread->onScreenReleased();
4358 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004359 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004360 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004361 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004362 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004363 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004364 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004365
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004366 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004367 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004368 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004369 // Update refresh rate stats.
4370 mRefreshRateStats->setPowerMode(mode);
4371 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004372 }
4373
Dominik Laskowski34157762018-10-31 13:07:19 -07004374 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004375}
4376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004377void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004378 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 const auto display = getDisplayDevice(displayToken);
4380 if (!display) {
4381 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4382 displayToken.get());
4383 } else if (display->isVirtual()) {
4384 ALOGW("Attempt to set power mode %d for virtual display", mode);
4385 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004386 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004387 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004388 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004389}
4390
4391// ---------------------------------------------------------------------------
4392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4394 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004395 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004396
Mathias Agopianbd115332013-04-18 16:41:04 -07004397 IPCThreadState* ipc = IPCThreadState::self();
4398 const int pid = ipc->getCallingPid();
4399 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004400
Mathias Agopianbd115332013-04-18 16:41:04 -07004401 if ((uid != AID_SHELL) &&
4402 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4404 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004405 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004406 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004407 // (this would indicate SF is stuck, but we want to be able to
4408 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004409 status_t err = mStateLock.timedLock(s2ns(1));
4410 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004411 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412 StringAppendF(&result,
4413 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4414 "(no locks held)\n",
4415 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004416 }
4417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004419
Dominik Laskowskic2867142019-01-21 11:33:38 -08004420 static const std::unordered_map<std::string, Dumper> dumpers = {
4421 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4422 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4423 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4424 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4425 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4426 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4427 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4428 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4429 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4430 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4431 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4432 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4433 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004434 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004435 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4436 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004437
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004439
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4441 (it->second)(args, asProto, result);
4442 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004443 if (asProto) {
4444 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4445 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4446 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004447 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004448 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004449 }
4450
Mathias Agopian9795c422009-08-26 16:36:26 -07004451 if (locked) {
4452 mStateLock.unlock();
4453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004456 return NO_ERROR;
4457}
4458
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 mCurrentState.traverseInZOrder(
4461 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004462}
4463
Dominik Laskowskic2867142019-01-21 11:33:38 -08004464void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004465 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004466
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467 if (args.size() > 1) {
4468 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004469 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004470 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004471 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004472 }
Robert Carr2047fae2016-11-28 14:09:09 -08004473 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004474 } else {
4475 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004476 }
4477}
4478
Dominik Laskowskic2867142019-01-21 11:33:38 -08004479void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004480 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004481 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004482 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004483 }
Robert Carr2047fae2016-11-28 14:09:09 -08004484 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004485
Svetoslavd85084b2014-03-20 10:28:31 -07004486 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004487}
4488
Dominik Laskowskic2867142019-01-21 11:33:38 -08004489void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4490 mTimeStats->parseArgs(asProto, args, result);
4491}
4492
Jamie Gennis6547ff42013-07-16 20:12:42 -07004493// This should only be called from the main thread. Otherwise it would need
4494// the lock and should use mCurrentState rather than mDrawingState.
4495void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004496 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004497 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004498 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004499
4500 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4501}
4502
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004504 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004505
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 if (isLayerTripleBufferingDisabled())
4507 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4510 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4511 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4512 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4513 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4514 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004515 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004516}
4517
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004518void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004519 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004520 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004521 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004522 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004523
4524 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4525
4526 if (mUseScheduler) {
4527 mScheduler->dump(mAppConnectionHandle, result);
4528 } else {
4529 mEventThread->dump(result);
4530 }
4531}
4532
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4534 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004535 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4536 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004537 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004538 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004540 }
David Sodman4a36e932017-11-07 14:29:47 -08004541 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004542 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004543 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4545 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004546}
4547
Dan Stozae77c7662016-05-13 11:37:28 -07004548void SurfaceFlinger::recordBufferingStats(const char* layerName,
4549 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004550 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4551 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004552 for (const auto& segment : history) {
4553 if (!segment.usedThirdBuffer) {
4554 stats.twoBufferTime += segment.totalTime;
4555 }
4556 if (segment.occupancyAverage < 1.0f) {
4557 stats.doubleBufferedTime += segment.totalTime;
4558 } else if (segment.occupancyAverage < 2.0f) {
4559 stats.tripleBufferedTime += segment.totalTime;
4560 }
4561 ++stats.numSegments;
4562 stats.totalTime += segment.totalTime;
4563 }
4564}
4565
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4567 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004568
4569 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4570 const size_t count = currentLayers.size();
4571 for (size_t i=0 ; i<count ; i++) {
4572 currentLayers[i]->dumpFrameEvents(result);
4573 }
4574}
4575
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004577 result.append("Buffering stats:\n");
4578 result.append(" [Layer name] <Active time> <Two buffer> "
4579 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004580 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004581 typedef std::tuple<std::string, float, float, float> BufferTuple;
4582 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004583 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004584 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004585 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004586 if (stats.numSegments == 0) {
4587 continue;
4588 }
4589 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4590 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4591 stats.totalTime;
4592 float doubleBufferRatio = static_cast<float>(
4593 stats.doubleBufferedTime) / stats.totalTime;
4594 float tripleBufferRatio = static_cast<float>(
4595 stats.tripleBufferedTime) / stats.totalTime;
4596 sorted.insert({activeTime, {name, twoBufferRatio,
4597 doubleBufferRatio, tripleBufferRatio}});
4598 }
4599 for (const auto& sortedPair : sorted) {
4600 float activeTime = sortedPair.first;
4601 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4603 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004604 }
4605 result.append("\n");
4606}
4607
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004610 const auto displayId = display->getId();
4611 if (!displayId) {
4612 continue;
4613 }
4614 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004615 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004616 continue;
4617 }
4618
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 StringAppendF(&result,
4620 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4621 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004622 uint8_t port;
4623 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004624 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 result.append("no identification data\n");
4626 continue;
4627 }
4628
4629 if (!isEdid(data)) {
4630 result.append("unknown identification data: ");
4631 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004633 }
4634 result.append("\n");
4635 continue;
4636 }
4637
4638 const auto edid = parseEdid(data);
4639 if (!edid) {
4640 result.append("invalid EDID: ");
4641 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004643 }
4644 result.append("\n");
4645 continue;
4646 }
4647
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649 result.append(edid->displayName.data(), edid->displayName.length());
4650 result.append("\"\n");
4651 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652}
4653
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4655 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4656 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4657 StringAppendF(&result, "DisplayColorSetting: %s\n",
4658 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004659
4660 // TODO: print out if wide-color mode is active or not
4661
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004662 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004663 const auto displayId = display->getId();
4664 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004665 continue;
4666 }
4667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004669 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004670 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004672 }
4673
Lloyd Pique32cbe282018-10-19 13:09:22 -07004674 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, " Current color mode: %s (%d)\n",
4676 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 }
4678 result.append("\n");
4679}
4680
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004682 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004683 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4684 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004685 continue;
4686 }
4687
Dominik Laskowski05275f12018-11-01 15:03:24 -07004688 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4690 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004691 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004692 compositionInfo.dump(result, nullptr);
4693 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004694 }
4695 }
David Sodman7e4ae112018-02-09 15:02:28 -08004696}
4697
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004698LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004699 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004700 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4701 const State& state = useDrawing ? mDrawingState : mCurrentState;
4702 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004703 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004704 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004705 });
4706
4707 return layersProto;
4708}
4709
Lloyd Pique32cbe282018-10-19 13:09:22 -07004710LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004711 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004712
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004713 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004714 resolution->set_w(displayDevice.getWidth());
4715 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004716
Lloyd Pique32cbe282018-10-19 13:09:22 -07004717 auto display = displayDevice.getCompositionDisplay();
4718 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004719
Lloyd Pique32cbe282018-10-19 13:09:22 -07004720 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4721 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4722 layersProto.set_global_transform(displayState.orientation);
4723
4724 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004725 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004726 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004727 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004728 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004729 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004730 }
4731 });
4732
4733 return layersProto;
4734}
4735
Dominik Laskowskic2867142019-01-21 11:33:38 -08004736void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4737 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 Colorizer colorizer(colorize);
4739
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004740 // figure out if we're stuck somewhere
4741 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4744
4745 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004746 * Dump library configuration.
4747 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748
4749 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004750 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004752 appendSfConfigString(result);
4753 appendUiConfigString(result);
4754 appendGuiConfigString(result);
4755 result.append("\n");
4756
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004757 result.append("\nDisplay identification data:\n");
4758 dumpDisplayIdentificationData(result);
4759
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004760 result.append("\nWide-Color information:\n");
4761 dumpWideColorInfo(result);
4762
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004764 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004766 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004767 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004768
Andy McFadden41d67d72014-04-25 16:58:34 -07004769 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004770 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004771 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004772 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004773 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004774
Dan Stozab90cf072015-03-05 11:05:59 -08004775 dumpStaticScreenStats(result);
4776 result.append("\n");
4777
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004779
Dan Stozae77c7662016-05-13 11:37:28 -07004780 dumpBufferingStats(result);
4781
Andy McFadden4803b742012-09-24 19:07:20 -07004782 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783 * Dump the visible layer list
4784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4787 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4788 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004790
Chia-I Wu2f884132018-09-13 15:17:58 -07004791 {
4792 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4793 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004795 result.append("\n");
4796 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797
David Sodman7e4ae112018-02-09 15:02:28 -08004798 result.append("\nFrame-Composition information:\n");
4799 dumpFrameCompositionInfo(result);
4800 result.append("\n");
4801
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004803 * Dump Display state
4804 */
4805
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004806 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004807 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004808 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004809 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004810 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004811 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004812 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004813
4814 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004815 * Dump SurfaceFlinger global state
4816 */
4817
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004818 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004819 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004821
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004822 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004823
Dominik Laskowski075d3172018-05-24 15:50:06 -07004824 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004825 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4826 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4828 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004829 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 StringAppendF(&result,
4831 " transaction-flags : %08x\n"
4832 " gpu_to_cpu_unsupported : %d\n",
4833 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004834
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004835 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004836 displayId && getHwComposer().isConnected(*displayId)) {
4837 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result,
4839 " refresh-rate : %f fps\n"
4840 " x-dpi : %f\n"
4841 " y-dpi : %f\n",
4842 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4843 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
Dan Stozae22aec72016-08-01 13:20:59 -07004848 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004849 * Tracing state
4850 */
4851 mTracing.dump(result);
4852 result.append("\n");
4853
4854 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004855 * HWC layer minidump
4856 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004857 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004858 const auto displayId = display->getId();
4859 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004860 continue;
4861 }
4862
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004864 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004865 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004866 result.append("\n");
4867 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004868
4869 /*
4870 * Dump HWComposer state
4871 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004872 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004873 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004874 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004875 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004877 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878
4879 /*
4880 * Dump gralloc state
4881 */
4882 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4883 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004884
4885 /*
4886 * Dump VrFlinger state if in use.
4887 */
4888 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4889 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004890 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004891 result.append("\n");
4892 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004893
4894 /**
4895 * Scheduler dump state.
4896 */
4897 if (mUseScheduler) {
4898 result.append("\nScheduler state:\n");
4899 result.append(mScheduler->doDump() + "\n");
4900 result.append(mRefreshRateStats->doDump() + "\n");
4901 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004902}
4903
Dominik Laskowski075d3172018-05-24 15:50:06 -07004904const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004905 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004906 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004907 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004908 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004909 }
4910 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004911
Dominik Laskowski34157762018-10-31 13:07:19 -07004912 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004913 static const Vector<sp<Layer>> empty;
4914 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004915}
4916
Keun young Park63f165f2012-08-31 10:53:36 -07004917bool SurfaceFlinger::startDdmConnection()
4918{
4919 void* libddmconnection_dso =
4920 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4921 if (!libddmconnection_dso) {
4922 return false;
4923 }
4924 void (*DdmConnection_start)(const char* name);
4925 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004926 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004927 if (!DdmConnection_start) {
4928 dlclose(libddmconnection_dso);
4929 return false;
4930 }
4931 (*DdmConnection_start)(getServiceName());
4932 return true;
4933}
4934
Chia-I Wu28f320b2018-05-03 11:02:56 -07004935void SurfaceFlinger::updateColorMatrixLocked() {
4936 mat4 colorMatrix;
4937 if (mGlobalSaturationFactor != 1.0f) {
4938 // Rec.709 luma coefficients
4939 float3 luminance{0.213f, 0.715f, 0.072f};
4940 luminance *= 1.0f - mGlobalSaturationFactor;
4941 mat4 saturationMatrix = mat4(
4942 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4943 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4944 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4945 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4946 );
4947 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4948 } else {
4949 colorMatrix = mClientColorMatrix * mDaltonizer();
4950 }
4951
4952 if (mCurrentState.colorMatrix != colorMatrix) {
4953 mCurrentState.colorMatrix = colorMatrix;
4954 mCurrentState.colorMatrixChanged = true;
4955 setTransactionFlags(eTransactionNeeded);
4956 }
4957}
4958
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004959status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960#pragma clang diagnostic push
4961#pragma clang diagnostic error "-Wswitch-enum"
4962 switch (static_cast<ISurfaceComposerTag>(code)) {
4963 // These methods should at minimum make sure that the client requested
4964 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004965 case BOOT_FINISHED:
4966 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 case CREATE_DISPLAY:
4968 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004969 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 case GET_ACTIVE_COLOR_MODE:
4971 case GET_ANIMATION_FRAME_STATS:
4972 case GET_HDR_CAPABILITIES:
4973 case SET_ACTIVE_CONFIG:
4974 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004975 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004976 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004977 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004978 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4979 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004980 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4981 IPCThreadState* ipc = IPCThreadState::self();
4982 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4983 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004984 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 }
Robert Carr1db73f62016-12-21 12:58:51 -08004986 return OK;
4987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004989 IPCThreadState* ipc = IPCThreadState::self();
4990 const int pid = ipc->getCallingPid();
4991 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4993 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004994 return PERMISSION_DENIED;
4995 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004996 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 // Used by apps to hook Choreographer to SurfaceFlinger.
4999 case CREATE_DISPLAY_EVENT_CONNECTION:
5000 // The following calls are currently used by clients that do not
5001 // request necessary permissions. However, they do not expose any secret
5002 // information, so it is OK to pass them.
5003 case AUTHENTICATE_SURFACE:
5004 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005005 case GET_PHYSICAL_DISPLAY_IDS:
5006 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005008 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005009 case GET_DISPLAY_CONFIGS:
5010 case GET_DISPLAY_STATS:
5011 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5012 // Calling setTransactionState is safe, because you need to have been
5013 // granted a reference to Client* and Handle* to do anything with it.
5014 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005015 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005016 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005017 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005018 case GET_PROTECTED_CONTENT_SUPPORT:
5019 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005020 case UNCACHE_BUFFER:
5021 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 return OK;
5023 }
5024 case CAPTURE_LAYERS:
5025 case CAPTURE_SCREEN: {
5026 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005027 IPCThreadState* ipc = IPCThreadState::self();
5028 const int pid = ipc->getCallingPid();
5029 const int uid = ipc->getCallingUid();
5030 if ((uid != AID_GRAPHICS) &&
5031 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5032 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5033 return PERMISSION_DENIED;
5034 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005035 return OK;
5036 }
5037 // The following codes are deprecated and should never be allowed to access SF.
5038 case CONNECT_DISPLAY_UNUSED:
5039 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5040 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5041 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005044
5045 // These codes are used for the IBinder protocol to either interrogate the recipient
5046 // side of the transaction for its canonical interface descriptor or to dump its state.
5047 // We let them pass by default.
5048 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5049 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5050 code == IBinder::SYSPROPS_TRANSACTION) {
5051 return OK;
5052 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005053 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005055 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005056 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5057 return OK;
5058 }
5059 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5060 return PERMISSION_DENIED;
5061#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005062}
5063
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5065 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005066 status_t credentialCheck = CheckTransactCodeCredentials(code);
5067 if (credentialCheck != OK) {
5068 return credentialCheck;
5069 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005071 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5072 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005073 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005074 IPCThreadState* ipc = IPCThreadState::self();
5075 const int uid = ipc->getCallingUid();
5076 if (CC_UNLIKELY(uid != AID_SYSTEM
5077 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005078 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005079 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005080 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005081 return PERMISSION_DENIED;
5082 }
5083 int n;
5084 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005085 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005086 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005087 return NO_ERROR;
5088 case 1002: // SHOW_UPDATES
5089 n = data.readInt32();
5090 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005091 invalidateHwcGeometry();
5092 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005095 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005098 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005099 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005100 setTransactionFlags(
5101 eTransactionNeeded|
5102 eDisplayTransactionNeeded|
5103 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005104 return NO_ERROR;
5105 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005106 case 1006:{ // send empty update
5107 signalRefresh();
5108 return NO_ERROR;
5109 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005110 case 1008: // toggle use of hw composer
5111 n = data.readInt32();
5112 mDebugDisableHWC = n ? 1 : 0;
5113 invalidateHwcGeometry();
5114 repaintEverything();
5115 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005116 case 1009: // toggle use of transform hint
5117 n = data.readInt32();
5118 mDebugDisableTransformHint = n ? 1 : 0;
5119 invalidateHwcGeometry();
5120 repaintEverything();
5121 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005123 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005124 reply->writeInt32(0);
5125 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005126 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005127 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005128 return NO_ERROR;
5129 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005130 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005131 if (!display) {
5132 return NAME_NOT_FOUND;
5133 }
5134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005135 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005136 return NO_ERROR;
5137 }
5138 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005139 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005140 // daltonize
5141 n = data.readInt32();
5142 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005143 case 1:
5144 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5145 break;
5146 case 2:
5147 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5148 break;
5149 case 3:
5150 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5151 break;
5152 default:
5153 mDaltonizer.setType(ColorBlindnessType::None);
5154 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005155 }
5156 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005157 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005158 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005159 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005160 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005161
5162 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005163 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005164 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005165 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005166 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005167 // apply a color matrix
5168 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005169 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005170 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005171 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005173 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005174 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005177 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005179
5180 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5181 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005182 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005183 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5184 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5185 }
5186
Chia-I Wu28f320b2018-05-03 11:02:56 -07005187 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005188 return NO_ERROR;
5189 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005190 // This is an experimental interface
5191 // Needs to be shifted to proper binder interface when we productize
5192 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005193 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005194 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005195 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005196 return NO_ERROR;
5197 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005198 case 1017: {
5199 n = data.readInt32();
5200 mForceFullDamage = static_cast<bool>(n);
5201 return NO_ERROR;
5202 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005203 case 1018: { // Modify Choreographer's phase offset
5204 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005205 if (mUseScheduler) {
5206 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5207 } else {
5208 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5209 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005210 return NO_ERROR;
5211 }
5212 case 1019: { // Modify SurfaceFlinger's phase offset
5213 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005214 if (mUseScheduler) {
5215 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5216 } else {
5217 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5218 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005219 return NO_ERROR;
5220 }
Irvel468051e2016-06-13 16:44:44 -07005221 case 1020: { // Layer updates interceptor
5222 n = data.readInt32();
5223 if (n) {
5224 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005225 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005226 }
5227 else{
5228 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005229 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005230 }
5231 return NO_ERROR;
5232 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005233 case 1021: { // Disable HWC virtual displays
5234 n = data.readInt32();
5235 mUseHwcVirtualDisplays = !n;
5236 return NO_ERROR;
5237 }
Romain Guy0147a172017-06-01 13:53:56 -07005238 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005239 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005240 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005241
Chia-I Wu28f320b2018-05-03 11:02:56 -07005242 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005243 return NO_ERROR;
5244 }
Romain Guy54f154a2017-10-24 21:40:32 +01005245 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005246 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005247 invalidateHwcGeometry();
5248 repaintEverything();
5249 return NO_ERROR;
5250 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005251 // Deprecate, use 1030 to check whether the device is color managed.
5252 case 1024: {
5253 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005254 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005255 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005256 n = data.readInt32();
5257 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005258 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005259 mTracing.enable();
5260 doTracing("tracing.enable");
5261 reply->writeInt32(NO_ERROR);
5262 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005263 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005264 status_t err = mTracing.disable();
5265 reply->writeInt32(err);
5266 }
5267 return NO_ERROR;
5268 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005269 case 1026: { // Get layer tracing status
5270 reply->writeBool(mTracing.isEnabled());
5271 return NO_ERROR;
5272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005273 // Is a DisplayColorSetting supported?
5274 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005275 const auto display = getDefaultDisplayDevice();
5276 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005277 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005278 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005279
5280 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5281 switch (setting) {
5282 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005283 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005284 break;
5285 case DisplayColorSetting::UNMANAGED:
5286 reply->writeBool(true);
5287 break;
5288 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005289 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 break;
5291 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005292 reply->writeBool(
5293 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005294 break;
5295 }
5296 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005297 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005298 // Is VrFlinger active?
5299 case 1028: {
5300 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005301 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005302 return NO_ERROR;
5303 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005304 // Is device color managed?
5305 case 1030: {
5306 reply->writeBool(useColorManagement);
5307 return NO_ERROR;
5308 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005309 // Override default composition data space
5310 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5311 // && adb shell stop zygote && adb shell start zygote
5312 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5313 // adb shell stop zygote && adb shell start zygote
5314 case 1031: {
5315 Mutex::Autolock _l(mStateLock);
5316 n = data.readInt32();
5317 if (n) {
5318 n = data.readInt32();
5319 if (n) {
5320 Dataspace dataspace = static_cast<Dataspace>(n);
5321 if (!validateCompositionDataspace(dataspace)) {
5322 return BAD_VALUE;
5323 }
5324 mDefaultCompositionDataspace = dataspace;
5325 }
5326 n = data.readInt32();
5327 if (n) {
5328 Dataspace dataspace = static_cast<Dataspace>(n);
5329 if (!validateCompositionDataspace(dataspace)) {
5330 return BAD_VALUE;
5331 }
5332 mWideColorGamutCompositionDataspace = dataspace;
5333 }
5334 } else {
5335 // restore composition data space.
5336 mDefaultCompositionDataspace = defaultCompositionDataspace;
5337 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5338 }
5339 return NO_ERROR;
5340 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005341 }
5342 }
5343 return err;
5344}
5345
Steven Thomas6d8110b2017-08-31 18:24:21 -07005346void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005347 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005348 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005349}
5350
Ana Krulec7d1d6832018-12-27 11:10:09 -08005351void SurfaceFlinger::repaintEverythingForHWC() {
5352 mRepaintEverything = true;
5353 mEventQueue->invalidateForHWC();
5354}
5355
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005356// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5357class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005358public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5360 ~WindowDisconnector() {
5361 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005362 }
5363
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364private:
5365 ANativeWindow* mWindow;
5366 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005367};
5368
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005369status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005370 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5371 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005372 uint32_t reqWidth, uint32_t reqHeight,
5373 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005374 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005375 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005378
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005379 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5380
Chia-I Wu20261cb2018-08-23 12:55:44 -07005381 sp<DisplayDevice> display;
5382 {
5383 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005384
Chia-I Wu20261cb2018-08-23 12:55:44 -07005385 display = getDisplayDeviceLocked(displayToken);
5386 if (!display) return BAD_VALUE;
5387
Chia-I Wucb023152018-08-28 12:57:23 -07005388 // set the requested width/height to the logical display viewport size
5389 // by default
5390 if (reqWidth == 0 || reqHeight == 0) {
5391 reqWidth = uint32_t(display->getViewport().width());
5392 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005393 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005394 }
5395
Peiyong Lin0e003c92018-09-17 11:09:51 -07005396 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5397 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005398
5399 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005400 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005401 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5402 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005403}
5404
5405status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005406 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5407 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005408 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005409 ATRACE_CALL();
5410
5411 class LayerRenderArea : public RenderArea {
5412 public:
Robert Carr578038f2018-03-09 12:25:24 -08005413 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5415 bool childrenOnly)
5416 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005417 mLayer(layer),
5418 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005419 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005420 mFlinger(flinger),
5421 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005422 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005423 Rect getBounds() const override {
5424 const Layer::State& layerState(mLayer->getDrawingState());
5425 return mLayer->getBufferSize(layerState);
5426 }
Marissa Wall61c58622018-07-18 10:12:20 -07005427 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005429 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005430 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005432 }
chaviwa76b2712017-09-20 12:02:26 -07005433 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005434 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005435 Rect getSourceCrop() const override {
5436 if (mCrop.isEmpty()) {
5437 return getBounds();
5438 } else {
5439 return mCrop;
5440 }
5441 }
Robert Carr578038f2018-03-09 12:25:24 -08005442 class ReparentForDrawing {
5443 public:
5444 const sp<Layer>& oldParent;
5445 const sp<Layer>& newParent;
5446
5447 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5448 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005449 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005450 }
Robert Carr15eae092018-03-23 13:43:53 -07005451 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005452 };
5453
5454 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005455 const Rect sourceCrop = getSourceCrop();
5456 // no need to check rotation because there is none
5457 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5458 sourceCrop.height() != getReqHeight();
5459
Robert Carr578038f2018-03-09 12:25:24 -08005460 if (!mChildrenOnly) {
5461 mTransform = mLayer->getTransform().inverse();
5462 drawLayers();
5463 } else {
5464 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005465 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005466 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5467 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005468
5469 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5470 drawLayers();
5471 }
5472 }
chaviwa76b2712017-09-20 12:02:26 -07005473
chaviwa76b2712017-09-20 12:02:26 -07005474 private:
chaviw7206d492017-11-10 16:16:12 -08005475 const sp<Layer> mLayer;
5476 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005477
5478 // In the "childrenOnly" case we reparent the children to a screenshot
5479 // layer which has no properties set and which does not draw.
5480 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005481 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005482 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005483
5484 SurfaceFlinger* mFlinger;
5485 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005486 };
5487
5488 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5489 auto parent = layerHandle->owner.promote();
5490
Robert Carr2e102c92018-10-23 12:11:15 -07005491 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005492 ALOGE("captureLayers called with a removed parent");
5493 return NAME_NOT_FOUND;
5494 }
5495
Robert Carr578038f2018-03-09 12:25:24 -08005496 const int uid = IPCThreadState::self()->getCallingUid();
5497 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005498 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005499 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5500 return PERMISSION_DENIED;
5501 }
5502
chaviw7206d492017-11-10 16:16:12 -08005503 Rect crop(sourceCrop);
5504 if (sourceCrop.width() <= 0) {
5505 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005506 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005507 }
5508
5509 if (sourceCrop.height() <= 0) {
5510 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005511 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005512 }
5513
5514 int32_t reqWidth = crop.width() * frameScale;
5515 int32_t reqHeight = crop.height() * frameScale;
5516
Chia-I Wu20261cb2018-08-23 12:55:44 -07005517 // really small crop or frameScale
5518 if (reqWidth <= 0) {
5519 reqWidth = 1;
5520 }
5521 if (reqHeight <= 0) {
5522 reqHeight = 1;
5523 }
5524
Peiyong Lin0e003c92018-09-17 11:09:51 -07005525 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005526
Robert Carr578038f2018-03-09 12:25:24 -08005527 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005528 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5529 if (!layer->isVisible()) {
5530 return;
Robert Carr578038f2018-03-09 12:25:24 -08005531 } else if (childrenOnly && layer == parent.get()) {
5532 return;
chaviwa76b2712017-09-20 12:02:26 -07005533 }
5534 visitor(layer);
5535 });
5536 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005537 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005538}
5539
5540status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5541 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005542 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005543 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005544 bool useIdentityTransform) {
5545 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005546
Peiyong Lin0e003c92018-09-17 11:09:51 -07005547 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005548 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5549 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005550 *outBuffer =
5551 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5552 static_cast<android_pixel_format>(reqPixelFormat), 1,
5553 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554
5555 // This mutex protects syncFd and captureResult for communication of the return values from the
5556 // main thread back to this Binder thread
5557 std::mutex captureMutex;
5558 std::condition_variable captureCondition;
5559 std::unique_lock<std::mutex> captureLock(captureMutex);
5560 int syncFd = -1;
5561 std::optional<status_t> captureResult;
5562
Robert Carr03480e22018-01-04 16:02:06 -08005563 const int uid = IPCThreadState::self()->getCallingUid();
5564 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5565
Dominik Laskowski8c001672018-05-30 16:52:06 -07005566 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 // If there is a refresh pending, bug out early and tell the binder thread to try again
5568 // after the refresh.
5569 if (mRefreshPending) {
5570 ATRACE_NAME("Skipping screenshot for now");
5571 std::unique_lock<std::mutex> captureLock(captureMutex);
5572 captureResult = std::make_optional<status_t>(EAGAIN);
5573 captureCondition.notify_one();
5574 return;
5575 }
5576
5577 status_t result = NO_ERROR;
5578 int fd = -1;
5579 {
5580 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005581 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005582 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5583 useIdentityTransform, forSystem, &fd);
5584 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005585 }
5586
5587 {
5588 std::unique_lock<std::mutex> captureLock(captureMutex);
5589 syncFd = fd;
5590 captureResult = std::make_optional<status_t>(result);
5591 captureCondition.notify_one();
5592 }
5593 });
5594
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005595 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005597 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598 while (*captureResult == EAGAIN) {
5599 captureResult.reset();
5600 result = postMessageAsync(message);
5601 if (result != NO_ERROR) {
5602 return result;
5603 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005604 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 }
5606 result = *captureResult;
5607 }
5608
5609 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610 sync_wait(syncFd, -1);
5611 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005613
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005615}
5616
chaviwa76b2712017-09-20 12:02:26 -07005617void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005618 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005619 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5620 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005621 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005622
chaviwa76b2712017-09-20 12:02:26 -07005623 const auto reqWidth = renderArea.getReqWidth();
5624 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005625 const auto sourceCrop = renderArea.getSourceCrop();
5626 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005627
Alec Mouri0f714832018-11-12 15:31:06 -08005628 renderengine::DisplaySettings clientCompositionDisplay;
5629 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005630
Alec Mouri0f714832018-11-12 15:31:06 -08005631 // assume that bounds are never offset, and that they are the same as the
5632 // buffer bounds.
5633 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5634 ui::Transform transform = renderArea.getTransform();
5635 mat4 m;
5636 m[0][0] = transform[0][0];
5637 m[0][1] = transform[0][1];
5638 m[0][3] = transform[0][2];
5639 m[1][0] = transform[1][0];
5640 m[1][1] = transform[1][1];
5641 m[1][3] = transform[1][2];
5642 m[3][0] = transform[2][0];
5643 m[3][1] = transform[2][1];
5644 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645
Alec Mouri0f714832018-11-12 15:31:06 -08005646 clientCompositionDisplay.globalTransform = m;
5647 mat4 rotMatrix;
5648 // Displacement for repositioning the clipping rectangle after rotating it
5649 // with the rotation hint.
5650 int displacementX = 0;
5651 int displacementY = 0;
5652 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5653 switch (rotation) {
5654 case ui::Transform::ROT_90:
5655 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5656 displacementX = reqWidth;
5657 break;
5658 case ui::Transform::ROT_180:
5659 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5660 displacementX = reqWidth;
5661 displacementY = reqHeight;
5662 break;
5663 case ui::Transform::ROT_270:
5664 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5665 displacementY = reqHeight;
5666 break;
5667 default:
5668 break;
5669 }
5670 // We need to transform the clipping window into the right spot.
5671 // First, rotate the clipping rectangle by the rotation hint to get the
5672 // right orientation
5673 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5674 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5675 const vec4 rotClipTL = rotMatrix * clipTL;
5676 const vec4 rotClipBR = rotMatrix * clipBR;
5677 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5678 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5679 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5680 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5681
5682 // Now reposition the clipping rectangle with the displacement vector
5683 // computed above.
5684 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5685
5686 clientCompositionDisplay.clip =
5687 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5688 newClipRight + displacementX, newClipBottom + displacementY);
5689
5690 // We need to perform the same transformation in layer space, so propagate
5691 // it to the global transform.
5692 mat4 clipTransform = displacementMat * rotMatrix;
5693 clientCompositionDisplay.globalTransform *= clipTransform;
5694 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5695 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005696
chaviw50da5042018-04-09 13:49:37 -07005697 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005698
Alec Mouri0f714832018-11-12 15:31:06 -08005699 renderengine::LayerSettings fillLayer;
5700 fillLayer.source.buffer.buffer = nullptr;
5701 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5702 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5703 fillLayer.alpha = half(alpha);
5704 clientCompositionLayers.push_back(fillLayer);
5705
5706 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005707 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005708 renderengine::LayerSettings layerSettings;
5709 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5710 layerSettings);
5711 if (prepared) {
5712 clientCompositionLayers.push_back(layerSettings);
5713 }
chaviwa76b2712017-09-20 12:02:26 -07005714 });
Alec Mouri0f714832018-11-12 15:31:06 -08005715
5716 clientCompositionDisplay.clearRegion = clearRegion;
5717 base::unique_fd drawFence;
5718 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5719 &drawFence);
5720
5721 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005722}
5723
chaviwa76b2712017-09-20 12:02:26 -07005724status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5725 TraverseLayersFunction traverseLayers,
5726 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005727 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005728 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005729 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005730 ATRACE_CALL();
5731
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005732 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005733
5734 traverseLayers([&](Layer* layer) {
5735 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5736 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005737
Robert Carr03480e22018-01-04 16:02:06 -08005738 // We allow the system server to take screenshots of secure layers for
5739 // use in situations like the Screen-rotation animation and place
5740 // the impetus on WindowManager to not persist them.
5741 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005742 ALOGW("FB is protected: PERMISSION_DENIED");
5743 return PERMISSION_DENIED;
5744 }
Alec Mouri0f714832018-11-12 15:31:06 -08005745 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005746 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005747}
5748
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005749// ---------------------------------------------------------------------------
5750
Dan Stoza412903f2017-04-27 13:42:17 -07005751void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5752 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005753}
5754
Dan Stoza412903f2017-04-27 13:42:17 -07005755void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5756 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005757}
5758
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005759void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005760 const LayerVector::Visitor& visitor) {
5761 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005762 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005763 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005764 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005765 continue;
5766 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005767 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005768 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005769 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005770 return;
5771 }
chaviwa76b2712017-09-20 12:02:26 -07005772 if (!layer->isVisible()) {
5773 return;
5774 }
5775 visitor(layer);
5776 });
5777 }
5778}
5779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005780}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005781
Lloyd Pique074e8122018-07-26 12:57:23 -07005782
Mathias Agopian3f844832013-08-07 21:24:32 -07005783#if defined(__gl_h_)
5784#error "don't include gl/gl.h in this file"
5785#endif
5786
5787#if defined(__gl2_h_)
5788#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005789#endif