blob: 954ecda11ec4fc30dbda17a0d8aaacabc2a3909b [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 Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700160ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
161 switch (rotation) {
162 case ISurfaceComposer::eRotateNone:
163 return ui::Transform::ROT_0;
164 case ISurfaceComposer::eRotate90:
165 return ui::Transform::ROT_90;
166 case ISurfaceComposer::eRotate180:
167 return ui::Transform::ROT_180;
168 case ISurfaceComposer::eRotate270:
169 return ui::Transform::ROT_270;
170 }
171 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
172 return ui::Transform::ROT_0;
173}
174
Peiyong Linfca547f2018-07-09 13:03:33 -0700175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Peiyong Lin9d846a52018-11-05 13:18:20 -0800190// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
191bool validateCompositionDataspace(Dataspace dataspace) {
192 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
193}
194
Steven Thomasb02664d2017-07-26 18:48:28 -0700195} // namespace anonymous
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Mathias Agopian99b49842011-06-27 16:05:52 -0700199const String16 sHardwareTest("android.permission.HARDWARE_TEST");
200const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
201const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
202const String16 sDump("android.permission.DUMP");
203
Daniel Solomon42d04562019-01-20 21:03:19 -0800204constexpr float kSrgbRedX = 0.4123f;
205constexpr float kSrgbRedY = 0.2126f;
206constexpr float kSrgbRedZ = 0.0193f;
207constexpr float kSrgbGreenX = 0.3576f;
208constexpr float kSrgbGreenY = 0.7152f;
209constexpr float kSrgbGreenZ = 0.1192f;
210constexpr float kSrgbBlueX = 0.1805f;
211constexpr float kSrgbBlueY = 0.0722f;
212constexpr float kSrgbBlueZ = 0.9506f;
213constexpr float kSrgbWhiteX = 0.9505f;
214constexpr float kSrgbWhiteY = 1.0000f;
215constexpr float kSrgbWhiteZ = 1.0891f;
216
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800217constexpr float kDefaultRefreshRate = 60.f;
218constexpr float kPerformanceRefreshRate = 90.f;
219
Mathias Agopian99b49842011-06-27 16:05:52 -0700220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700228int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700235
Kalle Raitaa099a242017-01-11 11:17:29 -0800236std::string getHwcServiceName() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.hwc_service_name", value, "default");
239 ALOGI("Using HWComposer service: '%s'", value);
240 return std::string(value);
241}
242
243bool useTrebleTestingOverride() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.treble_testing_override", value, "false");
246 ALOGI("Treble testing override: '%s'", value);
247 return std::string(value) == "true";
248}
249
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
251 switch(displayColorSetting) {
252 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Enhanced");
258 default:
259 return std::string("Unknown ") +
260 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262}
263
David Sodmanbc815282017-11-05 18:57:52 -0800264SurfaceFlingerBE::SurfaceFlingerBE()
265 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800266 mFrameBuckets(),
267 mTotalTime(0),
268 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800269 mComposerSequenceId(0) {
270}
271
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
273 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700276 mTransactionPending(false),
277 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700278 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700279 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800281 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800283 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800284 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800285 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700287 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700288 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700289 mDebugInTransaction(0),
290 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700291 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800292 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700293 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700294 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Lloyd Pique90c115d2018-09-18 21:39:42 -0700354 mPrimaryDispSync =
355 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
356 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700357
Daniel Solomon42d04562019-01-20 21:03:19 -0800358 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
359 if (surfaceFlingerConfigsServiceV1_2) {
360 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
361 [&](auto tmpPrimaries) {
362 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
363 });
364 } else {
365 initDefaultDisplayNativePrimaries();
366 }
367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 // debugging stuff...
369 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700372 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700373
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800374 property_get("debug.sf.showupdates", value, "0");
375 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700376
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700377 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000378
379 // DDMS debugging deprecated (b/120782499)
380 property_get("debug.sf.ddms", value, "0");
381 int debugDdms = atoi(value);
382 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800392 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Ana Krulec757f63a2019-01-25 10:46:18 -0800403 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
404 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700405
Romain Guy11d63f42017-07-20 12:47:14 -0700406 // We should be reading 'persist.sys.sf.color_saturation' here
407 // but since /data may be encrypted, we need to wait until after vold
408 // comes online to attempt to read the property. The property is
409 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800410
411 if (useTrebleTestingOverride()) {
412 // Without the override SurfaceFlinger cannot connect to HIDL
413 // services that are not listed in the manifests. Considered
414 // deriving the setting from the set service name, but it
415 // would be brittle if the name that's not 'default' is used
416 // for production purposes later on.
417 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419}
420
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421void SurfaceFlinger::onFirstRef()
422{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800423 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426SurfaceFlinger::~SurfaceFlinger()
427{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Dan Stozac7014012014-02-14 15:03:43 -0800430void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431{
432 // the window manager died on us. prepare its eulogy.
433
Andy McFadden13a082e2012-08-24 10:16:42 -0700434 // restore initial conditions (default device unblank, etc)
435 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436
437 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700438 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439}
440
Robert Carr1db73f62016-12-21 12:58:51 -0800441static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700442 status_t err = client->initCheck();
443 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 }
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return nullptr;
447}
448
449sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
450 return initClient(new Client(this));
451}
452
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
454 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455{
456 class DisplayToken : public BBinder {
457 sp<SurfaceFlinger> flinger;
458 virtual ~DisplayToken() {
459 // no more references, this display must be terminated
460 Mutex::Autolock _l(flinger->mStateLock);
461 flinger->mCurrentState.displays.removeItem(this);
462 flinger->setTransactionFlags(eDisplayTransactionNeeded);
463 }
464 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700465 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 : flinger(flinger) {
467 }
468 };
469
470 sp<BBinder> token = new DisplayToken(this);
471
472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 // Display ID is assigned when virtual display is allocated by HWC.
474 DisplayDeviceState state;
475 state.isSecure = secure;
476 state.displayName = displayName;
477 mCurrentState.displays.add(token, state);
478 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 return token;
480}
481
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700482void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 Mutex::Autolock _l(mStateLock);
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
486 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
492 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 ALOGE("destroyDisplay called for non-virtual display");
494 return;
495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 mInterceptor->saveDisplayDeletion(state.sequenceId);
497 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 setTransactionFlags(eDisplayTransactionNeeded);
499}
500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800501std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
502 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 const auto internalDisplayId = getInternalDisplayIdLocked();
505 if (!internalDisplayId) {
506 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 }
508
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800509 std::vector<PhysicalDisplayId> displayIds;
510 displayIds.reserve(mPhysicalDisplayTokens.size());
511 displayIds.push_back(internalDisplayId->value);
512
513 for (const auto& [id, token] : mPhysicalDisplayTokens) {
514 if (id != *internalDisplayId) {
515 displayIds.push_back(id.value);
516 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700518
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800519 return displayIds;
520}
521
522sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
523 Mutex::Autolock lock(mStateLock);
524 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
Ady Abraham37965d42018-11-01 13:43:32 -0700527status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
528 if (!outGetColorManagement) {
529 return BAD_VALUE;
530 }
531 *outGetColorManagement = useColorManagement;
532 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700533}
534
Lloyd Pique441d5042018-10-18 16:49:51 -0700535HWComposer& SurfaceFlinger::getHwComposer() const {
536 return mCompositionEngine->getHwComposer();
537}
538
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700539renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
540 return mCompositionEngine->getRenderEngine();
541}
542
Lloyd Pique70d91362018-10-18 16:02:55 -0700543compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
544 return *mCompositionEngine.get();
545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547void SurfaceFlinger::bootFinished()
548{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
556 // wait patiently for the window manager death
557 const String16 name("window");
558 sp<IBinder> window(defaultServiceManager()->getService(name));
559 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 }
Robert Carr720e5062018-07-30 17:45:14 -0700562 sp<IBinder> input(defaultServiceManager()->getService(
563 String16("inputflinger")));
564 if (input == nullptr) {
565 ALOGE("Failed to link to input service");
566 } else {
567 mInputFlinger = interface_cast<IInputFlinger>(input);
568 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700569
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 if (mVrFlinger) {
571 mVrFlinger->OnBootFinished();
572 }
573
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700574 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700575 // formerly we would just kill the process, but we now ask it to exit so it
576 // can choose where to stop the animation.
577 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700578
579 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
580 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
581 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700582
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 postMessageAsync(new LambdaMessage([this] {
584 readPersistentProperties();
585 mBootStage = BootStage::FINISHED;
586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700612}
613
Wei Wangf9b05ee2017-07-19 20:59:39 -0700614// Do not call property_set on main thread which will be blocked by init
615// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700617 ALOGI( "SurfaceFlinger's main thread ready to run. "
618 "Initializing graphics H/W...");
619
Ana Krulec757f63a2019-01-25 10:46:18 -0800620 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Dominik Laskowski83b88212018-12-11 13:34:06 -0800624 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800628 mScheduler = getFactory().createScheduler(
629 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
630
Ana Krulec757f63a2019-01-25 10:46:18 -0800631 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
632 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
633 mPhaseOffsets->setRefreshRateType(
634 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700635
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800636 auto resetIdleTimerCallback =
637 std::bind(&SurfaceFlinger::setRefreshRateTo, this, RefreshRateType::PERFORMANCE);
638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800640 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800641 resyncCallback, resetIdleTimerCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 impl::EventThread::InterceptVSyncsCallback());
643 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800644 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800645 resyncCallback, resetIdleTimerCallback,
646 [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mInterceptor->saveVSyncEvent(timestamp);
648 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700651 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
652 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 } else {
654 mEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800656 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 mEventThread =
658 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 impl::EventThread::InterceptVSyncsCallback(),
660 "appEventThread");
661 mSfEventThreadSource =
662 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800663 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700664
665 mSFEventThread =
666 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700667 [this](nsecs_t timestamp) {
668 mInterceptor->saveVSyncEvent(timestamp);
669 },
670 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800671 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700672 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700676 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700677 renderEngineFeature |= (useColorManagement ?
678 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700679 renderEngineFeature |= (useContextPriority ?
680 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700681
682 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700684 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700685 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700686
687 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
688 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700689 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
690 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 const auto display = getDefaultDisplayDeviceLocked();
694 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 // This callback is called from the vr flinger dispatch thread. We
701 // need to call signalTransaction(), which requires holding
702 // mStateLock when we're not on the main thread. Acquiring
703 // mStateLock from the vr flinger dispatch thread might trigger a
704 // deadlock in surface flinger (see b/66916578), so post a message
705 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
708 mVrFlingerRequestsDisplay = requestDisplay;
709 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700712 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
713 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700714 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700715 .value_or(0),
716 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800717 if (!mVrFlinger) {
718 ALOGE("Failed to start vrflinger");
719 }
720 }
721
Lloyd Pique90c115d2018-09-18 21:39:42 -0700722 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800723 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700724
Mathias Agopian92a979a2012-08-02 18:32:23 -0700725 // initialize our drawing state
726 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700727
Andy McFadden13a082e2012-08-24 10:16:42 -0700728 // set initial conditions (e.g. unblank default device)
729 initializeDisplays();
730
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700731 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700732
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700734
735 const bool presentFenceReliable =
736 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
737 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738
739 if (mStartPropertySetThread->Start() != NO_ERROR) {
740 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800744 mScheduler->setExpiredIdleTimerCallback([this] {
745 Mutex::Autolock lock(mStateLock);
746 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800747 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800748
Alec Mourifb571ea2019-01-24 18:42:10 -0800749 mRefreshRateStats =
750 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
751 *display->getId()),
752 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800753 }
754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800770
771 property_get("persist.sys.sf.color_mode", value, "0");
772 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700773}
774
Mathias Agopiana67e4182012-06-19 17:26:12 -0700775void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Start boot animation service by setting a property mailbox
777 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700778 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800779 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700780 if (mStartPropertySetThread->join() != NO_ERROR) {
781 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800782 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700783}
784
Mathias Agopian875d8e12013-06-07 15:35:48 -0700785size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700786 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700787}
788
Mathias Agopian875d8e12013-06-07 15:35:48 -0700789size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700790 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700791}
792
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800793// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800794
Jamie Gennis582270d2011-08-17 18:19:00 -0700795bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800796 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800797 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800798 return authenticateSurfaceTextureLocked(bufferProducer);
799}
800
801bool SurfaceFlinger::authenticateSurfaceTextureLocked(
802 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800803 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800804 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800805}
806
Brian Anderson6b376712017-04-04 10:51:39 -0700807status_t SurfaceFlinger::getSupportedFrameTimestamps(
808 std::vector<FrameEvent>* outSupported) const {
809 *outSupported = {
810 FrameEvent::REQUESTED_PRESENT,
811 FrameEvent::ACQUIRE,
812 FrameEvent::LATCH,
813 FrameEvent::FIRST_REFRESH_START,
814 FrameEvent::LAST_REFRESH_START,
815 FrameEvent::GPU_COMPOSITION_DONE,
816 FrameEvent::DEQUEUE_READY,
817 FrameEvent::RELEASE,
818 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700819 ConditionalLock _l(mStateLock,
820 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700821 if (!getHwComposer().hasCapability(
822 HWC2::Capability::PresentFenceIsNotReliable)) {
823 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
824 }
825 return NO_ERROR;
826}
827
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700828status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
829 Vector<DisplayInfo>* configs) {
830 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 return BAD_VALUE;
832 }
833
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800834 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
835
836 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700837 if (!displayId) {
838 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700839 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 // TODO: Not sure if display density should handled by SF any longer
842 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700845 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800846 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700847 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 }
849 return density;
850 }
851 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700852 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("ro.sf.lcd_density"); }
856 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700857
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dominik Laskowski075d3172018-05-24 15:50:06 -0700860 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 DisplayInfo info = DisplayInfo();
862
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 float xdpi = hwConfig->getDpiX();
864 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700865
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700866 info.w = hwConfig->getWidth();
867 info.h = hwConfig->getHeight();
868 // Default display viewport to display width and height
869 info.viewportW = info.w;
870 info.viewportH = info.h;
871
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800872 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 // The density of the device is provided by a build property
874 float density = Density::getBuildDensity() / 160.0f;
875 if (density == 0) {
876 // the build doesn't provide a density -- this is wrong!
877 // use xdpi instead
878 ALOGE("ro.sf.lcd_density must be defined as a build property");
879 density = xdpi / 160.0f;
880 }
881 if (Density::getEmuDensity()) {
882 // if "qemu.sf.lcd_density" is specified, it overrides everything
883 xdpi = ydpi = density = Density::getEmuDensity();
884 density /= 160.0f;
885 }
886 info.density = density;
887
888 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889 const auto display = getDefaultDisplayDeviceLocked();
890 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700891
892 // This is for screenrecord
893 const Rect viewport = display->getViewport();
894 if (viewport.isValid()) {
895 info.viewportW = uint32_t(viewport.getWidth());
896 info.viewportH = uint32_t(viewport.getHeight());
897 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 } else {
899 // TODO: where should this value come from?
900 static const int TV_DENSITY = 213;
901 info.density = TV_DENSITY / 160.0f;
902 info.orientation = 0;
903 }
904
Dan Stoza7f7da322014-05-02 15:26:25 -0700905 info.xdpi = xdpi;
906 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800908 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909
Andy McFadden91b2ca82014-06-13 14:04:23 -0700910 // This is how far in advance a buffer must be queued for
911 // presentation at a given time. If you want a buffer to appear
912 // on the screen at time N, you must submit the buffer before
913 // (N - presentationDeadline).
914 //
915 // Normally it's one full refresh period (to give SF a chance to
916 // latch the buffer), but this can be reduced by configuring a
917 // DispSync offset. Any additional delays introduced by the hardware
918 // composer or panel must be accounted for here.
919 //
920 // We add an additional 1ms to allow for processing time and
921 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800922 info.presentationDeadline =
923 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700924
925 // All non-virtual displays are currently considered secure.
926 info.secure = true;
927
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800928 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700929 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800930 std::swap(info.w, info.h);
931 }
932
Michael Wright28f24d02016-07-12 13:30:53 -0700933 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700934 }
935
Dan Stoza7f7da322014-05-02 15:26:25 -0700936 return NO_ERROR;
937}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
940 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700941 return BAD_VALUE;
942 }
943
Ana Krulece588e312018-09-18 12:32:24 -0700944 if (mUseScheduler) {
945 mScheduler->getDisplayStatInfo(stats);
946 } else {
947 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
948 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
949 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700950 return NO_ERROR;
951}
952
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
954 const auto display = getDisplayDevice(displayToken);
955 if (!display) {
956 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800957 return BAD_VALUE;
958 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700961}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700962
Ana Krulec7d1d6832018-12-27 11:10:09 -0800963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800965 postMessageSync(new LambdaMessage(
966 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967 return NO_ERROR;
968}
969
970void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
975 return;
976 }
977
978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 return;
983 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800985 ALOGW("Attempt to set active config %d for virtual display", mode);
986 return;
987 }
988 int currentDisplayPowerMode = display->getPowerMode();
989 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
990 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 return;
992 }
993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800996 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997 return;
998 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800999 if (mUseScheduler) {
1000 mRefreshRateStats->setConfigMode(mode);
1001 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Dominik Laskowski075d3172018-05-24 15:50:06 -07001003 const auto displayId = display->getId();
1004 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008
Ana Krulec7d1d6832018-12-27 11:10:09 -08001009 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001010 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1014 Vector<ColorMode>* outColorModes) {
1015 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 return BAD_VALUE;
1017 }
1018
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001020 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001021 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1022
1023 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1024 if (!displayId) {
1025 return NAME_NOT_FOUND;
1026 }
1027
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001029 }
Michael Wright28f24d02016-07-12 13:30:53 -07001030 outColorModes->clear();
1031 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1032
1033 return NO_ERROR;
1034}
1035
Daniel Solomon42d04562019-01-20 21:03:19 -08001036status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1037 ui::DisplayPrimaries &primaries) {
1038 if (!displayToken) {
1039 return BAD_VALUE;
1040 }
1041
1042 // Currently we only support this API for a single internal display.
1043 if (getInternalDisplayToken() != displayToken) {
1044 return BAD_VALUE;
1045 }
1046
1047 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001053 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001059 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 Vector<ColorMode> modes;
1061 getDisplayColorModes(displayToken, &modes);
1062 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1063 if (mode < ColorMode::NATIVE || !exists) {
1064 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001067 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 const auto display = getDisplayDevice(displayToken);
1069 if (!display) {
1070 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1071 decodeColorMode(mode).c_str(), mode, displayToken.get());
1072 } else if (display->isVirtual()) {
1073 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1074 decodeColorMode(mode).c_str(), mode);
1075 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001076 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1077 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 }
1079 }));
1080
Michael Wright28f24d02016-07-12 13:30:53 -07001081 return NO_ERROR;
1082}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001083
Svetoslavd85084b2014-03-20 10:28:31 -07001084status_t SurfaceFlinger::clearAnimationFrameStats() {
1085 Mutex::Autolock _l(mStateLock);
1086 mAnimFrameTracker.clearStats();
1087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1091 Mutex::Autolock _l(mStateLock);
1092 mAnimFrameTracker.getStats(outStats);
1093 return NO_ERROR;
1094}
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1097 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 Mutex::Autolock _l(mStateLock);
1099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100 const auto display = getDisplayDeviceLocked(displayToken);
1101 if (!display) {
1102 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001103 return BAD_VALUE;
1104 }
1105
Peiyong Linfb069302018-04-25 14:34:31 -07001106 // At this point the DisplayDeivce should already be set up,
1107 // meaning the luminance information is already queried from
1108 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001110 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1111 capabilities.getDesiredMaxLuminance(),
1112 capabilities.getDesiredMaxAverageLuminance(),
1113 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001114
1115 return NO_ERROR;
1116}
1117
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001118status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1119 ui::PixelFormat* outFormat,
1120 ui::Dataspace* outDataspace,
1121 uint8_t* outComponentMask) const {
1122 if (!outFormat || !outDataspace || !outComponentMask) {
1123 return BAD_VALUE;
1124 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001125 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001126 if (!display || !display->getId()) {
1127 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1128 return BAD_VALUE;
1129 }
1130 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1131 outDataspace, outComponentMask);
1132}
1133
Kevin DuBois74e53772018-11-19 10:52:38 -08001134status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1135 bool enable, uint8_t componentMask,
1136 uint64_t maxFrames) const {
1137 const auto display = getDisplayDevice(displayToken);
1138 if (!display || !display->getId()) {
1139 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1140 return BAD_VALUE;
1141 }
1142
1143 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1144 componentMask, maxFrames);
1145}
1146
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001147status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1148 uint64_t maxFrames, uint64_t timestamp,
1149 DisplayedFrameStats* outStats) const {
1150 const auto display = getDisplayDevice(displayToken);
1151 if (!display || !display->getId()) {
1152 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1153 return BAD_VALUE;
1154 }
1155
1156 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1157 outStats);
1158}
1159
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001160status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1161 if (!outSupported) {
1162 return BAD_VALUE;
1163 }
1164 *outSupported = getRenderEngine().supportsProtectedContent();
1165 return NO_ERROR;
1166}
1167
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001168status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1169 bool* outIsWideColorDisplay) const {
1170 if (!displayToken || !outIsWideColorDisplay) {
1171 return BAD_VALUE;
1172 }
1173 Mutex::Autolock _l(mStateLock);
1174 const auto display = getDisplayDeviceLocked(displayToken);
1175 if (!display) {
1176 return BAD_VALUE;
1177 }
1178 *outIsWideColorDisplay = display->hasWideColorGamut();
1179 return NO_ERROR;
1180}
1181
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001183 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001184 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186 if (mInjectVSyncs == enable) {
1187 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001188 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189
Dominik Laskowski83b88212018-12-11 13:34:06 -08001190 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001191
Ana Krulec98b5b242018-08-10 15:03:23 -07001192 // TODO(akrulec): Part of the Injector should be refactored, so that it
1193 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 if (enable) {
1195 ALOGV("VSync Injections enabled");
1196 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001197 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001198 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001199 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001200 impl::EventThread::InterceptVSyncsCallback(),
1201 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001203 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001204 } else {
1205 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001206 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001207 }
1208
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001210 }));
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212 return NO_ERROR;
1213}
1214
1215status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216 Mutex::Autolock _l(mStateLock);
1217
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218 if (!mInjectVSyncs) {
1219 ALOGE("VSync Injections not enabled");
1220 return BAD_VALUE;
1221 }
1222 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1223 ALOGV("Injecting VSync inside SurfaceFlinger");
1224 mVSyncInjector->onInjectSyncEvent(when);
1225 }
1226 return NO_ERROR;
1227}
1228
Lloyd Pique755e3192018-01-31 16:46:15 -08001229status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1230 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001231 // Try to acquire a lock for 1s, fail gracefully
1232 const status_t err = mStateLock.timedLock(s2ns(1));
1233 const bool locked = (err == NO_ERROR);
1234 if (!locked) {
1235 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1236 return TIMED_OUT;
1237 }
1238
1239 outLayers->clear();
1240 mCurrentState.traverseInZOrder([&](Layer* layer) {
1241 outLayers->push_back(layer->getLayerDebugInfo());
1242 });
1243
1244 mStateLock.unlock();
1245 return NO_ERROR;
1246}
1247
Peiyong Linc6780972018-10-28 15:24:08 -07001248status_t SurfaceFlinger::getCompositionPreference(
1249 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1250 Dataspace* outWideColorGamutDataspace,
1251 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001252 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001253 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001254 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001255 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001256 return NO_ERROR;
1257}
1258
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001259// ----------------------------------------------------------------------------
1260
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001261sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1262 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001263 auto resyncCallback = makeResyncCallback([this] {
1264 Mutex::Autolock lock(mStateLock);
1265 return getVsyncPeriod();
1266 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001267
Ana Krulec98b5b242018-08-10 15:03:23 -07001268 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001269 auto resetIdleTimerCallback = [this] {
1270 Mutex::Autolock lock(mStateLock);
1271 setRefreshRateTo(RefreshRateType::PERFORMANCE);
1272 };
1273
1274 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1275 : mAppConnectionHandle;
1276
1277 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1278 std::move(resetIdleTimerCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001279 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001280 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001281 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001283 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001284 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001285 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001286}
1287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289
1290void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001291 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001292}
1293
1294void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001295 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001296}
1297
1298void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001299 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001300}
1301
1302void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001303 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001304 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001305}
1306
1307status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001308 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001309 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001310}
1311
1312status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001313 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001314 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315 if (res == NO_ERROR) {
1316 msg->wait();
1317 }
1318 return res;
1319}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001321void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001322 do {
1323 waitForEvent();
1324 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001325}
1326
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001328 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001329 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1330 return 0;
1331 }
1332
1333 const auto config = getHwComposer().getActiveConfig(*displayId);
1334 return config ? config->getVsyncPeriod() : 0;
1335}
1336
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337void SurfaceFlinger::enableHardwareVsync() {
1338 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001340 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001341 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001343 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344}
1345
Dominik Laskowski83b88212018-12-11 13:34:06 -08001346void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 Mutex::Autolock _l(mHWVsyncLock);
1348
Jesse Hall948fe0c2013-10-14 12:56:09 -07001349 if (makeAvailable) {
1350 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001351 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1352 if (mUseScheduler) {
1353 mScheduler->makeHWSyncAvailable(true);
1354 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001355 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001356 // Hardware vsync is not currently available, so abort the resync
1357 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001358 return;
1359 }
1360
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001362 return;
1363 }
1364
Ana Krulece588e312018-09-18 12:32:24 -07001365 if (mUseScheduler) {
1366 mScheduler->setVsyncPeriod(period);
1367 } else {
1368 mPrimaryDispSync->reset();
1369 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370
Ana Krulece588e312018-09-18 12:32:24 -07001371 if (!mPrimaryHWVsyncEnabled) {
1372 mPrimaryDispSync->beginResync();
1373 mEventControlThread->setVsyncEnabled(true);
1374 mPrimaryHWVsyncEnabled = true;
1375 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001376 }
1377}
1378
Jesse Hall948fe0c2013-10-14 12:56:09 -07001379void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001380 Mutex::Autolock _l(mHWVsyncLock);
1381 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001382 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001383 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 mPrimaryHWVsyncEnabled = false;
1385 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001386 if (makeUnavailable) {
1387 mHWVsyncAvailable = false;
1388 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389}
1390
Dominik Laskowski83b88212018-12-11 13:34:06 -08001391void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001392 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001393
Dan Stoza57164302017-05-08 14:03:54 -07001394 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001395 const nsecs_t last = lastResyncTime.exchange(now);
1396
1397 if (now - last > kIgnoreDelay) {
1398 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001399 }
1400}
1401
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001402void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1403 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001404 ATRACE_NAME("SF onVsync");
1405
Steven Thomas3cfac282017-02-06 12:29:30 -08001406 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 return;
1410 }
1411
Dominik Laskowski075d3172018-05-24 15:50:06 -07001412 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001413 return;
1414 }
1415
Dominik Laskowski075d3172018-05-24 15:50:06 -07001416 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001417 // For now, we don't do anything with external display vsyncs.
1418 return;
1419 }
1420
Ana Krulece588e312018-09-18 12:32:24 -07001421 if (mUseScheduler) {
1422 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001423 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001424 bool needsHwVsync = false;
1425 { // Scope for the lock
1426 Mutex::Autolock _l(mHWVsyncLock);
1427 if (mPrimaryHWVsyncEnabled) {
1428 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1429 }
1430 }
1431
1432 if (needsHwVsync) {
1433 enableHardwareVsync();
1434 } else {
1435 disableHardwareVsync(false);
1436 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001437 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001438}
1439
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001440void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001441 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1442 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001443}
1444
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001445void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1446 mPhaseOffsets->setRefreshRateType(refreshRate);
1447
1448 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1449 mVsyncModulator.setPhaseOffsets(early, gl, late);
1450
1451 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452 return;
1453 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001454
Ana Krulec7d1d6832018-12-27 11:10:09 -08001455 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1456 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1457 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1458 // refresh cycle.
1459
1460 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001461 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001462 if (currentVsyncPeriod == 0) {
1463 return;
1464 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001465
Ana Krulec7d1d6832018-12-27 11:10:09 -08001466 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1467 // floating numbers.
1468 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001469 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1470 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001471 if (std::abs(currentFps - newFps) <= 1) {
1472 return;
1473 }
1474
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001475 const auto displayId = getInternalDisplayIdLocked();
1476 LOG_ALWAYS_FATAL_IF(!displayId);
1477
1478 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001479 for (int i = 0; i < configs.size(); i++) {
1480 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1481 if (vsyncPeriod == 0) {
1482 continue;
1483 }
1484 const float fps = 1e9 / vsyncPeriod;
1485 // TODO(b/113612090): There should be a better way at determining which config
1486 // has the right refresh rate.
1487 if (std::abs(fps - newFps) <= 1) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001488 setActiveConfigInternal(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001489 ATRACE_INT("FPS", newFps);
1490 }
1491 }
1492}
1493
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001494void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001495 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001496 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001497 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498
Lloyd Piqueba04e622017-12-14 17:11:26 -08001499 // Ignore events that do not have the right sequenceId.
1500 if (sequenceId != getBE().mComposerSequenceId) {
1501 return;
1502 }
1503
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 // Only lock if we're not on the main thread. This function is normally
1505 // called on a hwbinder thread, but for the primary display it's called on
1506 // the main thread with the state lock already held, so don't attempt to
1507 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001508 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001509
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001510 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001511
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001512 if (std::this_thread::get_id() == mMainThreadId) {
1513 // Process all pending hot plug events immediately if we are on the main thread.
1514 processDisplayHotplugEventsLocked();
1515 }
1516
Lloyd Piqueba04e622017-12-14 17:11:26 -08001517 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001518}
1519
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001520void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001521 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001522 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001525 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001526}
1527
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001528void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001529 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001532 getHwComposer().setVsyncEnabled(*displayId,
1533 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1534 }
Mathias Agopian86303202012-07-24 22:46:10 -07001535}
1536
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001537// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001538void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001539 if (mUseScheduler) {
1540 mScheduler->disableHardwareVsync(true);
1541 } else {
1542 disableHardwareVsync(true);
1543 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544 // Clear the drawing state so that the logic inside of
1545 // handleTransactionLocked will fire. It will determine the delta between
1546 // mCurrentState and mDrawingState and re-apply all changes when we make the
1547 // transition.
1548 mDrawingState.displays.clear();
1549 mDisplays.clear();
1550}
1551
Steven Thomas050b2c82017-03-06 11:45:16 -08001552void SurfaceFlinger::updateVrFlinger() {
1553 if (!mVrFlinger)
1554 return;
1555 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001557 return;
1558 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Pique441d5042018-10-18 16:49:51 -07001560 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 ALOGE("Vr flinger is only supported for remote hardware composer"
1562 " service connections. Ignoring request to transition to vr"
1563 " flinger.");
1564 mVrFlingerRequestsDisplay = false;
1565 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001566 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001571 LOG_ALWAYS_FATAL_IF(!display);
1572 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001573 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1574 // called below. Clear the reference now so we don't accidentally use it
1575 // later.
1576 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001577
Steven Thomasb02664d2017-07-26 18:48:28 -07001578 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001579 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001581
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001583 // Delete the current instance before creating the new one
1584 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1585 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1586 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1587 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588
Lloyd Pique441d5042018-10-18 16:49:51 -07001589 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001590 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001591
1592 if (vrFlingerRequestsDisplay) {
1593 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595
1596 mVisibleRegionsDirty = true;
1597 invalidateHwcGeometry();
1598
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001599 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001600 display = getDefaultDisplayDeviceLocked();
1601 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001602 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001603
Steven Thomasb02664d2017-07-26 18:48:28 -07001604 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001605 const nsecs_t vsyncPeriod = getVsyncPeriod();
1606 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001607
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001608 // The present fences returned from vr_hwc are not an accurate
1609 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001610 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001611 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1612 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001613 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001614 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001615 !hasSyncFramework);
1616 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001617
Steven Thomasb02664d2017-07-26 18:48:28 -07001618 // Use phase of 0 since phase is not known.
1619 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001620 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001621 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001622
Dominik Laskowski83b88212018-12-11 13:34:06 -08001623 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001624
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001625 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001626 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001627}
1628
Mathias Agopian4fec8732012-06-29 14:12:52 -07001629void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001630 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001631 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001632 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001633 if (mUseScheduler) {
1634 // This call is made each time SF wakes up and creates a new frame.
1635 mScheduler->incrementFrameCounter();
1636 }
Dan Stoza50182882016-07-08 12:02:20 -07001637 bool frameMissed = !mHadClientComposition &&
1638 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 (mPreviousPresentFence->getSignalTime() ==
1640 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001641 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001642 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001643 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001644 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001645 if (mPropagateBackpressure) {
1646 signalLayerUpdate();
1647 break;
1648 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001649 }
Dan Stoza50182882016-07-08 12:02:20 -07001650
Steven Thomas050b2c82017-03-06 11:45:16 -08001651 // Now that we're going to make it to the handleMessageTransaction()
1652 // call below it's safe to call updateVrFlinger(), which will
1653 // potentially trigger a display handoff.
1654 updateVrFlinger();
1655
Dan Stoza6b9454d2014-11-07 16:00:59 -08001656 bool refreshNeeded = handleMessageTransaction();
1657 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001658
1659 updateCursorAsync();
1660 updateInputFlinger();
1661
Dan Stoza58784442014-12-02 16:58:17 -08001662 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001663 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001664 // Signal a refresh if a transaction modified the window state,
1665 // a new buffer was latched, or if HWC has requested a full
1666 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001667 signalRefresh();
1668 }
1669 break;
1670 }
1671 case MessageQueue::REFRESH: {
1672 handleMessageRefresh();
1673 break;
1674 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001675 }
1676}
1677
Dan Stoza6b9454d2014-11-07 16:00:59 -08001678bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001679 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001680
1681 // Apply any ready transactions in the queues if there are still transactions that have not been
1682 // applied, wake up during the next vsync period and check again
1683 bool transactionNeeded = false;
1684 if (!flushTransactionQueues()) {
1685 transactionNeeded = true;
1686 }
1687
Mathias Agopian4fec8732012-06-29 14:12:52 -07001688 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001689 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001691
1692 if (transactionNeeded) {
1693 setTransactionFlags(eTransactionNeeded);
1694 }
1695
1696 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697}
1698
Mathias Agopian4fec8732012-06-29 14:12:52 -07001699void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001701
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001702 mRefreshPending = false;
1703
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001704 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001705 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001706 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001707 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 for (const auto& [token, display] : mDisplays) {
1709 beginFrame(display);
1710 prepareFrame(display);
1711 doDebugFlashRegions(display, repaintEverything);
1712 doComposition(display, repaintEverything);
1713 }
1714
Adrian Roos1e1a1282017-11-01 19:05:31 +01001715 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001716 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001717
1718 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001719 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001720
Dan Stozabfbffeb2016-07-21 14:49:33 -07001721 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001722 for (const auto& [token, displayDevice] : mDisplays) {
1723 auto display = displayDevice->getCompositionDisplay();
1724 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001725 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001726 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001727 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001728
Alec Mouri86770e52018-09-24 22:40:58 +00001729 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001730 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001731 if (mHadClientComposition) {
1732 base::unique_fd flushFence(getRenderEngine().flush());
1733 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1734 getBE().flushFence = new Fence(std::move(flushFence));
1735 } else {
1736 // Cleanup for hygiene.
1737 getBE().flushFence = Fence::NO_FENCE;
1738 }
1739 }
1740
Jorim Jaggi90535212018-05-23 23:44:06 +02001741 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001742
David Sodman7e4ae112018-02-09 15:02:28 -08001743 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001744 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001745 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001746 compositionInfo.hwc.hwcLayer = nullptr;
1747 }
David Sodmanba340492018-08-05 21:51:33 -07001748 }
David Sodman7e4ae112018-02-09 15:02:28 -08001749
1750 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001752
David Sodmanfa9b2af2017-12-24 13:28:59 -08001753
1754bool SurfaceFlinger::handleMessageInvalidate() {
1755 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001756 bool refreshNeeded = handlePageFlip();
1757
1758 for (auto& layer : mLayersPendingRefresh) {
1759 Region visibleReg;
1760 visibleReg.set(layer->computeScreenBounds());
1761 invalidateLayerStack(layer, visibleReg);
1762 }
1763 mLayersPendingRefresh.clear();
1764 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001765}
1766
David Sodman79bba0e2018-08-05 18:07:49 -07001767void SurfaceFlinger::calculateWorkingSet() {
1768 ATRACE_CALL();
1769 ALOGV(__FUNCTION__);
1770
David Sodman79bba0e2018-08-05 18:07:49 -07001771 // build the h/w work list
1772 if (CC_UNLIKELY(mGeometryInvalid)) {
1773 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001774 for (const auto& [token, displayDevice] : mDisplays) {
1775 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001776 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 if (!displayId) {
1778 continue;
1779 }
David Sodman79bba0e2018-08-05 18:07:49 -07001780
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 for (size_t i = 0; i < currentLayers.size(); i++) {
1783 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001784
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 if (!layer->hasHwcLayer(*displayId)) {
1786 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1787 layer->forceClientComposition(*displayId);
1788 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001789 }
1790 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791
Lloyd Pique32cbe282018-10-19 13:09:22 -07001792 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001793 if (mDebugDisableHWC || mDebugRegion) {
1794 layer->forceClientComposition(*displayId);
1795 }
David Sodman79bba0e2018-08-05 18:07:49 -07001796 }
1797 }
1798 }
1799
1800 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 for (const auto& [token, displayDevice] : mDisplays) {
1802 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001803 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001804 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001805 continue;
1806 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001807 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001808
1809 if (mDrawingState.colorMatrixChanged) {
1810 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001811 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001813 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001814 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001815 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1816 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001817 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001818 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001819 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1820 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001821 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001822 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001823 }
1824
Peiyong Lind3788632018-09-18 16:01:31 -07001825 // TODO(b/111562338) remove when composer 2.3 is shipped.
1826 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001827 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001828 }
1829
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001830 if (layer->getRoundedCornerState().radius > 0.0f) {
1831 layer->forceClientComposition(*displayId);
1832 }
1833
Dominik Laskowski075d3172018-05-24 15:50:06 -07001834 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001835 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001836 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001837 continue;
1838 }
1839
Lloyd Pique32cbe282018-10-19 13:09:22 -07001840 const auto& displayState = display->getState();
1841 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1842 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001843 }
1844
Peiyong Lin13effd12018-07-24 17:01:47 -07001845 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001846 ColorMode colorMode;
1847 Dataspace dataSpace;
1848 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001849 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001851 }
1852 }
1853
1854 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001855
1856 for (const auto& [token, display] : mDisplays) {
1857 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001858 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001859 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001860
1861 if (displayId) {
1862 if (!layer->setHwcLayer(*displayId)) {
1863 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1864 }
1865 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001866 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001867
Dominik Laskowski05275f12018-11-01 15:03:24 -07001868 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001869 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1870 }
1871 }
David Sodman79bba0e2018-08-05 18:07:49 -07001872}
1873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1875 bool repaintEverything) {
1876 auto display = displayDevice->getCompositionDisplay();
1877 const auto& displayState = display->getState();
1878
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879 // is debugging enabled
1880 if (CC_LIKELY(!mDebugRegion))
1881 return;
1882
Lloyd Pique32cbe282018-10-19 13:09:22 -07001883 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001884 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001885 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001886 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001887 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001888 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001889 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001891 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 }
1893 }
1894
Lloyd Pique32cbe282018-10-19 13:09:22 -07001895 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896
1897 if (mDebugRegion > 1) {
1898 usleep(mDebugRegion * 1000);
1899 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001900
Lloyd Pique32cbe282018-10-19 13:09:22 -07001901 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001902}
1903
Adrian Roos1e1a1282017-11-01 19:05:31 +01001904void SurfaceFlinger::doTracing(const char* where) {
1905 ATRACE_CALL();
1906 ATRACE_NAME(where);
1907 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001908 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001909 }
1910}
1911
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001912void SurfaceFlinger::logLayerStats() {
1913 ATRACE_CALL();
1914 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001915 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001916 if (display->isPrimary()) {
1917 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001918 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001919 }
1920 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001921
1922 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001923 }
1924}
1925
David Sodman2b406362017-12-15 13:33:47 -08001926void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 ATRACE_CALL();
1929 ALOGV("preComposition");
1930
David Sodman2b406362017-12-15 13:33:47 -08001931 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1932
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001934 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001935 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001936 needExtraInvalidate = true;
1937 }
Robert Carr2047fae2016-11-28 14:09:09 -08001938 });
1939
Mathias Agopiancd60f992012-08-16 16:28:27 -07001940 if (needExtraInvalidate) {
1941 signalLayerUpdate();
1942 }
1943}
1944
Ana Krulece588e312018-09-18 12:32:24 -07001945void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1946 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Update queue of past composite+present times and determine the
1948 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001949 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001951 while (!getBE().mCompositePresentTimes.empty()) {
1952 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 // Cached values should have been updated before calling this method,
1954 // which helps avoid duplicate syscalls.
1955 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1956 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1957 break;
1958 }
1959 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001960 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961 }
1962
1963 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001964 while (getBE().mCompositePresentTimes.size() > 16) {
1965 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966 }
1967
Ana Krulece588e312018-09-18 12:32:24 -07001968 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001969}
1970
Ana Krulece588e312018-09-18 12:32:24 -07001971void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1972 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973 // Integer division and modulo round toward 0 not -inf, so we need to
1974 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001975 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1976 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1977 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978
Ana Krulec757f63a2019-01-25 10:46:18 -08001979 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001980 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001981 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001982 }
1983
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001984 // Snap the latency to a value that removes scheduling jitter from the
1985 // composition and present times, which often have >1ms of jitter.
1986 // Reducing jitter is important if an app attempts to extrapolate
1987 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001988 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001990 nsecs_t bias = stats.vsyncPeriod / 2;
1991 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1992 nsecs_t snappedCompositeToPresentLatency =
1993 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994
David Sodman99974d22017-11-28 12:04:33 -08001995 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001996 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1997 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001998 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999}
2000
Ady Abraham8164d482019-01-11 14:47:59 -08002001// debug patch for b/119477596 - add stack guards to catch stack
2002// corruptions and disable clang optimizations.
2003// The code below is temporary and planned to be removed once stack
2004// corruptions are found.
2005#pragma clang optimize off
2006class StackGuard {
2007public:
2008 StackGuard(const char* name, const char* func, int line) {
2009 guarders.reserve(MIN_CAPACITY);
2010 guarders.push_back({this, name, func, line});
2011 validate();
2012 }
2013 ~StackGuard() {
2014 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2015 if (i->guard == this) {
2016 guarders.erase(i);
2017 break;
2018 }
2019 }
2020 }
2021
2022 static void validate() {
2023 for (const auto& guard : guarders) {
2024 if (guard.guard->cookie != COOKIE_VALUE) {
2025 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2026 CallStack stack(LOG_TAG);
2027 abort();
2028 }
2029 }
2030 }
2031
2032private:
2033 uint64_t cookie = COOKIE_VALUE;
2034 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2035 static constexpr size_t MIN_CAPACITY = 16;
2036
2037 struct GuarderElement {
2038 StackGuard* guard;
2039 const char* name;
2040 const char* func;
2041 int line;
2042 };
2043
2044 static std::vector<GuarderElement> guarders;
2045};
2046std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2047
2048#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2049
2050#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002051void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002052{
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 ATRACE_CALL();
2055 ALOGV("postComposition");
2056
Brian Anderson3546a3f2016-07-14 11:51:14 -07002057 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002058 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002059 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002060 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002061 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002062 }
Ady Abraham8164d482019-01-11 14:47:59 -08002063 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002064
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002065 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002066 const auto displayDevice = getDefaultDisplayDeviceLocked();
2067 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068
David Sodman73beded2017-11-15 11:56:06 -08002069 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002070 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002071 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2072
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002074 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002075 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2076 ->getRenderSurface()
2077 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002078 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079 } else {
2080 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2081 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002082
Ady Abraham8164d482019-01-11 14:47:59 -08002083 ASSERT_ON_STACK_GUARD();
2084
David Sodman73beded2017-11-15 11:56:06 -08002085 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002086 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2087 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002088 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002089 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002090 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002091
Ana Krulece588e312018-09-18 12:32:24 -07002092 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002093 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002094 if (mUseScheduler) {
2095 mScheduler->getDisplayStatInfo(&stats);
2096 } else {
2097 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2098 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2099 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002100
Ady Abraham8164d482019-01-11 14:47:59 -08002101 ASSERT_ON_STACK_GUARD();
2102
David Sodman2b406362017-12-15 13:33:47 -08002103 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002104 // when we started doing work for this frame, but that should be okay
2105 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002106 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002107 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002108 DEFINE_STACK_GUARD(compositorTiming);
2109
Brian Andersond0010582017-03-07 13:20:31 -08002110 {
David Sodman99974d22017-11-28 12:04:33 -08002111 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002112 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002113 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002114
2115 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002116 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002117
Robert Carr2047fae2016-11-28 14:09:09 -08002118 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002119 bool frameLatched =
2120 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2121 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002122 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002123 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002124 recordBufferingStats(layer->getName().string(),
2125 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002126 }
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002128 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002129
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002130 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002132 if (mUseScheduler) {
2133 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002134 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002135 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002136 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2137 enableHardwareVsync();
2138 } else {
2139 disableHardwareVsync(false);
2140 }
Ady Abraham8164d482019-01-11 14:47:59 -08002141 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002142 }
2143 }
2144
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002145 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002146 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2147 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002148 if (mUseScheduler) {
2149 mScheduler->enableHardwareVsync();
2150 } else {
2151 enableHardwareVsync();
2152 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002153 }
2154 }
2155
Ady Abraham8164d482019-01-11 14:47:59 -08002156 ASSERT_ON_STACK_GUARD();
2157
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158 if (mAnimCompositionPending) {
2159 mAnimCompositionPending = false;
2160
Brian Anderson4e606e32017-03-16 15:34:57 -07002161 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002162 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002163 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002164
2165 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002166 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002167 // The HWC doesn't support present fences, so use the refresh
2168 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002169 const nsecs_t presentTime =
2170 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002171 DEFINE_STACK_GUARD(presentTime);
2172
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002173 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002174 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002175 }
2176 mAnimFrameTracker.advanceFrame();
2177 }
Dan Stozab90cf072015-03-05 11:05:59 -08002178
Ady Abraham8164d482019-01-11 14:47:59 -08002179 ASSERT_ON_STACK_GUARD();
2180
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002181 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002182 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002183 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002184 }
2185
Ady Abraham8164d482019-01-11 14:47:59 -08002186 ASSERT_ON_STACK_GUARD();
2187
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002188 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002189
Ady Abraham8164d482019-01-11 14:47:59 -08002190 ASSERT_ON_STACK_GUARD();
2191
Lloyd Pique32cbe282018-10-19 13:09:22 -07002192 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2193 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002194 return;
2195 }
2196
2197 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002198 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002199 if (mHasPoweredOff) {
2200 mHasPoweredOff = false;
2201 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002202 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002203 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002204 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002205 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002206 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2207 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002208 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002210 }
David Sodman4a36e932017-11-07 14:29:47 -08002211 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002212
2213 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002214 }
David Sodman4a36e932017-11-07 14:29:47 -08002215 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002216 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002217
2218 {
2219 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002220 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002221 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002222 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002223 if (refillCount > 0) {
2224 const size_t offset = mTexturePool.size();
2225 mTexturePool.resize(mTexturePoolSize);
2226 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2227 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2228 }
Ady Abraham8164d482019-01-11 14:47:59 -08002229 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002230 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002231
Marissa Wallfda30bb2018-10-12 11:34:28 -07002232 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002233 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002234
2235 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002236}
Ady Abraham8164d482019-01-11 14:47:59 -08002237#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002238
2239void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 ATRACE_CALL();
2241 ALOGV("rebuildLayerStacks");
2242
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002243 // We need to clear these out now as these may be holding on to a
2244 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2245 // also holds a reference. When the set of visible layers is recomputed,
2246 // some layers may be destroyed if the only thing keeping them alive was
2247 // that list of visible layers associated with each display. The layer
2248 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2249 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2250 for (const auto& [token, display] : mDisplays) {
2251 getBE().mCompositionInfo[token].clear();
2252 }
2253
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002255 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002256 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002257 mVisibleRegionsDirty = false;
2258 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002259
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002260 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002261 const auto& displayDevice = pair.second;
2262 auto display = displayDevice->getCompositionDisplay();
2263 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002264 Region opaqueRegion;
2265 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002266 compositionengine::Output::OutputLayers layersSortedByZ;
2267 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002268 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 const ui::Transform& tr = displayState.transform;
2270 const Rect bounds = displayState.bounds;
2271 if (displayState.isEnabled) {
2272 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002273
Jeff Sharkey76488112017-02-27 14:15:18 -07002274 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002275 auto compositionLayer = layer->getCompositionLayer();
2276 if (compositionLayer == nullptr) {
2277 return;
2278 }
2279
Chia-I Wu83806892017-11-16 10:50:20 -08002280 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002281 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002282 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2283 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2284
Lloyd Piqueef36b002019-01-23 17:52:04 -08002285 if (display->belongsInOutput(layer->getLayerStack(),
2286 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002287 Region drawRegion(tr.transform(
2288 layer->visibleNonTransparentRegion));
2289 drawRegion.andSelf(bounds);
2290 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002291 layersSortedByZ.emplace_back(
2292 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2293 layerFE));
2294
2295 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002296 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002297 // Clear out the HWC layer if this layer was
2298 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002300 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002301 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002302 // WM changes display->layerStack upon sleep/awake.
2303 // Here we make sure we delete the HWC layers even if
2304 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002306 }
2307
2308 // If a layer is not going to get a release fence because
2309 // it is invisible, but it is also going to release its
2310 // old buffer, add it to the list of layers needing
2311 // fences.
2312 if (hwcLayerDestroyed) {
2313 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2314 mLayersWithQueuedFrames.cend(), layer);
2315 if (found != mLayersWithQueuedFrames.cend()) {
2316 layersNeedingFences.add(layer);
2317 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002318 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002319 });
2320 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002321
2322 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2323
2324 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002325 displayDevice->setLayersNeedingFences(layersNeedingFences);
2326
2327 Region undefinedRegion{bounds};
2328 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2329
2330 display->editState().undefinedRegion = undefinedRegion;
2331 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002332 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002333 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002334}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002335
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002338// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002340// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341// The returned HDR data space is one of
2342// - Dataspace::UNKNOWN
2343// - Dataspace::BT2020_HLG
2344// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2346 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002347 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002348 *outHdrDataSpace = Dataspace::UNKNOWN;
2349
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002351 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002352 case Dataspace::V0_SCRGB:
2353 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002354 case Dataspace::BT2020:
2355 case Dataspace::BT2020_ITU:
2356 case Dataspace::BT2020_LINEAR:
2357 case Dataspace::DISPLAY_BT2020:
2358 bestDataSpace = Dataspace::DISPLAY_BT2020;
2359 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002361 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002362 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002363 case Dataspace::BT2020_PQ:
2364 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002365 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002368 case Dataspace::BT2020_HLG:
2369 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002370 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002371 // When there's mixed PQ content and HLG content, we set the HDR
2372 // data space to be BT2020_PQ and convert HLG to PQ.
2373 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2374 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002375 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376 break;
2377 default:
2378 break;
2379 }
Romain Guy54f154a2017-10-24 21:40:32 +01002380 }
2381
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002382 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002383}
2384
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002385// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002386void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2387 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2389 *outMode = ColorMode::NATIVE;
2390 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002392 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002393 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002394
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002395 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002396 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002397
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002398 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2399
Peiyong Lina3ea5592019-02-10 14:45:00 -08002400 switch (mForceColorMode) {
2401 case ColorMode::SRGB:
2402 bestDataSpace = Dataspace::V0_SRGB;
2403 break;
2404 case ColorMode::DISPLAY_P3:
2405 bestDataSpace = Dataspace::DISPLAY_P3;
2406 break;
2407 default:
2408 break;
2409 }
2410
Peiyong Lindfde5112018-06-05 10:58:41 -07002411 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002412 const bool isHdr =
2413 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002414 if (isHdr) {
2415 bestDataSpace = hdrDataSpace;
2416 }
2417
Chia-I Wu0d711262018-05-21 15:19:35 -07002418 RenderIntent intent;
2419 switch (mDisplayColorSetting) {
2420 case DisplayColorSetting::MANAGED:
2421 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002422 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002423 break;
2424 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002425 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002426 break;
2427 default: // vendor display color setting
2428 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2429 break;
2430 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002431
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002432 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2436 auto display = displayDevice->getCompositionDisplay();
2437 const auto& displayState = display->getState();
2438
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002439 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2441 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002442
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 // If nothing has changed (!dirty), don't recompose.
2444 // If something changed, but we don't currently have any visible layers,
2445 // and didn't when we last did a composition, then skip it this time.
2446 // The second rule does two things:
2447 // - When all layers are removed from a display, we'll emit one black
2448 // frame, then nothing more until we get new layers.
2449 // - When a display is created with a private layer stack, we won't
2450 // emit any black frames until a layer is added to the layer stack.
2451 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002452
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 const char flagPrefix[] = {'-', '+'};
2454 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002455 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2456 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2457 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2458 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002459
Lloyd Pique31cb2942018-10-19 17:23:03 -07002460 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002461
David Sodmanfa9b2af2017-12-24 13:28:59 -08002462 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002464 }
2465}
2466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2468 auto display = displayDevice->getCompositionDisplay();
2469 const auto& displayState = display->getState();
2470
2471 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 return;
David Sodman2b406362017-12-15 13:33:47 -08002473 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002474
Lloyd Pique31cb2942018-10-19 17:23:03 -07002475 status_t result = display->getRenderSurface()->prepareFrame(
2476 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002477 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002479}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002482 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 ALOGV("doComposition");
2484
Lloyd Pique32cbe282018-10-19 13:09:22 -07002485 auto display = displayDevice->getCompositionDisplay();
2486 const auto& displayState = display->getState();
2487
2488 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002489 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002490 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002491
David Sodmanfa9b2af2017-12-24 13:28:59 -08002492 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002493 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002494
Lloyd Pique32cbe282018-10-19 13:09:22 -07002495 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002496 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002497 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002499}
2500
David Sodmanfa9b2af2017-12-24 13:28:59 -08002501void SurfaceFlinger::postFrame()
2502{
2503 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 const auto display = getDefaultDisplayDeviceLocked();
2505 if (display && getHwComposer().isConnected(*display->getId())) {
2506 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002507 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2508 logFrameStats();
2509 }
2510 }
2511}
2512
Lloyd Pique32cbe282018-10-19 13:09:22 -07002513void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002514 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002516
Lloyd Pique32cbe282018-10-19 13:09:22 -07002517 auto display = displayDevice->getCompositionDisplay();
2518 const auto& displayState = display->getState();
2519 const auto displayId = display->getId();
2520
David Sodmanfa9b2af2017-12-24 13:28:59 -08002521 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002522
Lloyd Pique32cbe282018-10-19 13:09:22 -07002523 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 if (displayId) {
2525 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002526 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002527 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002528 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002529 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002530
Chia-I Wu7b549592017-11-15 09:14:57 -08002531 // The layer buffer from the previous frame (if any) is released
2532 // by HWC only when the release fence from this frame (if any) is
2533 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 if (displayId && layer->hasHwcLayer(*displayId)) {
2535 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2536 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002537 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002538
2539 // If the layer was client composited in the previous frame, we
2540 // need to merge with the previous client target acquire fence.
2541 // Since we do not track that, always merge with the current
2542 // client target acquire fence when it is available, even though
2543 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002544 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002545 releaseFence =
2546 Fence::merge("LayerRelease", releaseFence,
2547 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002548 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002549
David Sodman15094112018-10-11 09:39:37 -07002550 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 }
Chia-I Wu83806892017-11-16 10:50:20 -08002552
2553 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002555 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002556 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002558 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002559 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002560 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002561 }
2562 }
2563
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 if (displayId) {
2565 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002566 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568}
2569
Mathias Agopian87baae12012-07-31 12:38:26 -07002570void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571{
Mathias Agopian841cde52012-03-01 15:44:37 -08002572 ATRACE_CALL();
2573
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002574 // here we keep a copy of the drawing state (that is the state that's
2575 // going to be overwritten by handleTransactionLocked()) outside of
2576 // mStateLock so that the side-effects of the State assignment
2577 // don't happen with mStateLock held (which can cause deadlocks).
2578 State drawingState(mDrawingState);
2579
Mathias Agopianca4d3602011-05-19 15:38:14 -07002580 Mutex::Autolock _l(mStateLock);
2581 const nsecs_t now = systemTime();
2582 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
Mathias Agopianca4d3602011-05-19 15:38:14 -07002584 // Here we're guaranteed that some transaction flags are set
2585 // so we can call handleTransactionLocked() unconditionally.
2586 // We call getTransactionFlags(), which will also clear the flags,
2587 // with mStateLock held to guarantee that mCurrentState won't change
2588 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002589
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002590 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002592 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002593
Mathias Agopianca4d3602011-05-19 15:38:14 -07002594 mLastTransactionTime = systemTime() - now;
2595 mDebugInTransaction = 0;
2596 invalidateHwcGeometry();
2597 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002598}
2599
Lloyd Piqueba04e622017-12-14 17:11:26 -08002600void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2601 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 const std::optional<DisplayIdentificationInfo> info =
2603 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 continue;
2607 }
2608
Lloyd Piqueba04e622017-12-14 17:11:26 -08002609 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002611 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 mPhysicalDisplayTokens[info->id] = new BBinder();
2613 DisplayDeviceState state;
2614 state.displayId = info->id;
2615 state.isSecure = true; // All physical displays are currently considered secure.
2616 state.displayName = info->name;
2617 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2618 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002619 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002620 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002621 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002622
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2624 if (index >= 0) {
2625 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2626 mInterceptor->saveDisplayDeletion(state.sequenceId);
2627 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002628 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002630 }
2631
2632 processDisplayChangesLocked();
2633 }
2634
2635 mPendingHotplugEvents.clear();
2636}
2637
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002638void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002639 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002640 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2641 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002642 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002643 mEventThread->onHotplugReceived(displayId, connected);
2644 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002645 }
2646}
2647
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002650 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002651 const sp<IGraphicBufferProducer>& producer) {
2652 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002653 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002655 creationArgs.isSecure = state.isSecure;
2656 creationArgs.displaySurface = dispSurface;
2657 creationArgs.hasWideColorGamut = false;
2658 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002659
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002660 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 creationArgs.isPrimary = isInternalDisplay;
2662
2663 if (useColorManagement && displayId) {
2664 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002666 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002667 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002669
Dominik Laskowski7e045462018-05-30 13:02:02 -07002670 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002671 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002672 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673 }
tangrobin6753a022018-08-10 10:58:54 +08002674 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 if (displayId) {
2677 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002678 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002679 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002680 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681
Lloyd Pique90c115d2018-09-18 21:39:42 -07002682 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002683 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002684 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002685
Lloyd Pique99d3da52018-01-22 17:48:03 -08002686 // Make sure that composition can never be stalled by a virtual display
2687 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002688 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002689 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2691 }
2692
Dominik Laskowski075d3172018-05-24 15:50:06 -07002693 creationArgs.displayInstallOrientation =
2694 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002695
Lloyd Pique99d3da52018-01-22 17:48:03 -08002696 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002697 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002698
Lloyd Pique90c115d2018-09-18 21:39:42 -07002699 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700
2701 if (maxFrameBufferAcquiredBuffers >= 3) {
2702 nativeWindowSurface->preallocateBuffers();
2703 }
2704
2705 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002706 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002707 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002708 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002709 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002710 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002711 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2712 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002713 if (!state.isVirtual()) {
2714 LOG_ALWAYS_FATAL_IF(!displayId);
2715 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002716 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002718 display->setLayerStack(state.layerStack);
2719 display->setProjection(state.orientation, state.viewport, state.frame);
2720 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002723}
2724
Lloyd Pique347200f2017-12-14 17:00:15 -08002725void SurfaceFlinger::processDisplayChangesLocked() {
2726 // here we take advantage of Vector's copy-on-write semantics to
2727 // improve performance by skipping the transaction entirely when
2728 // know that the lists are identical
2729 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2730 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2731 if (!curr.isIdenticalTo(draw)) {
2732 mVisibleRegionsDirty = true;
2733 const size_t cc = curr.size();
2734 size_t dc = draw.size();
2735
2736 // find the displays that were removed
2737 // (ie: in drawing state but not in current state)
2738 // also handle displays that changed
2739 // (ie: displays that are in both lists)
2740 for (size_t i = 0; i < dc;) {
2741 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2742 if (j < 0) {
2743 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002745 // Save display ID before disconnecting.
2746 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002747 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002748
2749 if (!display->isVirtual()) {
2750 LOG_ALWAYS_FATAL_IF(!displayId);
2751 dispatchDisplayHotplugEvent(displayId->value, false);
2752 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002753 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002754
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 } else {
2757 // this display is in both lists. see if something changed.
2758 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2761 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2762 if (state_binder != draw_binder) {
2763 // changing the surface is like destroying and
2764 // recreating the DisplayDevice, so we just remove it
2765 // from the drawing state, so that it get re-added
2766 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002768 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002769 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002770 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 mDrawingState.displays.removeItemsAt(i);
2772 dc--;
2773 // at this point we must loop to the next item
2774 continue;
2775 }
2776
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 }
2781 if ((state.orientation != draw[i].orientation) ||
2782 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002783 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 }
2785 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002786 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 }
2788 }
2789 }
2790 ++i;
2791 }
2792
2793 // find displays that were added
2794 // (ie: in current state but not in drawing state)
2795 for (size_t i = 0; i < cc; i++) {
2796 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2797 const DisplayDeviceState& state(curr[i]);
2798
Lloyd Pique542307f2018-10-19 13:24:08 -07002799 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002800 sp<IGraphicBufferProducer> producer;
2801 sp<IGraphicBufferProducer> bqProducer;
2802 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002803 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002804
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002806 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 // Virtual displays without a surface are dormant:
2808 // they have external state (layer stack, projection,
2809 // etc.) but no internal state (i.e. a DisplayDevice).
2810 if (state.surface != nullptr) {
2811 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002813 int width = 0;
2814 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2815 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2816 int height = 0;
2817 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2818 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2819 int intFormat = 0;
2820 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2821 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002822 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002823
Dominik Laskowski075d3172018-05-24 15:50:06 -07002824 displayId =
2825 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002826 }
2827
2828 // TODO: Plumb requested format back up to consumer
2829
2830 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002831 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 bqProducer, bqConsumer,
2833 state.displayName);
2834
2835 dispSurface = vds;
2836 producer = vds;
2837 }
2838 } else {
2839 ALOGE_IF(state.surface != nullptr,
2840 "adding a supported display, but rendering "
2841 "surface is provided (%p), ignoring it",
2842 state.surface.get());
2843
Dominik Laskowski075d3172018-05-24 15:50:06 -07002844 displayId = state.displayId;
2845 LOG_ALWAYS_FATAL_IF(!displayId);
2846 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002847 producer = bqProducer;
2848 }
2849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002851 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002853 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002855 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002856 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002857 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002858 }
2859 }
2860 }
2861 }
2862 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002863
2864 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002865}
2866
Mathias Agopian87baae12012-07-31 12:38:26 -07002867void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002868{
Dan Stoza7dde5992015-05-22 09:51:44 -07002869 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002870 mCurrentState.traverseInZOrder([](Layer* layer) {
2871 layer->notifyAvailableFrames();
2872 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002873
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 /*
2875 * Traversal of the children
2876 * (perform the transaction for each of them if needed)
2877 */
2878
Mathias Agopian3559b072012-08-15 13:46:03 -07002879 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002880 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002882 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
2884 const uint32_t flags = layer->doTransaction(0);
2885 if (flags & Layer::eVisibleRegion)
2886 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002887
2888 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002889 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002890 }
Robert Carr2047fae2016-11-28 14:09:09 -08002891 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 }
2893
2894 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002895 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 */
2897
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002899 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002900 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002901 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002904 // The transform hint might have changed for some layers
2905 // (either because a display has changed, or because a layer
2906 // as changed).
2907 //
2908 // Walk through all the layers in currentLayers,
2909 // and update their transform hint.
2910 //
2911 // If a layer is visible only on a single display, then that
2912 // display is used to calculate the hint, otherwise we use the
2913 // default display.
2914 //
2915 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2916 // the hint is set before we acquire a buffer from the surface texture.
2917 //
2918 // NOTE: layer transactions have taken place already, so we use their
2919 // drawing state. However, SurfaceFlinger's own transaction has not
2920 // happened yet, so we must use the current state layer list
2921 // (soon to become the drawing state list).
2922 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002923 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002924 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002925 bool first = true;
2926 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002927 // NOTE: we rely on the fact that layers are sorted by
2928 // layerStack first (so we don't have to traverse the list
2929 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002931 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002932 currentlayerStack = layerStack;
2933 // figure out if this layerstack is mirrored
2934 // (more than one display) if so, pick the default display,
2935 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 hintDisplay = nullptr;
2937 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002938 if (display->getCompositionDisplay()
2939 ->belongsInOutput(layer->getLayerStack(),
2940 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002941 if (hintDisplay) {
2942 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002943 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002944 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002946 }
2947 }
2948 }
2949 }
Chet Haase91d25932013-04-11 15:24:55 -07002950
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002951 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002952 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2953 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002954
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002955 // could be null when this layer is using a layerStack
2956 // that is not visible on any display. Also can occur at
2957 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002958 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002959 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002960
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002961 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002962 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002963 if (hintDisplay) {
2964 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002965 }
Robert Carr2047fae2016-11-28 14:09:09 -08002966
2967 first = false;
2968 });
Mathias Agopian84300952012-11-21 16:02:13 -08002969 }
2970
2971
Mathias Agopian3559b072012-08-15 13:46:03 -07002972 /*
2973 * Perform our own transaction if needed
2974 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002975
2976 if (mLayersAdded) {
2977 mLayersAdded = false;
2978 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002979 mVisibleRegionsDirty = true;
2980 }
2981
2982 // some layers might have been removed, so
2983 // we need to update the regions they're exposing.
2984 if (mLayersRemoved) {
2985 mLayersRemoved = false;
2986 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002987 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002989 // this layer is not visible anymore
2990 // TODO: we could traverse the tree from front to back and
2991 // compute the actual visible region
2992 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 Region visibleReg;
2994 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002995 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002996 }
Robert Carr2047fae2016-11-28 14:09:09 -08002997 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998 }
2999
3000 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003001}
3002
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003003void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003004 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003005 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003006 return;
3007 }
3008
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003009 if (mVisibleRegionsDirty || mInputInfoChanged) {
3010 mInputInfoChanged = false;
3011 updateInputWindowInfo();
3012 }
3013
3014 executeInputWindowCommands();
3015}
3016
3017void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003018 Vector<InputWindowInfo> inputHandles;
3019
3020 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3021 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003022 // When calculating the screen bounds we ignore the transparent region since it may
3023 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003024 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003025 }
3026 });
3027 mInputFlinger->setInputWindows(inputHandles);
3028}
3029
chaviwfbe5d9c2018-12-26 12:23:37 -08003030void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003031 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3032 if (transferTouchFocusCommand.fromToken != nullptr &&
3033 transferTouchFocusCommand.toToken != nullptr &&
3034 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3035 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3036 transferTouchFocusCommand.toToken);
3037 }
3038 }
3039
3040 mInputWindowCommands.clear();
3041}
3042
Riley Andrews03414a12014-07-01 14:22:59 -07003043void SurfaceFlinger::updateCursorAsync()
3044{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003045 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003046 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003047 continue;
3048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3051 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003052 }
3053 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054}
3055
chaviw61626f22018-11-15 16:26:27 -08003056void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3057 if (layer->hasReadyFrame()) {
3058 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3059 if (layer->shouldPresentNow(expectedPresentTime)) {
3060 bool ignored = false;
3061 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3062 }
3063 }
3064 layer->releasePendingBuffer(systemTime());
3065}
3066
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067void SurfaceFlinger::commitTransaction()
3068{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003069 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003070 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 for (const auto& l : mLayersPendingRemoval) {
3072 recordBufferingStats(l->getName().string(),
3073 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003074
3075 // We need to release the HWC layers when the Layer is removed
3076 // from the current state otherwise the HWC layer just continues
3077 // showing at its last configured state until we eventually
3078 // abandon the buffer queue.
3079 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003080 l->destroyHwcLayersForAllDisplays();
3081 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003082 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003083 }
3084 mLayersPendingRemoval.clear();
3085 }
3086
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003087 // If this transaction is part of a window animation then the next frame
3088 // we composite should be considered an animation as well.
3089 mAnimCompositionPending = mAnimTransactionPending;
3090
Mathias Agopian4fec8732012-06-29 14:12:52 -07003091 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003092 // clear the "changed" flags in current state
3093 mCurrentState.colorMatrixChanged = false;
3094
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 mDrawingState.traverseInZOrder([](Layer* layer) {
3096 layer->commitChildList();
3097 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003098 mTransactionPending = false;
3099 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101}
3102
Lloyd Pique32cbe282018-10-19 13:09:22 -07003103void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003105 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003106 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003107
Lloyd Pique32cbe282018-10-19 13:09:22 -07003108 auto display = displayDevice->getCompositionDisplay();
3109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 Region aboveOpaqueLayers;
3111 Region aboveCoveredLayers;
3112 Region dirty;
3113
Mathias Agopian87baae12012-07-31 12:38:26 -07003114 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115
Robert Carr2047fae2016-11-28 14:09:09 -08003116 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003117 // start with the whole surface at its current location
3118 const Layer::State& s(layer->getDrawingState());
3119
Jesse Hall01e29052013-02-19 16:13:35 -08003120 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003121 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003122 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003123 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003124
Mathias Agopianab028732010-03-16 16:41:46 -07003125 /*
3126 * opaqueRegion: area of a surface that is fully opaque.
3127 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003129
3130 /*
3131 * visibleRegion: area of a surface that is visible on screen
3132 * and not fully transparent. This is essentially the layer's
3133 * footprint minus the opaque regions above it.
3134 * Areas covered by a translucent surface are considered visible.
3135 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003137
3138 /*
3139 * coveredRegion: area of a surface that is covered by all
3140 * visible regions above it (which includes the translucent areas).
3141 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003143
Jesse Halla8026d22012-09-25 13:25:04 -07003144 /*
3145 * transparentRegion: area of a surface that is hinted to be completely
3146 * transparent. This is only used to tell when the layer has no visible
3147 * non-transparent regions and can be removed from the layer list. It
3148 * does not affect the visibleRegion of this layer or any layers
3149 * beneath it. The hint may not be correct if apps don't respect the
3150 * SurfaceView restrictions (which, sadly, some don't).
3151 */
3152 Region transparentRegion;
3153
Mathias Agopianab028732010-03-16 16:41:46 -07003154
3155 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003156 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003157 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003161 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003162 if (!visibleRegion.isEmpty()) {
3163 // Remove the transparent area from the visible region
3164 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003165 if (tr.preserveRects()) {
3166 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003167 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003168 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003169 // transformation too complex, can't do the
3170 // transparent region optimization.
3171 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003172 }
Mathias Agopianab028732010-03-16 16:41:46 -07003173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174
Mathias Agopianab028732010-03-16 16:41:46 -07003175 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003177 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003178 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003179 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003180 // the opaque region is the layer's footprint
3181 opaqueRegion = visibleRegion;
3182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 }
3184 }
3185
Robert Carre5f4f692018-01-12 13:12:28 -08003186 if (visibleRegion.isEmpty()) {
3187 layer->clearVisibilityRegions();
3188 return;
3189 }
3190
Mathias Agopianab028732010-03-16 16:41:46 -07003191 // Clip the covered region to the visible region
3192 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3193
3194 // Update aboveCoveredLayers for next (lower) layer
3195 aboveCoveredLayers.orSelf(visibleRegion);
3196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 // subtract the opaque region covered by the layers above us
3198 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199
3200 // compute this layer's dirty region
3201 if (layer->contentDirty) {
3202 // we need to invalidate the whole region
3203 dirty = visibleRegion;
3204 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003205 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 layer->contentDirty = false;
3207 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003208 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003209 * the exposed region consists of two components:
3210 * 1) what's VISIBLE now and was COVERED before
3211 * 2) what's EXPOSED now less what was EXPOSED before
3212 *
3213 * note that (1) is conservative, we start with the whole
3214 * visible region but only keep what used to be covered by
3215 * something -- which mean it may have been exposed.
3216 *
3217 * (2) handles areas that were not covered by anything but got
3218 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003219 */
Mathias Agopianab028732010-03-16 16:41:46 -07003220 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003221 const Region oldVisibleRegion = layer->visibleRegion;
3222 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003223 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3224 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226 dirty.subtractSelf(aboveOpaqueLayers);
3227
3228 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003229 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230
Mathias Agopianab028732010-03-16 16:41:46 -07003231 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003233
Jesse Halla8026d22012-09-25 13:25:04 -07003234 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 layer->setVisibleRegion(visibleRegion);
3236 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003237 layer->setVisibleNonTransparentRegion(
3238 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003239 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240
Mathias Agopian87baae12012-07-31 12:38:26 -07003241 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Chia-I Wuab0c3192017-08-01 11:29:00 -07003244void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003245 for (const auto& [token, displayDevice] : mDisplays) {
3246 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003247 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003248 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003249 }
3250 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003251}
3252
Daniel Solomon42d04562019-01-20 21:03:19 -08003253void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3254 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3255 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3256 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3257 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3258 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3259 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3260 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3261 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3262 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3263 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3264 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3265 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3266}
3267
Dan Stoza6b9454d2014-11-07 16:00:59 -08003268bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003270 ALOGV("handlePageFlip");
3271
Brian Andersond6927fb2016-07-23 23:37:30 -07003272 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273
Mathias Agopian4fec8732012-06-29 14:12:52 -07003274 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003275 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003276 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003277
3278 // Store the set of layers that need updates. This set must not change as
3279 // buffers are being latched, as this could result in a deadlock.
3280 // Example: Two producers share the same command stream and:
3281 // 1.) Layer 0 is latched
3282 // 2.) Layer 0 gets a new frame
3283 // 2.) Layer 1 gets a new frame
3284 // 3.) Layer 1 is latched.
3285 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3286 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003287 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003288 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003289 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003290 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3291 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003292 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003293 } else {
3294 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003295 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003296 } else {
3297 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003298 }
Robert Carr2047fae2016-11-28 14:09:09 -08003299 });
3300
Lloyd Piquef2c79392018-12-20 16:23:33 -08003301 if (!mLayersWithQueuedFrames.empty()) {
3302 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3303 // writes to Layer current state. See also b/119481871
3304 Mutex::Autolock lock(mStateLock);
3305
3306 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003307 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3308 mLayersPendingRefresh.push_back(layer);
3309 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003310 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003311 if (layer->isBufferLatched()) {
3312 newDataLatched = true;
3313 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003314 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003315 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003316
Alec Mouri86770e52018-09-24 22:40:58 +00003317 // Clear the renderengine fence here...
3318 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3319 // clear instead of sp::clear.
3320 getBE().flushFence = Fence::NO_FENCE;
3321
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003322 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003323
3324 // If we will need to wake up at some time in the future to deal with a
3325 // queued frame that shouldn't be displayed during this vsync period, wake
3326 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003327 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003328 signalLayerUpdate();
3329 }
3330
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003331 // enter boot animation on first buffer latch
3332 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3333 ALOGI("Enter boot animation");
3334 mBootStage = BootStage::BOOTANIMATION;
3335 }
3336
Dan Stoza6b9454d2014-11-07 16:00:59 -08003337 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003338 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339}
3340
Mathias Agopianad456f92011-01-13 17:53:01 -08003341void SurfaceFlinger::invalidateHwcGeometry()
3342{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003344}
3345
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003347 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003348 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003349 // We only need to actually compose the display if:
3350 // 1) It is being handled by hardware composer, which may need this to
3351 // keep its virtual display state machine in sync, or
3352 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003353 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003354 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003355 return;
3356 }
3357
Dan Stoza9e56aa02015-11-02 13:00:03 -08003358 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003359 base::unique_fd readyFence;
3360 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003361
3362 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003363 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364}
3365
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003366bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3367 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003368 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003370
Lloyd Pique32cbe282018-10-19 13:09:22 -07003371 auto display = displayDevice->getCompositionDisplay();
3372 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003373 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003374
3375 const Region bounds(displayState.bounds);
3376 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003377 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003378 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003379
Peiyong Lind3788632018-09-18 16:01:31 -07003380 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003381 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003382
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 renderengine::DisplaySettings clientCompositionDisplay;
3384 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3385 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003386
Dan Stoza9e56aa02015-11-02 13:00:03 -08003387 if (hasClientComposition) {
3388 ALOGV("hasClientComposition");
3389
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003391
3392 if (buf == nullptr) {
3393 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3394 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003395 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003396 return false;
3397 }
3398
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003399 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3400 clientCompositionDisplay.clip = displayState.scissor;
3401 const ui::Transform& displayTransform = displayState.transform;
3402 mat4 m;
3403 m[0][0] = displayTransform[0][0];
3404 m[0][1] = displayTransform[0][1];
3405 m[0][3] = displayTransform[0][2];
3406 m[1][0] = displayTransform[1][0];
3407 m[1][1] = displayTransform[1][1];
3408 m[1][3] = displayTransform[1][2];
3409 m[3][0] = displayTransform[2][0];
3410 m[3][1] = displayTransform[2][1];
3411 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003412
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003413 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003415 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003416 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003417 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003418 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003419 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003420 clientCompositionDisplay.outputDataspace = outputDataspace;
3421 clientCompositionDisplay.maxLuminance =
3422 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003423
Lloyd Pique441d5042018-10-18 16:49:51 -07003424 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003425 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003426 getHwComposer()
3427 .hasDisplayCapability(displayId,
3428 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003429
Peiyong Lind3788632018-09-18 16:01:31 -07003430 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003431 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3432 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003433 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003434 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003435 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003436
Mathias Agopian85d751c2012-08-29 16:59:24 -07003437 /*
3438 * and then, render the layers targeted at the framebuffer
3439 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003440
Dan Stoza9e56aa02015-11-02 13:00:03 -08003441 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003442 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003443 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003444 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003445 const Region viewportRegion(displayState.viewport);
3446 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003447 ALOGV("Layer: %s", layer->getName().string());
3448 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003450 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 case HWC2::Composition::Cursor:
3452 case HWC2::Composition::Device:
3453 case HWC2::Composition::Sideband:
3454 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003455 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003456 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003457 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003458 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003459 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003460 // never clear the very first layer since we're
3461 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003462 renderengine::LayerSettings layerSettings;
3463 Region dummyRegion;
3464 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3465 layerSettings);
3466
3467 if (prepared) {
3468 layerSettings.source.buffer.buffer = nullptr;
3469 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3470 layerSettings.alpha = half(0.0);
3471 layerSettings.disableBlending = true;
3472 clientCompositionLayers.push_back(layerSettings);
3473 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003474 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003475 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003476 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003477 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003478 renderengine::LayerSettings layerSettings;
3479 bool prepared =
3480 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3481 if (prepared) {
3482 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003483 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003484 break;
3485 }
3486 default:
3487 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003488 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 } else {
3490 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003491 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003492 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003493 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003494
Alec Mouri820c7402019-01-23 13:02:39 -08003495 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003496 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003497 clientCompositionDisplay.clearRegion = clearRegion;
3498 if (!debugRegion.isEmpty()) {
3499 Region::const_iterator it = debugRegion.begin();
3500 Region::const_iterator end = debugRegion.end();
3501 while (it != end) {
3502 const Rect& rect = *it++;
3503 renderengine::LayerSettings layerSettings;
3504 layerSettings.source.buffer.buffer = nullptr;
3505 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3506 layerSettings.geometry.boundaries = rect.toFloatRect();
3507 layerSettings.alpha = half(1.0);
3508 clientCompositionLayers.push_back(layerSettings);
3509 }
3510 }
3511 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3512 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003513 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003514 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515}
3516
Chia-I Wu28e3a252018-09-07 12:05:02 -07003517void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003518 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003519 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520}
3521
Dan Stoza7d89d062015-04-30 13:29:25 -07003522status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003523 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003524 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003525 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003526 const sp<Layer>& parent,
3527 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003528{
Dan Stoza7d89d062015-04-30 13:29:25 -07003529 // add this layer to the current state list
3530 {
3531 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003532 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003533 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3534 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003535 return NO_MEMORY;
3536 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003537 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003538 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003539 } else if (parent == nullptr) {
3540 lbc->onRemovedFromCurrentState();
3541 } else if (parent->isRemovedFromCurrentState()) {
3542 parent->addChild(lbc);
3543 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003544 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 parent->addChild(lbc);
3546 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003547
Yiwei Zhang243b3782018-05-15 17:40:04 -07003548 if (gbc != nullptr) {
3549 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3550 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3551 mMaxGraphicBufferProducerListSize,
3552 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3553 mGraphicBufferProducerList.size(),
3554 mMaxGraphicBufferProducerListSize, mNumLayers);
3555 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003556 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003557 }
3558
Mathias Agopian96f08192010-06-02 23:28:45 -07003559 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003560 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003561
Dan Stoza7d89d062015-04-30 13:29:25 -07003562 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003563}
3564
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003565uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003566 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003567}
3568
Mathias Agopian3f844832013-08-07 21:24:32 -07003569uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003570 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571}
3572
Mathias Agopian3f844832013-08-07 21:24:32 -07003573uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003574 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003575}
3576
3577uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003578 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003579 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003580 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003582 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 }
3584 return old;
3585}
3586
Marissa Wall713b63f2018-10-17 15:42:43 -07003587bool SurfaceFlinger::flushTransactionQueues() {
3588 Mutex::Autolock _l(mStateLock);
3589 auto it = mTransactionQueues.begin();
3590 while (it != mTransactionQueues.end()) {
3591 auto& [applyToken, transactionQueue] = *it;
3592
3593 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003594 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3595 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003596 break;
3597 }
chaviw273171b2018-12-26 11:46:30 -08003598 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003599 transactionQueue.pop();
3600 }
3601
3602 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3603 }
3604 return mTransactionQueues.empty();
3605}
3606
chaviwca27f252018-02-06 16:46:39 -08003607bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3608 for (const ComposerState& state : states) {
3609 // Here we need to check that the interface we're given is indeed
3610 // one of our own. A malicious client could give us a nullptr
3611 // IInterface, or one of its own or even one of our own but a
3612 // different type. All these situations would cause us to crash.
3613 if (state.client == nullptr) {
3614 return true;
3615 }
3616
3617 sp<IBinder> binder = IInterface::asBinder(state.client);
3618 if (binder == nullptr) {
3619 return true;
3620 }
3621
3622 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3623 return true;
3624 }
3625 }
3626 return false;
3627}
3628
Marissa Wall17b4e452018-12-26 16:32:34 -08003629bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3630 const Vector<ComposerState>& states) {
3631 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3632 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3633 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3634 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3635 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3636 return false;
3637 }
3638
Marissa Wall713b63f2018-10-17 15:42:43 -07003639 for (const ComposerState& state : states) {
3640 const layer_state_t& s = state.state;
3641 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3642 continue;
3643 }
3644 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003645 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003646 }
3647 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003648 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003649}
3650
3651void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3652 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003653 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003654 const InputWindowCommands& inputWindowCommands,
3655 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003656 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003657 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003658
chaviwca27f252018-02-06 16:46:39 -08003659 if (containsAnyInvalidClientState(states)) {
3660 return;
3661 }
3662
Marissa Wall713b63f2018-10-17 15:42:43 -07003663 // If its TransactionQueue already has a pending TransactionState or if it is pending
3664 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003665 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3666 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003667 setTransactionFlags(eTransactionNeeded);
3668 return;
3669 }
3670
chaviw273171b2018-12-26 11:46:30 -08003671 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003672}
3673
3674void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003675 const Vector<DisplayState>& displays, uint32_t flags,
3676 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003677 uint32_t transactionFlags = 0;
3678
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 if (flags & eAnimation) {
3680 // For window updates that are part of an animation we must wait for
3681 // previous animation "frames" to be handled.
3682 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003683 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 if (CC_UNLIKELY(err != NO_ERROR)) {
3685 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003686 // caller after a few seconds.
3687 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3688 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003689 mAnimTransactionPending = false;
3690 break;
3691 }
3692 }
3693 }
3694
chaviwca27f252018-02-06 16:46:39 -08003695 for (const DisplayState& display : displays) {
3696 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003697 }
3698
Marissa Walle2ffb422018-10-12 11:33:52 -07003699 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003700 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003701 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003702 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003703 // If the state doesn't require a traversal and there are callbacks, send them now
3704 if (!(clientStateFlags & eTraversalNeeded)) {
3705 mTransactionCompletedThread.sendCallbacks();
3706 }
3707 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003708
chaviw273171b2018-12-26 11:46:30 -08003709 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3710
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003711 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3712 // anyway. This can be used as a flush mechanism for previous async transactions.
3713 // Empty animation transaction can be used to simulate back-pressure, so also force a
3714 // transaction for empty animation transactions.
3715 if (transactionFlags == 0 &&
3716 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003717 transactionFlags = eTransactionNeeded;
3718 }
3719
Mathias Agopian386aa982011-11-07 21:58:03 -08003720 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003721 if (mInterceptor->isEnabled()) {
3722 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003723 }
Irvel468051e2016-06-13 16:44:44 -07003724
Mathias Agopian386aa982011-11-07 21:58:03 -08003725 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003726 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3727 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003728 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003729
3730 // if this is a synchronous transaction, wait for it to take effect
3731 // before returning.
3732 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003733 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003734 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003735 if (flags & eAnimation) {
3736 mAnimTransactionPending = true;
3737 }
3738 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003739 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3740 if (CC_UNLIKELY(err != NO_ERROR)) {
3741 // just in case something goes wrong in SF, return to the
3742 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003743 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3744 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003745 break;
3746 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 }
3749}
3750
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003751uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3752 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3753 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003754
Mathias Agopiane57f2922012-08-09 16:29:12 -07003755 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003756 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3757
3758 const uint32_t what = s.what;
3759 if (what & DisplayState::eSurfaceChanged) {
3760 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3761 state.surface = s.surface;
3762 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003763 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003764 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003765 if (what & DisplayState::eLayerStackChanged) {
3766 if (state.layerStack != s.layerStack) {
3767 state.layerStack = s.layerStack;
3768 flags |= eDisplayTransactionNeeded;
3769 }
3770 }
3771 if (what & DisplayState::eDisplayProjectionChanged) {
3772 if (state.orientation != s.orientation) {
3773 state.orientation = s.orientation;
3774 flags |= eDisplayTransactionNeeded;
3775 }
3776 if (state.frame != s.frame) {
3777 state.frame = s.frame;
3778 flags |= eDisplayTransactionNeeded;
3779 }
3780 if (state.viewport != s.viewport) {
3781 state.viewport = s.viewport;
3782 flags |= eDisplayTransactionNeeded;
3783 }
3784 }
3785 if (what & DisplayState::eDisplaySizeChanged) {
3786 if (state.width != s.width) {
3787 state.width = s.width;
3788 flags |= eDisplayTransactionNeeded;
3789 }
3790 if (state.height != s.height) {
3791 state.height = s.height;
3792 flags |= eDisplayTransactionNeeded;
3793 }
3794 }
3795
Mathias Agopiane57f2922012-08-09 16:29:12 -07003796 return flags;
3797}
3798
Robert Carrd4ae7f32018-06-07 16:10:57 -07003799bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3800 IPCThreadState* ipc = IPCThreadState::self();
3801 const int pid = ipc->getCallingPid();
3802 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003803 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003804 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003805 return false;
3806 }
3807 return true;
3808}
3809
chaviwca27f252018-02-06 16:46:39 -08003810uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3811 const layer_state_t& s = composerState.state;
3812 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3813
Mathias Agopian13127d82013-03-05 17:47:11 -08003814 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003815 if (layer == nullptr) {
3816 return 0;
3817 }
3818
chaviw8b3871a2017-11-01 17:41:01 -07003819 uint32_t flags = 0;
3820
Garfield Tan8a3083e2018-12-03 13:21:07 -08003821 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003822 bool geometryAppliesWithResize =
3823 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003824
3825 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3826 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003827 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003828 layer->pushPendingState();
3829 }
3830
chaviw8b3871a2017-11-01 17:41:01 -07003831 if (what & layer_state_t::ePositionChanged) {
3832 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3833 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003834 }
chaviw8b3871a2017-11-01 17:41:01 -07003835 }
3836 if (what & layer_state_t::eLayerChanged) {
3837 // NOTE: index needs to be calculated before we update the state
3838 const auto& p = layer->getParent();
3839 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003840 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003841 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003842 mCurrentState.layersSortedByZ.removeAt(idx);
3843 mCurrentState.layersSortedByZ.add(layer);
3844 // we need traversal (state changed)
3845 // AND transaction (list changed)
3846 flags |= eTransactionNeeded|eTraversalNeeded;
3847 }
chaviw8b3871a2017-11-01 17:41:01 -07003848 } else {
3849 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003850 flags |= eTransactionNeeded|eTraversalNeeded;
3851 }
3852 }
chaviw8b3871a2017-11-01 17:41:01 -07003853 }
3854 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003855 // NOTE: index needs to be calculated before we update the state
3856 const auto& p = layer->getParent();
3857 if (p == nullptr) {
3858 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3859 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3860 mCurrentState.layersSortedByZ.removeAt(idx);
3861 mCurrentState.layersSortedByZ.add(layer);
3862 // we need traversal (state changed)
3863 // AND transaction (list changed)
3864 flags |= eTransactionNeeded|eTraversalNeeded;
3865 }
3866 } else {
3867 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3868 flags |= eTransactionNeeded|eTraversalNeeded;
3869 }
chaviw8b3871a2017-11-01 17:41:01 -07003870 }
3871 }
3872 if (what & layer_state_t::eSizeChanged) {
3873 if (layer->setSize(s.w, s.h)) {
3874 flags |= eTraversalNeeded;
3875 }
3876 }
3877 if (what & layer_state_t::eAlphaChanged) {
3878 if (layer->setAlpha(s.alpha))
3879 flags |= eTraversalNeeded;
3880 }
3881 if (what & layer_state_t::eColorChanged) {
3882 if (layer->setColor(s.color))
3883 flags |= eTraversalNeeded;
3884 }
Peiyong Lind3788632018-09-18 16:01:31 -07003885 if (what & layer_state_t::eColorTransformChanged) {
3886 if (layer->setColorTransform(s.colorTransform)) {
3887 flags |= eTraversalNeeded;
3888 }
3889 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003890 if (what & layer_state_t::eBackgroundColorChanged) {
3891 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3892 flags |= eTraversalNeeded;
3893 }
3894 }
chaviw8b3871a2017-11-01 17:41:01 -07003895 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003896 // TODO: b/109894387
3897 //
3898 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3899 // rotation. To see the problem observe that if we have a square parent, and a child
3900 // of the same size, then we rotate the child 45 degrees around it's center, the child
3901 // must now be cropped to a non rectangular 8 sided region.
3902 //
3903 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3904 // private API, and the WindowManager only uses rotation in one case, which is on a top
3905 // level layer in which cropping is not an issue.
3906 //
3907 // However given that abuse of rotation matrices could lead to surfaces extending outside
3908 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3909 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3910 // transformations.
3911 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003912 flags |= eTraversalNeeded;
3913 }
3914 if (what & layer_state_t::eTransparentRegionChanged) {
3915 if (layer->setTransparentRegionHint(s.transparentRegion))
3916 flags |= eTraversalNeeded;
3917 }
3918 if (what & layer_state_t::eFlagsChanged) {
3919 if (layer->setFlags(s.flags, s.mask))
3920 flags |= eTraversalNeeded;
3921 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003922 if (what & layer_state_t::eCropChanged_legacy) {
3923 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003924 flags |= eTraversalNeeded;
3925 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003926 if (what & layer_state_t::eCornerRadiusChanged) {
3927 if (layer->setCornerRadius(s.cornerRadius))
3928 flags |= eTraversalNeeded;
3929 }
chaviw8b3871a2017-11-01 17:41:01 -07003930 if (what & layer_state_t::eLayerStackChanged) {
3931 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3932 // We only allow setting layer stacks for top level layers,
3933 // everything else inherits layer stack from its parent.
3934 if (layer->hasParent()) {
3935 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3936 layer->getName().string());
3937 } else if (idx < 0) {
3938 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3939 "that also does not appear in the top level layer list. Something"
3940 " has gone wrong.", layer->getName().string());
3941 } else if (layer->setLayerStack(s.layerStack)) {
3942 mCurrentState.layersSortedByZ.removeAt(idx);
3943 mCurrentState.layersSortedByZ.add(layer);
3944 // we need traversal (state changed)
3945 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003946 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003947 }
3948 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003949 if (what & layer_state_t::eDeferTransaction_legacy) {
3950 if (s.barrierHandle_legacy != nullptr) {
3951 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3952 } else if (s.barrierGbp_legacy != nullptr) {
3953 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003954 if (authenticateSurfaceTextureLocked(gbp)) {
3955 const auto& otherLayer =
3956 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003957 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003958 } else {
3959 ALOGE("Attempt to defer transaction to to an"
3960 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003961 }
3962 }
chaviw8b3871a2017-11-01 17:41:01 -07003963 // We don't trigger a traversal here because if no other state is
3964 // changed, we don't want this to cause any more work
3965 }
3966 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003967 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003968 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003969 if (!hadParent) {
3970 mCurrentState.layersSortedByZ.remove(layer);
3971 }
chaviw8b3871a2017-11-01 17:41:01 -07003972 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003973 }
chaviw8b3871a2017-11-01 17:41:01 -07003974 }
3975 if (what & layer_state_t::eReparentChildren) {
3976 if (layer->reparentChildren(s.reparentHandle)) {
3977 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003978 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003979 }
chaviw8b3871a2017-11-01 17:41:01 -07003980 if (what & layer_state_t::eDetachChildren) {
3981 layer->detachChildren();
3982 }
3983 if (what & layer_state_t::eOverrideScalingModeChanged) {
3984 layer->setOverrideScalingMode(s.overrideScalingMode);
3985 // We don't trigger a traversal here because if no other state is
3986 // changed, we don't want this to cause any more work
3987 }
Marissa Wall61c58622018-07-18 10:12:20 -07003988 if (what & layer_state_t::eTransformChanged) {
3989 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3990 }
3991 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3992 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3993 flags |= eTraversalNeeded;
3994 }
3995 if (what & layer_state_t::eCropChanged) {
3996 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3997 }
Marissa Wall861616d2018-10-22 12:52:23 -07003998 if (what & layer_state_t::eFrameChanged) {
3999 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4000 }
Marissa Wall61c58622018-07-18 10:12:20 -07004001 if (what & layer_state_t::eAcquireFenceChanged) {
4002 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4003 }
4004 if (what & layer_state_t::eDataspaceChanged) {
4005 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4006 }
4007 if (what & layer_state_t::eHdrMetadataChanged) {
4008 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4009 }
4010 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4011 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4012 }
4013 if (what & layer_state_t::eApiChanged) {
4014 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4015 }
4016 if (what & layer_state_t::eSidebandStreamChanged) {
4017 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4018 }
Robert Carr720e5062018-07-30 17:45:14 -07004019 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004020 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4021 layer->setInputInfo(s.inputInfo);
4022 flags |= eTraversalNeeded;
4023 } else {
4024 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4025 }
Robert Carr720e5062018-07-30 17:45:14 -07004026 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004027 if (what & layer_state_t::eMetadataChanged) {
4028 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4029 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004030 std::vector<sp<CallbackHandle>> callbackHandles;
4031 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4032 mTransactionCompletedThread.run();
4033 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4034 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4035 }
4036 }
Marissa Wall73411622019-01-25 10:45:41 -08004037
4038 if (what & layer_state_t::eBufferChanged) {
4039 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4040 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4041 s.buffer);
4042 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004043 if (what & layer_state_t::eCachedBufferChanged) {
4044 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004045 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4046 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004047 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4048 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004049 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4050 // Do not put anything that updates layer state or modifies flags after
4051 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004052 return flags;
4053}
4054
chaviw273171b2018-12-26 11:46:30 -08004055uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4056 uint32_t flags = 0;
4057 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4058 flags |= eTraversalNeeded;
4059 }
4060
4061 mInputWindowCommands.merge(inputWindowCommands);
4062 return flags;
4063}
4064
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004065status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4066 uint32_t h, PixelFormat format, uint32_t flags,
4067 LayerMetadata metadata, sp<IBinder>* handle,
4068 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004069 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004070 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004071 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004073 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004074
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004075 status_t result = NO_ERROR;
4076
4077 sp<Layer> layer;
4078
Cody Northropbc755282017-03-31 12:00:08 -06004079 String8 uniqueName = getUniqueLayerName(name);
4080
Mathias Agopian3165cc22012-08-08 19:42:09 -07004081 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004082 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004083 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4084 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004087 case ISurfaceComposerClient::eFXSurfaceBufferState:
4088 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4089 break;
chaviw13fdc492017-06-27 12:40:18 -07004090 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004091 // check if buffer size is set for color layer.
4092 if (w > 0 || h > 0) {
4093 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4094 int(w), int(h));
4095 return BAD_VALUE;
4096 }
4097
chaviw13fdc492017-06-27 12:40:18 -07004098 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004099 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004100 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004102 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004103 // check if buffer size is set for container layer.
4104 if (w > 0 || h > 0) {
4105 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4106 int(w), int(h));
4107 return BAD_VALUE;
4108 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004109 result = createContainerLayer(client,
4110 uniqueName, w, h, flags,
4111 handle, &layer);
4112 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004113 default:
4114 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004115 break;
4116 }
4117
Dan Stoza7d89d062015-04-30 13:29:25 -07004118 if (result != NO_ERROR) {
4119 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004121
Chia-I Wuab0c3192017-08-01 11:29:00 -07004122 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4123 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004124 if (metadata.has(METADATA_WINDOW_TYPE)) {
4125 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4126 if (windowType == 441731) {
4127 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4128 layer->setPrimaryDisplayOnly();
4129 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004130 }
4131
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004132 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004133
Robert Carrb89ea9d2018-12-10 13:01:14 -08004134 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4135 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4136 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004137 if (result != NO_ERROR) {
4138 return result;
4139 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004140 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004141
4142 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004143 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144}
4145
Cody Northropbc755282017-03-31 12:00:08 -06004146String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4147{
4148 bool matchFound = true;
4149 uint32_t dupeCounter = 0;
4150
4151 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4152 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4153
Dan Stoza436ccf32018-06-21 12:10:12 -07004154 // Grab the state lock since we're accessing mCurrentState
4155 Mutex::Autolock lock(mStateLock);
4156
Cody Northropbc755282017-03-31 12:00:08 -06004157 // Loop over layers until we're sure there is no matching name
4158 while (matchFound) {
4159 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004160 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004161 if (layer->getName() == uniqueName) {
4162 matchFound = true;
4163 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4164 }
4165 });
4166 }
4167
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004168 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4169 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004170
4171 return uniqueName;
4172}
4173
Marissa Wallfd668622018-05-10 10:21:13 -07004174status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4175 uint32_t w, uint32_t h, uint32_t flags,
4176 PixelFormat& format, sp<IBinder>* handle,
4177 sp<IGraphicBufferProducer>* gbp,
4178 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004180 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 case PIXEL_FORMAT_TRANSPARENT:
4182 case PIXEL_FORMAT_TRANSLUCENT:
4183 format = PIXEL_FORMAT_RGBA_8888;
4184 break;
4185 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004186 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 break;
4188 }
4189
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004190 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004191 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004192 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004193 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004194 *handle = layer->getHandle();
4195 *gbp = layer->getProducer();
4196 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198
Marissa Wallfd668622018-05-10 10:21:13 -07004199 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004200 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201}
4202
Marissa Wall61c58622018-07-18 10:12:20 -07004203status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4204 uint32_t w, uint32_t h, uint32_t flags,
4205 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004206 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004207 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004208 *handle = layer->getHandle();
4209 *outLayer = layer;
4210
4211 return NO_ERROR;
4212}
4213
chaviw13fdc492017-06-27 12:40:18 -07004214status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004215 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004216 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004217{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004218 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004219 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004220 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004221}
4222
Robert Carr6b3f6c52018-08-13 13:05:17 -07004223status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4224 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4225 sp<IBinder>* handle, sp<Layer>* outLayer)
4226{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004227 *outLayer =
4228 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004229 *handle = (*outLayer)->getHandle();
4230 return NO_ERROR;
4231}
4232
4233
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004234void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004235 mLayersPendingRemoval.add(layer);
4236 mLayersRemoved = true;
4237 setTransactionFlags(eTransactionNeeded);
4238}
4239
Robert Carr695d5282018-12-18 15:27:58 -08004240void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004241{
Robert Carr2e102c92018-10-23 12:11:15 -07004242 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004243 // If a layer has a parent, we allow it to out-live it's handle
4244 // with the idea that the parent holds a reference and will eventually
4245 // be cleaned up. However no one cleans up the top-level so we do so
4246 // here.
4247 if (layer->getParent() == nullptr) {
4248 mCurrentState.layersSortedByZ.remove(layer);
4249 }
4250 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004251 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004252}
4253
Mathias Agopianb60314a2012-04-10 22:09:54 -07004254// ---------------------------------------------------------------------------
4255
Andy McFadden13a082e2012-08-24 10:16:42 -07004256void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004257 const auto display = getDefaultDisplayDeviceLocked();
4258 if (!display) return;
4259
4260 const sp<IBinder> token = display->getDisplayToken().promote();
4261 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004262
Jesse Hall01e29052013-02-19 16:13:35 -08004263 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004264 Vector<ComposerState> state;
4265 Vector<DisplayState> displays;
4266 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004267 d.what = DisplayState::eDisplayProjectionChanged |
4268 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004269 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004270 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004271 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004272 d.frame.makeInvalid();
4273 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004274 d.width = 0;
4275 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004276 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004277 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004278
Dominik Laskowskie9774092018-12-11 10:04:24 -08004279 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004280
Dominik Laskowski83b88212018-12-11 13:34:06 -08004281 const nsecs_t vsyncPeriod = getVsyncPeriod();
4282 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004283
Brian Andersond0010582017-03-07 13:20:31 -08004284 // Use phase of 0 since phase is not known.
4285 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004286 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004287 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004288}
4289
4290void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004291 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004292 postMessageAsync(
4293 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004294}
4295
Dominik Laskowskie9774092018-12-11 10:04:24 -08004296void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297 if (display->isVirtual()) {
4298 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004299 return;
4300 }
4301
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 const auto displayId = display->getId();
4303 LOG_ALWAYS_FATAL_IF(!displayId);
4304
Dominik Laskowski34157762018-10-31 13:07:19 -07004305 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004306
4307 int currentMode = display->getPowerMode();
4308 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004309 return;
4310 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004311
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 display->setPowerMode(mode);
4313
Lloyd Pique4dccc412018-01-22 17:21:36 -08004314 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004315 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004316 }
4317
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004318 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004319 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004320 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004321 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004322 if (mUseScheduler) {
4323 mScheduler->onScreenAcquired(mAppConnectionHandle);
4324 } else {
4325 mEventThread->onScreenAcquired();
4326 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004327 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004328 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004329
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004330 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004331 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004332 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004333
4334 struct sched_param param = {0};
4335 param.sched_priority = 1;
4336 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4337 ALOGW("Couldn't set SCHED_FIFO on display on");
4338 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004339 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004340 // Turn off the display
4341 struct sched_param param = {0};
4342 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4343 ALOGW("Couldn't set SCHED_OTHER on display off");
4344 }
4345
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004346 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004347 if (mUseScheduler) {
4348 mScheduler->disableHardwareVsync(true);
4349 } else {
4350 disableHardwareVsync(true); // also cancels any in-progress resync
4351 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004352 if (mUseScheduler) {
4353 mScheduler->onScreenReleased(mAppConnectionHandle);
4354 } else {
4355 mEventThread->onScreenReleased();
4356 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004357 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004358
Dominik Laskowski075d3172018-05-24 15:50:06 -07004359 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004360 mVisibleRegionsDirty = true;
4361 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004362 } else if (mode == HWC_POWER_MODE_DOZE ||
4363 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004364 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004365 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004366 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004367 if (mUseScheduler) {
4368 mScheduler->onScreenAcquired(mAppConnectionHandle);
4369 } else {
4370 mEventThread->onScreenAcquired();
4371 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004372 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004373 }
4374 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4375 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004376 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004377 if (mUseScheduler) {
4378 mScheduler->disableHardwareVsync(true);
4379 } else {
4380 disableHardwareVsync(true); // also cancels any in-progress resync
4381 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004382 if (mUseScheduler) {
4383 mScheduler->onScreenReleased(mAppConnectionHandle);
4384 } else {
4385 mEventThread->onScreenReleased();
4386 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004387 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004388 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004389 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004390 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004391 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004392 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004393
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004394 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004395 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004396 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004397 // Update refresh rate stats.
4398 mRefreshRateStats->setPowerMode(mode);
4399 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004400 }
4401
Dominik Laskowski34157762018-10-31 13:07:19 -07004402 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004403}
4404
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004405void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004406 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 const auto display = getDisplayDevice(displayToken);
4408 if (!display) {
4409 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4410 displayToken.get());
4411 } else if (display->isVirtual()) {
4412 ALOGW("Attempt to set power mode %d for virtual display", mode);
4413 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004414 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004415 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004416 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004417}
4418
4419// ---------------------------------------------------------------------------
4420
Dominik Laskowskic2867142019-01-21 11:33:38 -08004421status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4422 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004424
Mathias Agopianbd115332013-04-18 16:41:04 -07004425 IPCThreadState* ipc = IPCThreadState::self();
4426 const int pid = ipc->getCallingPid();
4427 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004428
Mathias Agopianbd115332013-04-18 16:41:04 -07004429 if ((uid != AID_SHELL) &&
4430 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4432 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004434 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004435 // (this would indicate SF is stuck, but we want to be able to
4436 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004437 status_t err = mStateLock.timedLock(s2ns(1));
4438 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004439 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440 StringAppendF(&result,
4441 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4442 "(no locks held)\n",
4443 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004444 }
4445
Dominik Laskowskic2867142019-01-21 11:33:38 -08004446 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004447
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448 static const std::unordered_map<std::string, Dumper> dumpers = {
4449 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4450 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4451 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4452 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4453 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4454 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4455 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4456 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4457 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4458 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4459 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4460 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4461 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004462 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4464 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004465
Dominik Laskowskic2867142019-01-21 11:33:38 -08004466 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004467
Dominik Laskowskic2867142019-01-21 11:33:38 -08004468 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4469 (it->second)(args, asProto, result);
4470 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004471 if (asProto) {
4472 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4473 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4474 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004475 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004476 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004477 }
4478
Mathias Agopian9795c422009-08-26 16:36:26 -07004479 if (locked) {
4480 mStateLock.unlock();
4481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004483 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 return NO_ERROR;
4485}
4486
Dominik Laskowskic2867142019-01-21 11:33:38 -08004487void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 mCurrentState.traverseInZOrder(
4489 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004490}
4491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004493 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004494
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495 if (args.size() > 1) {
4496 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004497 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004498 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004499 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004500 }
Robert Carr2047fae2016-11-28 14:09:09 -08004501 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004502 } else {
4503 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504 }
4505}
4506
Dominik Laskowskic2867142019-01-21 11:33:38 -08004507void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004508 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004509 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004510 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004511 }
Robert Carr2047fae2016-11-28 14:09:09 -08004512 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004513
Svetoslavd85084b2014-03-20 10:28:31 -07004514 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004515}
4516
Dominik Laskowskic2867142019-01-21 11:33:38 -08004517void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4518 mTimeStats->parseArgs(asProto, args, result);
4519}
4520
Jamie Gennis6547ff42013-07-16 20:12:42 -07004521// This should only be called from the main thread. Otherwise it would need
4522// the lock and should use mCurrentState rather than mDrawingState.
4523void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004524 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004525 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004526 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004527
4528 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4529}
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004532 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004533
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004534 if (isLayerTripleBufferingDisabled())
4535 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4538 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4539 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4540 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4541 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4542 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004543 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004544}
4545
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004546void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004547 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004548 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004549 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004550 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551
4552 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4553
4554 if (mUseScheduler) {
4555 mScheduler->dump(mAppConnectionHandle, result);
4556 } else {
4557 mEventThread->dump(result);
4558 }
4559}
4560
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4562 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004563 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4564 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004565 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004566 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004568 }
David Sodman4a36e932017-11-07 14:29:47 -08004569 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004570 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004571 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4573 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004574}
4575
Dan Stozae77c7662016-05-13 11:37:28 -07004576void SurfaceFlinger::recordBufferingStats(const char* layerName,
4577 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004578 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4579 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004580 for (const auto& segment : history) {
4581 if (!segment.usedThirdBuffer) {
4582 stats.twoBufferTime += segment.totalTime;
4583 }
4584 if (segment.occupancyAverage < 1.0f) {
4585 stats.doubleBufferedTime += segment.totalTime;
4586 } else if (segment.occupancyAverage < 2.0f) {
4587 stats.tripleBufferedTime += segment.totalTime;
4588 }
4589 ++stats.numSegments;
4590 stats.totalTime += segment.totalTime;
4591 }
4592}
4593
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4595 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004596
4597 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4598 const size_t count = currentLayers.size();
4599 for (size_t i=0 ; i<count ; i++) {
4600 currentLayers[i]->dumpFrameEvents(result);
4601 }
4602}
4603
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004605 result.append("Buffering stats:\n");
4606 result.append(" [Layer name] <Active time> <Two buffer> "
4607 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004608 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004609 typedef std::tuple<std::string, float, float, float> BufferTuple;
4610 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004611 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004612 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004613 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004614 if (stats.numSegments == 0) {
4615 continue;
4616 }
4617 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4618 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4619 stats.totalTime;
4620 float doubleBufferRatio = static_cast<float>(
4621 stats.doubleBufferedTime) / stats.totalTime;
4622 float tripleBufferRatio = static_cast<float>(
4623 stats.tripleBufferedTime) / stats.totalTime;
4624 sorted.insert({activeTime, {name, twoBufferRatio,
4625 doubleBufferRatio, tripleBufferRatio}});
4626 }
4627 for (const auto& sortedPair : sorted) {
4628 float activeTime = sortedPair.first;
4629 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4631 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004632 }
4633 result.append("\n");
4634}
4635
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004638 const auto displayId = display->getId();
4639 if (!displayId) {
4640 continue;
4641 }
4642 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004643 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004644 continue;
4645 }
4646
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result,
4648 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4649 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 uint8_t port;
4651 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004652 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004653 result.append("no identification data\n");
4654 continue;
4655 }
4656
4657 if (!isEdid(data)) {
4658 result.append("unknown identification data: ");
4659 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004661 }
4662 result.append("\n");
4663 continue;
4664 }
4665
4666 const auto edid = parseEdid(data);
4667 if (!edid) {
4668 result.append("invalid EDID: ");
4669 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004671 }
4672 result.append("\n");
4673 continue;
4674 }
4675
Yiwei Zhang5434a782018-12-05 18:06:32 -08004676 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004677 result.append(edid->displayName.data(), edid->displayName.length());
4678 result.append("\"\n");
4679 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004680}
4681
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4683 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4684 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4685 StringAppendF(&result, "DisplayColorSetting: %s\n",
4686 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004687
4688 // TODO: print out if wide-color mode is active or not
4689
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004690 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004691 const auto displayId = display->getId();
4692 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004693 continue;
4694 }
4695
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004698 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004700 }
4701
Lloyd Pique32cbe282018-10-19 13:09:22 -07004702 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703 StringAppendF(&result, " Current color mode: %s (%d)\n",
4704 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004705 }
4706 result.append("\n");
4707}
4708
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004710 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004711 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4712 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004713 continue;
4714 }
4715
Dominik Laskowski05275f12018-11-01 15:03:24 -07004716 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4718 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004719 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 compositionInfo.dump(result, nullptr);
4721 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004722 }
4723 }
David Sodman7e4ae112018-02-09 15:02:28 -08004724}
4725
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004726LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004727 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004728 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4729 const State& state = useDrawing ? mDrawingState : mCurrentState;
4730 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004731 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004732 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004733 });
4734
4735 return layersProto;
4736}
4737
Lloyd Pique32cbe282018-10-19 13:09:22 -07004738LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004739 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004740
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004741 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004742 resolution->set_w(displayDevice.getWidth());
4743 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744
Lloyd Pique32cbe282018-10-19 13:09:22 -07004745 auto display = displayDevice.getCompositionDisplay();
4746 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004747
Lloyd Pique32cbe282018-10-19 13:09:22 -07004748 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4749 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4750 layersProto.set_global_transform(displayState.orientation);
4751
4752 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004753 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004754 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004755 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004756 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004758 }
4759 });
4760
4761 return layersProto;
4762}
4763
Dominik Laskowskic2867142019-01-21 11:33:38 -08004764void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4765 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766 Colorizer colorizer(colorize);
4767
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768 // figure out if we're stuck somewhere
4769 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4772
4773 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004774 * Dump library configuration.
4775 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776
4777 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004778 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004780 appendSfConfigString(result);
4781 appendUiConfigString(result);
4782 appendGuiConfigString(result);
4783 result.append("\n");
4784
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004785 result.append("\nDisplay identification data:\n");
4786 dumpDisplayIdentificationData(result);
4787
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004788 result.append("\nWide-Color information:\n");
4789 dumpWideColorInfo(result);
4790
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004792 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004793 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004794 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004795 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004796
Andy McFadden41d67d72014-04-25 16:58:34 -07004797 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004798 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004799 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004800 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004801 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004802
Dan Stozab90cf072015-03-05 11:05:59 -08004803 dumpStaticScreenStats(result);
4804 result.append("\n");
4805
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004807
Dan Stozae77c7662016-05-13 11:37:28 -07004808 dumpBufferingStats(result);
4809
Andy McFadden4803b742012-09-24 19:07:20 -07004810 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004811 * Dump the visible layer list
4812 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004813 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004814 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4815 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4816 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004818
Chia-I Wu2f884132018-09-13 15:17:58 -07004819 {
4820 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4821 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004822 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004823 result.append("\n");
4824 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004825
David Sodman7e4ae112018-02-09 15:02:28 -08004826 result.append("\nFrame-Composition information:\n");
4827 dumpFrameCompositionInfo(result);
4828 result.append("\n");
4829
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004831 * Dump Display state
4832 */
4833
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004835 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004836 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004837 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004839 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004840 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004841
4842 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004843 * Dump SurfaceFlinger global state
4844 */
4845
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004846 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004847 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004848 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004850 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004851
Dominik Laskowski075d3172018-05-24 15:50:06 -07004852 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004853 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4854 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4856 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004857 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004858 StringAppendF(&result,
4859 " transaction-flags : %08x\n"
4860 " gpu_to_cpu_unsupported : %d\n",
4861 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004862
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004863 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004864 displayId && getHwComposer().isConnected(*displayId)) {
4865 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004866 StringAppendF(&result,
4867 " refresh-rate : %f fps\n"
4868 " x-dpi : %f\n"
4869 " y-dpi : %f\n",
4870 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4871 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004872 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004873
Yiwei Zhang5434a782018-12-05 18:06:32 -08004874 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004875
Dan Stozae22aec72016-08-01 13:20:59 -07004876 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004877 * Tracing state
4878 */
4879 mTracing.dump(result);
4880 result.append("\n");
4881
4882 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004883 * HWC layer minidump
4884 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004885 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 const auto displayId = display->getId();
4887 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004888 continue;
4889 }
4890
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004892 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004893 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004894 result.append("\n");
4895 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004896
4897 /*
4898 * Dump HWComposer state
4899 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004900 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004901 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004902 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004905 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004906
4907 /*
4908 * Dump gralloc state
4909 */
4910 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4911 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004912
4913 /*
4914 * Dump VrFlinger state if in use.
4915 */
4916 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4917 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004918 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004919 result.append("\n");
4920 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004921
4922 /**
4923 * Scheduler dump state.
4924 */
4925 if (mUseScheduler) {
4926 result.append("\nScheduler state:\n");
4927 result.append(mScheduler->doDump() + "\n");
4928 result.append(mRefreshRateStats->doDump() + "\n");
4929 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004930}
4931
Dominik Laskowski075d3172018-05-24 15:50:06 -07004932const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004933 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004934 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004935 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004936 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004937 }
4938 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004939
Dominik Laskowski34157762018-10-31 13:07:19 -07004940 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004941 static const Vector<sp<Layer>> empty;
4942 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004943}
4944
Chia-I Wu28f320b2018-05-03 11:02:56 -07004945void SurfaceFlinger::updateColorMatrixLocked() {
4946 mat4 colorMatrix;
4947 if (mGlobalSaturationFactor != 1.0f) {
4948 // Rec.709 luma coefficients
4949 float3 luminance{0.213f, 0.715f, 0.072f};
4950 luminance *= 1.0f - mGlobalSaturationFactor;
4951 mat4 saturationMatrix = mat4(
4952 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4953 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4954 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4955 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4956 );
4957 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4958 } else {
4959 colorMatrix = mClientColorMatrix * mDaltonizer();
4960 }
4961
4962 if (mCurrentState.colorMatrix != colorMatrix) {
4963 mCurrentState.colorMatrix = colorMatrix;
4964 mCurrentState.colorMatrixChanged = true;
4965 setTransactionFlags(eTransactionNeeded);
4966 }
4967}
4968
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004969status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970#pragma clang diagnostic push
4971#pragma clang diagnostic error "-Wswitch-enum"
4972 switch (static_cast<ISurfaceComposerTag>(code)) {
4973 // These methods should at minimum make sure that the client requested
4974 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004975 case BOOT_FINISHED:
4976 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977 case CREATE_DISPLAY:
4978 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004979 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980 case GET_ACTIVE_COLOR_MODE:
4981 case GET_ANIMATION_FRAME_STATS:
4982 case GET_HDR_CAPABILITIES:
4983 case SET_ACTIVE_CONFIG:
4984 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004985 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004986 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004987 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004988 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4989 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004990 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4991 IPCThreadState* ipc = IPCThreadState::self();
4992 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4993 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004994 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004995 }
Robert Carr1db73f62016-12-21 12:58:51 -08004996 return OK;
4997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004999 IPCThreadState* ipc = IPCThreadState::self();
5000 const int pid = ipc->getCallingPid();
5001 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5003 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005004 return PERMISSION_DENIED;
5005 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005006 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 // Used by apps to hook Choreographer to SurfaceFlinger.
5009 case CREATE_DISPLAY_EVENT_CONNECTION:
5010 // The following calls are currently used by clients that do not
5011 // request necessary permissions. However, they do not expose any secret
5012 // information, so it is OK to pass them.
5013 case AUTHENTICATE_SURFACE:
5014 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005015 case GET_PHYSICAL_DISPLAY_IDS:
5016 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005018 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 case GET_DISPLAY_CONFIGS:
5020 case GET_DISPLAY_STATS:
5021 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5022 // Calling setTransactionState is safe, because you need to have been
5023 // granted a reference to Client* and Handle* to do anything with it.
5024 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005025 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005026 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005027 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005028 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005029 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 return OK;
5031 }
5032 case CAPTURE_LAYERS:
5033 case CAPTURE_SCREEN: {
5034 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005035 IPCThreadState* ipc = IPCThreadState::self();
5036 const int pid = ipc->getCallingPid();
5037 const int uid = ipc->getCallingUid();
5038 if ((uid != AID_GRAPHICS) &&
5039 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5040 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5041 return PERMISSION_DENIED;
5042 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005043 return OK;
5044 }
5045 // The following codes are deprecated and should never be allowed to access SF.
5046 case CONNECT_DISPLAY_UNUSED:
5047 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5048 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5049 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052
5053 // These codes are used for the IBinder protocol to either interrogate the recipient
5054 // side of the transaction for its canonical interface descriptor or to dump its state.
5055 // We let them pass by default.
5056 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5057 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5058 code == IBinder::SYSPROPS_TRANSACTION) {
5059 return OK;
5060 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005061 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005063 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5065 return OK;
5066 }
5067 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5068 return PERMISSION_DENIED;
5069#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005070}
5071
Ana Krulec13be8ad2018-08-21 02:43:56 +00005072status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5073 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005074 status_t credentialCheck = CheckTransactCodeCredentials(code);
5075 if (credentialCheck != OK) {
5076 return credentialCheck;
5077 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5080 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005081 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005082 IPCThreadState* ipc = IPCThreadState::self();
5083 const int uid = ipc->getCallingUid();
5084 if (CC_UNLIKELY(uid != AID_SYSTEM
5085 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005086 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005087 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005088 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005089 return PERMISSION_DENIED;
5090 }
5091 int n;
5092 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005093 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005094 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 return NO_ERROR;
5096 case 1002: // SHOW_UPDATES
5097 n = data.readInt32();
5098 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005099 invalidateHwcGeometry();
5100 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005103 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005104 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005105 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005106 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005107 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005108 setTransactionFlags(
5109 eTransactionNeeded|
5110 eDisplayTransactionNeeded|
5111 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005112 return NO_ERROR;
5113 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005114 case 1006:{ // send empty update
5115 signalRefresh();
5116 return NO_ERROR;
5117 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005118 case 1008: // toggle use of hw composer
5119 n = data.readInt32();
5120 mDebugDisableHWC = n ? 1 : 0;
5121 invalidateHwcGeometry();
5122 repaintEverything();
5123 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005124 case 1009: // toggle use of transform hint
5125 n = data.readInt32();
5126 mDebugDisableTransformHint = n ? 1 : 0;
5127 invalidateHwcGeometry();
5128 repaintEverything();
5129 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005131 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 reply->writeInt32(0);
5133 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005134 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005135 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005136 return NO_ERROR;
5137 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005138 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005139 if (!display) {
5140 return NAME_NOT_FOUND;
5141 }
5142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005143 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005144 return NO_ERROR;
5145 }
5146 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005147 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005148 // daltonize
5149 n = data.readInt32();
5150 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005151 case 1:
5152 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5153 break;
5154 case 2:
5155 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5156 break;
5157 case 3:
5158 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5159 break;
5160 default:
5161 mDaltonizer.setType(ColorBlindnessType::None);
5162 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005163 }
5164 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005165 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005166 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005167 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169
5170 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 // apply a color matrix
5176 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005177 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005178 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005179 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005180 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005181 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005182 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005183 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005184 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005186 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005187
5188 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5189 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005191 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5192 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5193 }
5194
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005196 return NO_ERROR;
5197 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005198 // This is an experimental interface
5199 // Needs to be shifted to proper binder interface when we productize
5200 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005201 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005202 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005203 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005204 return NO_ERROR;
5205 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005206 case 1017: {
5207 n = data.readInt32();
5208 mForceFullDamage = static_cast<bool>(n);
5209 return NO_ERROR;
5210 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005211 case 1018: { // Modify Choreographer's phase offset
5212 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005213 if (mUseScheduler) {
5214 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5215 } else {
5216 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5217 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005218 return NO_ERROR;
5219 }
5220 case 1019: { // Modify SurfaceFlinger's phase offset
5221 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005222 if (mUseScheduler) {
5223 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5224 } else {
5225 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5226 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005227 return NO_ERROR;
5228 }
Irvel468051e2016-06-13 16:44:44 -07005229 case 1020: { // Layer updates interceptor
5230 n = data.readInt32();
5231 if (n) {
5232 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005233 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005234 }
5235 else{
5236 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005237 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005238 }
5239 return NO_ERROR;
5240 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005241 case 1021: { // Disable HWC virtual displays
5242 n = data.readInt32();
5243 mUseHwcVirtualDisplays = !n;
5244 return NO_ERROR;
5245 }
Romain Guy0147a172017-06-01 13:53:56 -07005246 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005247 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005248 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005249
Chia-I Wu28f320b2018-05-03 11:02:56 -07005250 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005251 return NO_ERROR;
5252 }
Romain Guy54f154a2017-10-24 21:40:32 +01005253 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005254 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005255 invalidateHwcGeometry();
5256 repaintEverything();
5257 return NO_ERROR;
5258 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005259 // Deprecate, use 1030 to check whether the device is color managed.
5260 case 1024: {
5261 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005262 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005263 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005264 n = data.readInt32();
5265 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005266 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005267 mTracing.enable();
5268 doTracing("tracing.enable");
5269 reply->writeInt32(NO_ERROR);
5270 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005271 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005272 status_t err = mTracing.disable();
5273 reply->writeInt32(err);
5274 }
5275 return NO_ERROR;
5276 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005277 case 1026: { // Get layer tracing status
5278 reply->writeBool(mTracing.isEnabled());
5279 return NO_ERROR;
5280 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005281 // Is a DisplayColorSetting supported?
5282 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283 const auto display = getDefaultDisplayDevice();
5284 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005285 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005286 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005287
5288 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5289 switch (setting) {
5290 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005291 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005292 break;
5293 case DisplayColorSetting::UNMANAGED:
5294 reply->writeBool(true);
5295 break;
5296 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005297 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005298 break;
5299 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005300 reply->writeBool(
5301 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005302 break;
5303 }
5304 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005305 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005306 // Is VrFlinger active?
5307 case 1028: {
5308 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005309 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005310 return NO_ERROR;
5311 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005312 // Is device color managed?
5313 case 1030: {
5314 reply->writeBool(useColorManagement);
5315 return NO_ERROR;
5316 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005317 // Override default composition data space
5318 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5319 // && adb shell stop zygote && adb shell start zygote
5320 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5321 // adb shell stop zygote && adb shell start zygote
5322 case 1031: {
5323 Mutex::Autolock _l(mStateLock);
5324 n = data.readInt32();
5325 if (n) {
5326 n = data.readInt32();
5327 if (n) {
5328 Dataspace dataspace = static_cast<Dataspace>(n);
5329 if (!validateCompositionDataspace(dataspace)) {
5330 return BAD_VALUE;
5331 }
5332 mDefaultCompositionDataspace = dataspace;
5333 }
5334 n = data.readInt32();
5335 if (n) {
5336 Dataspace dataspace = static_cast<Dataspace>(n);
5337 if (!validateCompositionDataspace(dataspace)) {
5338 return BAD_VALUE;
5339 }
5340 mWideColorGamutCompositionDataspace = dataspace;
5341 }
5342 } else {
5343 // restore composition data space.
5344 mDefaultCompositionDataspace = defaultCompositionDataspace;
5345 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5346 }
5347 return NO_ERROR;
5348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005349 }
5350 }
5351 return err;
5352}
5353
Steven Thomas6d8110b2017-08-31 18:24:21 -07005354void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005355 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005356 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005357}
5358
Ana Krulec7d1d6832018-12-27 11:10:09 -08005359void SurfaceFlinger::repaintEverythingForHWC() {
5360 mRepaintEverything = true;
5361 mEventQueue->invalidateForHWC();
5362}
5363
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5365class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005366public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005367 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5368 ~WindowDisconnector() {
5369 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005370 }
5371
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372private:
5373 ANativeWindow* mWindow;
5374 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005375};
5376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005378 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5379 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005380 uint32_t reqWidth, uint32_t reqHeight,
5381 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005382 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005385 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005386
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005387 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5388
Chia-I Wu20261cb2018-08-23 12:55:44 -07005389 sp<DisplayDevice> display;
5390 {
5391 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005392
Chia-I Wu20261cb2018-08-23 12:55:44 -07005393 display = getDisplayDeviceLocked(displayToken);
5394 if (!display) return BAD_VALUE;
5395
Chia-I Wucb023152018-08-28 12:57:23 -07005396 // set the requested width/height to the logical display viewport size
5397 // by default
5398 if (reqWidth == 0 || reqHeight == 0) {
5399 reqWidth = uint32_t(display->getViewport().width());
5400 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005401 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005402 }
5403
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5405 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005406
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005407 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5408 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5410 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005411}
5412
5413status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5415 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005416 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005417 ATRACE_CALL();
5418
5419 class LayerRenderArea : public RenderArea {
5420 public:
Robert Carr578038f2018-03-09 12:25:24 -08005421 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005422 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5423 bool childrenOnly)
5424 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005425 mLayer(layer),
5426 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005427 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005428 mFlinger(flinger),
5429 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005430 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 Rect getBounds() const override {
5432 const Layer::State& layerState(mLayer->getDrawingState());
5433 return mLayer->getBufferSize(layerState);
5434 }
Marissa Wall61c58622018-07-18 10:12:20 -07005435 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005437 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005438 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005439 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005440 }
chaviwa76b2712017-09-20 12:02:26 -07005441 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005442 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005443 Rect getSourceCrop() const override {
5444 if (mCrop.isEmpty()) {
5445 return getBounds();
5446 } else {
5447 return mCrop;
5448 }
5449 }
Robert Carr578038f2018-03-09 12:25:24 -08005450 class ReparentForDrawing {
5451 public:
5452 const sp<Layer>& oldParent;
5453 const sp<Layer>& newParent;
5454
5455 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5456 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005457 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005458 }
Robert Carr15eae092018-03-23 13:43:53 -07005459 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005460 };
5461
5462 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005463 const Rect sourceCrop = getSourceCrop();
5464 // no need to check rotation because there is none
5465 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5466 sourceCrop.height() != getReqHeight();
5467
Robert Carr578038f2018-03-09 12:25:24 -08005468 if (!mChildrenOnly) {
5469 mTransform = mLayer->getTransform().inverse();
5470 drawLayers();
5471 } else {
5472 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005473 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005474 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5475 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005476
5477 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5478 drawLayers();
5479 }
5480 }
chaviwa76b2712017-09-20 12:02:26 -07005481
chaviwa76b2712017-09-20 12:02:26 -07005482 private:
chaviw7206d492017-11-10 16:16:12 -08005483 const sp<Layer> mLayer;
5484 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005485
5486 // In the "childrenOnly" case we reparent the children to a screenshot
5487 // layer which has no properties set and which does not draw.
5488 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005489 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005490 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005491
5492 SurfaceFlinger* mFlinger;
5493 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005494 };
5495
5496 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5497 auto parent = layerHandle->owner.promote();
5498
Robert Carr2e102c92018-10-23 12:11:15 -07005499 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005500 ALOGE("captureLayers called with a removed parent");
5501 return NAME_NOT_FOUND;
5502 }
5503
Robert Carr578038f2018-03-09 12:25:24 -08005504 const int uid = IPCThreadState::self()->getCallingUid();
5505 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005506 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005507 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5508 return PERMISSION_DENIED;
5509 }
5510
chaviw7206d492017-11-10 16:16:12 -08005511 Rect crop(sourceCrop);
5512 if (sourceCrop.width() <= 0) {
5513 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005514 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005515 }
5516
5517 if (sourceCrop.height() <= 0) {
5518 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005519 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005520 }
5521
5522 int32_t reqWidth = crop.width() * frameScale;
5523 int32_t reqHeight = crop.height() * frameScale;
5524
Chia-I Wu20261cb2018-08-23 12:55:44 -07005525 // really small crop or frameScale
5526 if (reqWidth <= 0) {
5527 reqWidth = 1;
5528 }
5529 if (reqHeight <= 0) {
5530 reqHeight = 1;
5531 }
5532
Peiyong Lin0e003c92018-09-17 11:09:51 -07005533 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005534
Robert Carr578038f2018-03-09 12:25:24 -08005535 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005536 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5537 if (!layer->isVisible()) {
5538 return;
Robert Carr578038f2018-03-09 12:25:24 -08005539 } else if (childrenOnly && layer == parent.get()) {
5540 return;
chaviwa76b2712017-09-20 12:02:26 -07005541 }
5542 visitor(layer);
5543 });
5544 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005545 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005546}
5547
5548status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5549 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005550 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005551 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005552 bool useIdentityTransform) {
5553 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005554
Peiyong Lin0e003c92018-09-17 11:09:51 -07005555 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005556 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5557 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005558 *outBuffer =
5559 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5560 static_cast<android_pixel_format>(reqPixelFormat), 1,
5561 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562
5563 // This mutex protects syncFd and captureResult for communication of the return values from the
5564 // main thread back to this Binder thread
5565 std::mutex captureMutex;
5566 std::condition_variable captureCondition;
5567 std::unique_lock<std::mutex> captureLock(captureMutex);
5568 int syncFd = -1;
5569 std::optional<status_t> captureResult;
5570
Robert Carr03480e22018-01-04 16:02:06 -08005571 const int uid = IPCThreadState::self()->getCallingUid();
5572 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5573
Dominik Laskowski8c001672018-05-30 16:52:06 -07005574 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005575 // If there is a refresh pending, bug out early and tell the binder thread to try again
5576 // after the refresh.
5577 if (mRefreshPending) {
5578 ATRACE_NAME("Skipping screenshot for now");
5579 std::unique_lock<std::mutex> captureLock(captureMutex);
5580 captureResult = std::make_optional<status_t>(EAGAIN);
5581 captureCondition.notify_one();
5582 return;
5583 }
5584
5585 status_t result = NO_ERROR;
5586 int fd = -1;
5587 {
5588 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005589 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005590 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5591 useIdentityTransform, forSystem, &fd);
5592 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 }
5594
5595 {
5596 std::unique_lock<std::mutex> captureLock(captureMutex);
5597 syncFd = fd;
5598 captureResult = std::make_optional<status_t>(result);
5599 captureCondition.notify_one();
5600 }
5601 });
5602
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005603 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005604 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005605 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005606 while (*captureResult == EAGAIN) {
5607 captureResult.reset();
5608 result = postMessageAsync(message);
5609 if (result != NO_ERROR) {
5610 return result;
5611 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005612 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613 }
5614 result = *captureResult;
5615 }
5616
5617 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005618 sync_wait(syncFd, -1);
5619 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005621
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005622 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005623}
5624
chaviwa76b2712017-09-20 12:02:26 -07005625void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005626 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005627 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5628 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005630
chaviwa76b2712017-09-20 12:02:26 -07005631 const auto reqWidth = renderArea.getReqWidth();
5632 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005633 const auto sourceCrop = renderArea.getSourceCrop();
5634 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005635
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005636 renderengine::DisplaySettings clientCompositionDisplay;
5637 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005638
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005639 // assume that bounds are never offset, and that they are the same as the
5640 // buffer bounds.
5641 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5642 ui::Transform transform = renderArea.getTransform();
5643 mat4 m;
5644 m[0][0] = transform[0][0];
5645 m[0][1] = transform[0][1];
5646 m[0][3] = transform[0][2];
5647 m[1][0] = transform[1][0];
5648 m[1][1] = transform[1][1];
5649 m[1][3] = transform[1][2];
5650 m[3][0] = transform[2][0];
5651 m[3][1] = transform[2][1];
5652 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005653
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005654 clientCompositionDisplay.globalTransform = m;
5655 mat4 rotMatrix;
5656 // Displacement for repositioning the clipping rectangle after rotating it
5657 // with the rotation hint.
5658 int displacementX = 0;
5659 int displacementY = 0;
5660 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5661 switch (rotation) {
5662 case ui::Transform::ROT_90:
5663 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5664 displacementX = reqWidth;
5665 break;
5666 case ui::Transform::ROT_180:
5667 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5668 displacementX = reqWidth;
5669 displacementY = reqHeight;
5670 break;
5671 case ui::Transform::ROT_270:
5672 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5673 displacementY = reqHeight;
5674 break;
5675 default:
5676 break;
5677 }
5678 // We need to transform the clipping window into the right spot.
5679 // First, rotate the clipping rectangle by the rotation hint to get the
5680 // right orientation
5681 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5682 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5683 const vec4 rotClipTL = rotMatrix * clipTL;
5684 const vec4 rotClipBR = rotMatrix * clipBR;
5685 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5686 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5687 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5688 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5689
5690 // Now reposition the clipping rectangle with the displacement vector
5691 // computed above.
5692 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5693
5694 clientCompositionDisplay.clip =
5695 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5696 newClipRight + displacementX, newClipBottom + displacementY);
5697
5698 // We need to perform the same transformation in layer space, so propagate
5699 // it to the global transform.
5700 mat4 clipTransform = displacementMat * rotMatrix;
5701 clientCompositionDisplay.globalTransform *= clipTransform;
5702 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5703 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005704
chaviw50da5042018-04-09 13:49:37 -07005705 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005706
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005707 renderengine::LayerSettings fillLayer;
5708 fillLayer.source.buffer.buffer = nullptr;
5709 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5710 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5711 fillLayer.alpha = half(alpha);
5712 clientCompositionLayers.push_back(fillLayer);
5713
5714 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005715 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005716 renderengine::LayerSettings layerSettings;
5717 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5718 layerSettings);
5719 if (prepared) {
5720 clientCompositionLayers.push_back(layerSettings);
5721 }
chaviwa76b2712017-09-20 12:02:26 -07005722 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005723
5724 clientCompositionDisplay.clearRegion = clearRegion;
5725 base::unique_fd drawFence;
5726 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5727 &drawFence);
5728
5729 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005730}
5731
chaviwa76b2712017-09-20 12:02:26 -07005732status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5733 TraverseLayersFunction traverseLayers,
5734 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005735 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005736 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005737 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005738 ATRACE_CALL();
5739
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005740 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005741
5742 traverseLayers([&](Layer* layer) {
5743 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5744 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005745
Robert Carr03480e22018-01-04 16:02:06 -08005746 // We allow the system server to take screenshots of secure layers for
5747 // use in situations like the Screen-rotation animation and place
5748 // the impetus on WindowManager to not persist them.
5749 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005750 ALOGW("FB is protected: PERMISSION_DENIED");
5751 return PERMISSION_DENIED;
5752 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005754 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005755}
5756
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005757// ---------------------------------------------------------------------------
5758
Dan Stoza412903f2017-04-27 13:42:17 -07005759void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5760 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005761}
5762
Dan Stoza412903f2017-04-27 13:42:17 -07005763void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5764 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005765}
5766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005767void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005768 const LayerVector::Visitor& visitor) {
5769 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005770 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005771 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005772 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005773 continue;
5774 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005775 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005776 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005777 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005778 return;
5779 }
chaviwa76b2712017-09-20 12:02:26 -07005780 if (!layer->isVisible()) {
5781 return;
5782 }
5783 visitor(layer);
5784 });
5785 }
5786}
5787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005788}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005789
Lloyd Pique074e8122018-07-26 12:57:23 -07005790
Mathias Agopian3f844832013-08-07 21:24:32 -07005791#if defined(__gl_h_)
5792#error "don't include gl/gl.h in this file"
5793#endif
5794
5795#if defined(__gl2_h_)
5796#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005797#endif