blob: ae2d4aa2119177c226bdee8d0f38d85215766356 [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));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700783 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700787 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800831 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
832
833 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 if (!displayId) {
835 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700836 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 // TODO: Not sure if display density should handled by SF any longer
839 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700842 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800843 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700844 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845 }
846 return density;
847 }
848 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700849 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700851 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 return getDensityFromProperty("ro.sf.lcd_density"); }
853 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700856
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 DisplayInfo info = DisplayInfo();
859
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 float xdpi = hwConfig->getDpiX();
861 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700862
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863 info.w = hwConfig->getWidth();
864 info.h = hwConfig->getHeight();
865 // Default display viewport to display width and height
866 info.viewportW = info.w;
867 info.viewportH = info.h;
868
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800869 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 // The density of the device is provided by a build property
871 float density = Density::getBuildDensity() / 160.0f;
872 if (density == 0) {
873 // the build doesn't provide a density -- this is wrong!
874 // use xdpi instead
875 ALOGE("ro.sf.lcd_density must be defined as a build property");
876 density = xdpi / 160.0f;
877 }
878 if (Density::getEmuDensity()) {
879 // if "qemu.sf.lcd_density" is specified, it overrides everything
880 xdpi = ydpi = density = Density::getEmuDensity();
881 density /= 160.0f;
882 }
883 info.density = density;
884
885 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700886 const auto display = getDefaultDisplayDeviceLocked();
887 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700888
889 // This is for screenrecord
890 const Rect viewport = display->getViewport();
891 if (viewport.isValid()) {
892 info.viewportW = uint32_t(viewport.getWidth());
893 info.viewportH = uint32_t(viewport.getHeight());
894 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 } else {
896 // TODO: where should this value come from?
897 static const int TV_DENSITY = 213;
898 info.density = TV_DENSITY / 160.0f;
899 info.orientation = 0;
900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 info.xdpi = xdpi;
903 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800905 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906
Andy McFadden91b2ca82014-06-13 14:04:23 -0700907 // This is how far in advance a buffer must be queued for
908 // presentation at a given time. If you want a buffer to appear
909 // on the screen at time N, you must submit the buffer before
910 // (N - presentationDeadline).
911 //
912 // Normally it's one full refresh period (to give SF a chance to
913 // latch the buffer), but this can be reduced by configuring a
914 // DispSync offset. Any additional delays introduced by the hardware
915 // composer or panel must be accounted for here.
916 //
917 // We add an additional 1ms to allow for processing time and
918 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800919 info.presentationDeadline =
920 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700921
922 // All non-virtual displays are currently considered secure.
923 info.secure = true;
924
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800925 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700926 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800927 std::swap(info.w, info.h);
928 }
929
Michael Wright28f24d02016-07-12 13:30:53 -0700930 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700931 }
932
Dan Stoza7f7da322014-05-02 15:26:25 -0700933 return NO_ERROR;
934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
937 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return BAD_VALUE;
939 }
940
Ana Krulece588e312018-09-18 12:32:24 -0700941 if (mUseScheduler) {
942 mScheduler->getDisplayStatInfo(stats);
943 } else {
944 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
945 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
946 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700947 return NO_ERROR;
948}
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
951 const auto display = getDisplayDevice(displayToken);
952 if (!display) {
953 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800954 return BAD_VALUE;
955 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700958}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700959
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
961 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800962 postMessageSync(new LambdaMessage(
963 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800964 return NO_ERROR;
965}
966
967void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
968 Vector<DisplayInfo> configs;
969 getDisplayConfigs(displayToken, &configs);
970 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
971 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
972 return;
973 }
974
975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
978 displayToken.get());
979 return;
980 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700981 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800982 ALOGW("Attempt to set active config %d for virtual display", mode);
983 return;
984 }
985 int currentDisplayPowerMode = display->getPowerMode();
986 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
987 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 return;
989 }
990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700992 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800993 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700994 return;
995 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800996 if (mUseScheduler) {
997 mRefreshRateStats->setConfigMode(mode);
998 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 const auto displayId = display->getId();
1001 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001004 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Ana Krulec7d1d6832018-12-27 11:10:09 -08001006 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001007 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001008}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1011 Vector<ColorMode>* outColorModes) {
1012 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001013 return BAD_VALUE;
1014 }
1015
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001017 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001018 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1019
1020 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1021 if (!displayId) {
1022 return NAME_NOT_FOUND;
1023 }
1024
Dominik Laskowski075d3172018-05-24 15:50:06 -07001025 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001026 }
Michael Wright28f24d02016-07-12 13:30:53 -07001027 outColorModes->clear();
1028 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1029
1030 return NO_ERROR;
1031}
1032
Daniel Solomon42d04562019-01-20 21:03:19 -08001033status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1034 ui::DisplayPrimaries &primaries) {
1035 if (!displayToken) {
1036 return BAD_VALUE;
1037 }
1038
1039 // Currently we only support this API for a single internal display.
1040 if (getInternalDisplayToken() != displayToken) {
1041 return BAD_VALUE;
1042 }
1043
1044 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1045 return NO_ERROR;
1046}
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1049 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001050 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001051 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001053}
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001056 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 Vector<ColorMode> modes;
1058 getDisplayColorModes(displayToken, &modes);
1059 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1060 if (mode < ColorMode::NATIVE || !exists) {
1061 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1062 decodeColorMode(mode).c_str(), mode, displayToken.get());
1063 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001064 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065 const auto display = getDisplayDevice(displayToken);
1066 if (!display) {
1067 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1068 decodeColorMode(mode).c_str(), mode, displayToken.get());
1069 } else if (display->isVirtual()) {
1070 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1071 decodeColorMode(mode).c_str(), mode);
1072 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001073 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1074 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075 }
1076 }));
1077
Michael Wright28f24d02016-07-12 13:30:53 -07001078 return NO_ERROR;
1079}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080
Svetoslavd85084b2014-03-20 10:28:31 -07001081status_t SurfaceFlinger::clearAnimationFrameStats() {
1082 Mutex::Autolock _l(mStateLock);
1083 mAnimFrameTracker.clearStats();
1084 return NO_ERROR;
1085}
1086
1087status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1088 Mutex::Autolock _l(mStateLock);
1089 mAnimFrameTracker.getStats(outStats);
1090 return NO_ERROR;
1091}
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1094 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001095 Mutex::Autolock _l(mStateLock);
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 const auto display = getDisplayDeviceLocked(displayToken);
1098 if (!display) {
1099 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001100 return BAD_VALUE;
1101 }
1102
Peiyong Linfb069302018-04-25 14:34:31 -07001103 // At this point the DisplayDeivce should already be set up,
1104 // meaning the luminance information is already queried from
1105 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001107 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1108 capabilities.getDesiredMaxLuminance(),
1109 capabilities.getDesiredMaxAverageLuminance(),
1110 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001111
1112 return NO_ERROR;
1113}
1114
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001115status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1116 ui::PixelFormat* outFormat,
1117 ui::Dataspace* outDataspace,
1118 uint8_t* outComponentMask) const {
1119 if (!outFormat || !outDataspace || !outComponentMask) {
1120 return BAD_VALUE;
1121 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001122 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001123 if (!display || !display->getId()) {
1124 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1125 return BAD_VALUE;
1126 }
1127 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1128 outDataspace, outComponentMask);
1129}
1130
Kevin DuBois74e53772018-11-19 10:52:38 -08001131status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1132 bool enable, uint8_t componentMask,
1133 uint64_t maxFrames) const {
1134 const auto display = getDisplayDevice(displayToken);
1135 if (!display || !display->getId()) {
1136 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1137 return BAD_VALUE;
1138 }
1139
1140 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1141 componentMask, maxFrames);
1142}
1143
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001144status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1145 uint64_t maxFrames, uint64_t timestamp,
1146 DisplayedFrameStats* outStats) const {
1147 const auto display = getDisplayDevice(displayToken);
1148 if (!display || !display->getId()) {
1149 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1150 return BAD_VALUE;
1151 }
1152
1153 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1154 outStats);
1155}
1156
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001157status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1158 if (!outSupported) {
1159 return BAD_VALUE;
1160 }
1161 *outSupported = getRenderEngine().supportsProtectedContent();
1162 return NO_ERROR;
1163}
1164
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001165status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1166 bool* outIsWideColorDisplay) const {
1167 if (!displayToken || !outIsWideColorDisplay) {
1168 return BAD_VALUE;
1169 }
1170 Mutex::Autolock _l(mStateLock);
1171 const auto display = getDisplayDeviceLocked(displayToken);
1172 if (!display) {
1173 return BAD_VALUE;
1174 }
1175 *outIsWideColorDisplay = display->hasWideColorGamut();
1176 return NO_ERROR;
1177}
1178
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001180 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 if (mInjectVSyncs == enable) {
1184 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186
Dominik Laskowski83b88212018-12-11 13:34:06 -08001187 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001188
Ana Krulec98b5b242018-08-10 15:03:23 -07001189 // TODO(akrulec): Part of the Injector should be refactored, so that it
1190 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 if (enable) {
1192 ALOGV("VSync Injections enabled");
1193 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001194 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001195 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001196 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001197 impl::EventThread::InterceptVSyncsCallback(),
1198 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001200 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001201 } else {
1202 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001203 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001204 }
1205
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001206 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001207 }));
1208
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209 return NO_ERROR;
1210}
1211
1212status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001213 Mutex::Autolock _l(mStateLock);
1214
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215 if (!mInjectVSyncs) {
1216 ALOGE("VSync Injections not enabled");
1217 return BAD_VALUE;
1218 }
1219 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1220 ALOGV("Injecting VSync inside SurfaceFlinger");
1221 mVSyncInjector->onInjectSyncEvent(when);
1222 }
1223 return NO_ERROR;
1224}
1225
Lloyd Pique755e3192018-01-31 16:46:15 -08001226status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1227 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001228 // Try to acquire a lock for 1s, fail gracefully
1229 const status_t err = mStateLock.timedLock(s2ns(1));
1230 const bool locked = (err == NO_ERROR);
1231 if (!locked) {
1232 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1233 return TIMED_OUT;
1234 }
1235
1236 outLayers->clear();
1237 mCurrentState.traverseInZOrder([&](Layer* layer) {
1238 outLayers->push_back(layer->getLayerDebugInfo());
1239 });
1240
1241 mStateLock.unlock();
1242 return NO_ERROR;
1243}
1244
Peiyong Linc6780972018-10-28 15:24:08 -07001245status_t SurfaceFlinger::getCompositionPreference(
1246 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1247 Dataspace* outWideColorGamutDataspace,
1248 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001249 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001250 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001251 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001252 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001253 return NO_ERROR;
1254}
1255
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001256// ----------------------------------------------------------------------------
1257
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1259 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001260 auto resyncCallback = makeResyncCallback([this] {
1261 Mutex::Autolock lock(mStateLock);
1262 return getVsyncPeriod();
1263 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001264
Ana Krulec98b5b242018-08-10 15:03:23 -07001265 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001266 auto resetIdleTimerCallback = [this] {
1267 Mutex::Autolock lock(mStateLock);
1268 setRefreshRateTo(RefreshRateType::PERFORMANCE);
1269 };
1270
1271 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1272 : mAppConnectionHandle;
1273
1274 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1275 std::move(resetIdleTimerCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001276 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001277 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001278 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001279 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001280 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001281 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001282 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001283}
1284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001285// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001286
1287void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001288 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289}
1290
1291void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001292 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001293}
1294
1295void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001296 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001297}
1298
1299void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001300 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001301 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001302}
1303
1304status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001305 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001306 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001307}
1308
1309status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001310 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001311 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001312 if (res == NO_ERROR) {
1313 msg->wait();
1314 }
1315 return res;
1316}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001317
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001318void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001319 do {
1320 waitForEvent();
1321 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001322}
1323
Dominik Laskowski83b88212018-12-11 13:34:06 -08001324nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001325 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001326 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1327 return 0;
1328 }
1329
1330 const auto config = getHwComposer().getActiveConfig(*displayId);
1331 return config ? config->getVsyncPeriod() : 0;
1332}
1333
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334void SurfaceFlinger::enableHardwareVsync() {
1335 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001336 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001337 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001340 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341}
1342
Dominik Laskowski83b88212018-12-11 13:34:06 -08001343void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 Mutex::Autolock _l(mHWVsyncLock);
1345
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346 if (makeAvailable) {
1347 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001348 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1349 if (mUseScheduler) {
1350 mScheduler->makeHWSyncAvailable(true);
1351 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001352 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001353 // Hardware vsync is not currently available, so abort the resync
1354 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001355 return;
1356 }
1357
Dominik Laskowski83b88212018-12-11 13:34:06 -08001358 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001359 return;
1360 }
1361
Ana Krulece588e312018-09-18 12:32:24 -07001362 if (mUseScheduler) {
1363 mScheduler->setVsyncPeriod(period);
1364 } else {
1365 mPrimaryDispSync->reset();
1366 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001367
Ana Krulece588e312018-09-18 12:32:24 -07001368 if (!mPrimaryHWVsyncEnabled) {
1369 mPrimaryDispSync->beginResync();
1370 mEventControlThread->setVsyncEnabled(true);
1371 mPrimaryHWVsyncEnabled = true;
1372 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 }
1374}
1375
Jesse Hall948fe0c2013-10-14 12:56:09 -07001376void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377 Mutex::Autolock _l(mHWVsyncLock);
1378 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001379 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001380 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001381 mPrimaryHWVsyncEnabled = false;
1382 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001383 if (makeUnavailable) {
1384 mHWVsyncAvailable = false;
1385 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386}
1387
Dominik Laskowski83b88212018-12-11 13:34:06 -08001388void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001389 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001390
Dan Stoza57164302017-05-08 14:03:54 -07001391 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001392 const nsecs_t last = lastResyncTime.exchange(now);
1393
1394 if (now - last > kIgnoreDelay) {
1395 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001396 }
1397}
1398
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001399void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1400 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001401 ATRACE_NAME("SF onVsync");
1402
Steven Thomas3cfac282017-02-06 12:29:30 -08001403 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001405 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 return;
1407 }
1408
Dominik Laskowski075d3172018-05-24 15:50:06 -07001409 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001410 return;
1411 }
1412
Dominik Laskowski075d3172018-05-24 15:50:06 -07001413 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001414 // For now, we don't do anything with external display vsyncs.
1415 return;
1416 }
1417
Ana Krulece588e312018-09-18 12:32:24 -07001418 if (mUseScheduler) {
1419 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001420 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001421 bool needsHwVsync = false;
1422 { // Scope for the lock
1423 Mutex::Autolock _l(mHWVsyncLock);
1424 if (mPrimaryHWVsyncEnabled) {
1425 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1426 }
1427 }
1428
1429 if (needsHwVsync) {
1430 enableHardwareVsync();
1431 } else {
1432 disableHardwareVsync(false);
1433 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001434 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001435}
1436
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001437void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001438 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1439 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001440}
1441
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001442void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1443 mPhaseOffsets->setRefreshRateType(refreshRate);
1444
1445 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1446 mVsyncModulator.setPhaseOffsets(early, gl, late);
1447
1448 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001449 return;
1450 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001451
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1453 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1454 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1455 // refresh cycle.
1456
1457 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001458 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001459 if (currentVsyncPeriod == 0) {
1460 return;
1461 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001462
Ana Krulec7d1d6832018-12-27 11:10:09 -08001463 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1464 // floating numbers.
1465 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001466 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1467 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001468 if (std::abs(currentFps - newFps) <= 1) {
1469 return;
1470 }
1471
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001472 const auto displayId = getInternalDisplayIdLocked();
1473 LOG_ALWAYS_FATAL_IF(!displayId);
1474
1475 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001476 for (int i = 0; i < configs.size(); i++) {
1477 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1478 if (vsyncPeriod == 0) {
1479 continue;
1480 }
1481 const float fps = 1e9 / vsyncPeriod;
1482 // TODO(b/113612090): There should be a better way at determining which config
1483 // has the right refresh rate.
1484 if (std::abs(fps - newFps) <= 1) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001485 setActiveConfigInternal(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 ATRACE_INT("FPS", newFps);
1487 }
1488 }
1489}
1490
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001491void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001492 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001494 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001495
Lloyd Piqueba04e622017-12-14 17:11:26 -08001496 // Ignore events that do not have the right sequenceId.
1497 if (sequenceId != getBE().mComposerSequenceId) {
1498 return;
1499 }
1500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Only lock if we're not on the main thread. This function is normally
1502 // called on a hwbinder thread, but for the primary display it's called on
1503 // the main thread with the state lock already held, so don't attempt to
1504 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001505 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001506
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001507 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001508
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001509 if (std::this_thread::get_id() == mMainThreadId) {
1510 // Process all pending hot plug events immediately if we are on the main thread.
1511 processDisplayHotplugEventsLocked();
1512 }
1513
Lloyd Piqueba04e622017-12-14 17:11:26 -08001514 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001515}
1516
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001517void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001518 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001519 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001521 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001523}
1524
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001525void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001526 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001527 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001528 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001529 getHwComposer().setVsyncEnabled(*displayId,
1530 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1531 }
Mathias Agopian86303202012-07-24 22:46:10 -07001532}
1533
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001535void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001536 if (mUseScheduler) {
1537 mScheduler->disableHardwareVsync(true);
1538 } else {
1539 disableHardwareVsync(true);
1540 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001541 // Clear the drawing state so that the logic inside of
1542 // handleTransactionLocked will fire. It will determine the delta between
1543 // mCurrentState and mDrawingState and re-apply all changes when we make the
1544 // transition.
1545 mDrawingState.displays.clear();
1546 mDisplays.clear();
1547}
1548
Steven Thomas050b2c82017-03-06 11:45:16 -08001549void SurfaceFlinger::updateVrFlinger() {
1550 if (!mVrFlinger)
1551 return;
1552 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001554 return;
1555 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 ALOGE("Vr flinger is only supported for remote hardware composer"
1559 " service connections. Ignoring request to transition to vr"
1560 " flinger.");
1561 mVrFlingerRequestsDisplay = false;
1562 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001563 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001568 LOG_ALWAYS_FATAL_IF(!display);
1569 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1571 // called below. Clear the reference now so we don't accidentally use it
1572 // later.
1573 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001576 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001580 // Delete the current instance before creating the new one
1581 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1582 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1583 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1584 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001587 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001588
1589 if (vrFlingerRequestsDisplay) {
1590 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001591 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592
1593 mVisibleRegionsDirty = true;
1594 invalidateHwcGeometry();
1595
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001596 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001597 display = getDefaultDisplayDeviceLocked();
1598 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001599 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001600
Steven Thomasb02664d2017-07-26 18:48:28 -07001601 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001602 const nsecs_t vsyncPeriod = getVsyncPeriod();
1603 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001604
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001605 // The present fences returned from vr_hwc are not an accurate
1606 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001607 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001608 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1609 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001610 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001611 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001612 !hasSyncFramework);
1613 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Use phase of 0 since phase is not known.
1616 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001617 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001618 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001619
Dominik Laskowski83b88212018-12-11 13:34:06 -08001620 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001621
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001622 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001623 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001624}
1625
Mathias Agopian4fec8732012-06-29 14:12:52 -07001626void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001627 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001628 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001630 if (mUseScheduler) {
1631 // This call is made each time SF wakes up and creates a new frame.
1632 mScheduler->incrementFrameCounter();
1633 }
Dan Stoza50182882016-07-08 12:02:20 -07001634 bool frameMissed = !mHadClientComposition &&
1635 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 (mPreviousPresentFence->getSignalTime() ==
1637 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001638 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001639 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001640 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001641 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001642 if (mPropagateBackpressure) {
1643 signalLayerUpdate();
1644 break;
1645 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001646 }
Dan Stoza50182882016-07-08 12:02:20 -07001647
Steven Thomas050b2c82017-03-06 11:45:16 -08001648 // Now that we're going to make it to the handleMessageTransaction()
1649 // call below it's safe to call updateVrFlinger(), which will
1650 // potentially trigger a display handoff.
1651 updateVrFlinger();
1652
Dan Stoza6b9454d2014-11-07 16:00:59 -08001653 bool refreshNeeded = handleMessageTransaction();
1654 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001655
1656 updateCursorAsync();
1657 updateInputFlinger();
1658
Dan Stoza58784442014-12-02 16:58:17 -08001659 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001660 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001661 // Signal a refresh if a transaction modified the window state,
1662 // a new buffer was latched, or if HWC has requested a full
1663 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001664 signalRefresh();
1665 }
1666 break;
1667 }
1668 case MessageQueue::REFRESH: {
1669 handleMessageRefresh();
1670 break;
1671 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001672 }
1673}
1674
Dan Stoza6b9454d2014-11-07 16:00:59 -08001675bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001676 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001677
1678 // Apply any ready transactions in the queues if there are still transactions that have not been
1679 // applied, wake up during the next vsync period and check again
1680 bool transactionNeeded = false;
1681 if (!flushTransactionQueues()) {
1682 transactionNeeded = true;
1683 }
1684
Mathias Agopian4fec8732012-06-29 14:12:52 -07001685 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001686 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001688
1689 if (transactionNeeded) {
1690 setTransactionFlags(eTransactionNeeded);
1691 }
1692
1693 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001694}
1695
Mathias Agopian4fec8732012-06-29 14:12:52 -07001696void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001699 mRefreshPending = false;
1700
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001701 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001702 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001703 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001704 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705 for (const auto& [token, display] : mDisplays) {
1706 beginFrame(display);
1707 prepareFrame(display);
1708 doDebugFlashRegions(display, repaintEverything);
1709 doComposition(display, repaintEverything);
1710 }
1711
Adrian Roos1e1a1282017-11-01 19:05:31 +01001712 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001713 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001714
1715 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001716 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001717
Dan Stozabfbffeb2016-07-21 14:49:33 -07001718 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001719 for (const auto& [token, displayDevice] : mDisplays) {
1720 auto display = displayDevice->getCompositionDisplay();
1721 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001723 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001724 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001725
Alec Mouri86770e52018-09-24 22:40:58 +00001726 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001727 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001728 if (mHadClientComposition) {
1729 base::unique_fd flushFence(getRenderEngine().flush());
1730 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1731 getBE().flushFence = new Fence(std::move(flushFence));
1732 } else {
1733 // Cleanup for hygiene.
1734 getBE().flushFence = Fence::NO_FENCE;
1735 }
1736 }
1737
Jorim Jaggi90535212018-05-23 23:44:06 +02001738 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001739
David Sodman7e4ae112018-02-09 15:02:28 -08001740 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001741 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001742 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001743 compositionInfo.hwc.hwcLayer = nullptr;
1744 }
David Sodmanba340492018-08-05 21:51:33 -07001745 }
David Sodman7e4ae112018-02-09 15:02:28 -08001746
1747 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001749
David Sodmanfa9b2af2017-12-24 13:28:59 -08001750
1751bool SurfaceFlinger::handleMessageInvalidate() {
1752 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001753 bool refreshNeeded = handlePageFlip();
1754
Vishnu Nair4351ad52019-02-11 14:13:02 -08001755 if (mVisibleRegionsDirty) {
1756 computeLayerBounds();
1757 }
1758
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001759 for (auto& layer : mLayersPendingRefresh) {
1760 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001761 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001762 invalidateLayerStack(layer, visibleReg);
1763 }
1764 mLayersPendingRefresh.clear();
1765 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001766}
1767
David Sodman79bba0e2018-08-05 18:07:49 -07001768void SurfaceFlinger::calculateWorkingSet() {
1769 ATRACE_CALL();
1770 ALOGV(__FUNCTION__);
1771
David Sodman79bba0e2018-08-05 18:07:49 -07001772 // build the h/w work list
1773 if (CC_UNLIKELY(mGeometryInvalid)) {
1774 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001775 for (const auto& [token, displayDevice] : mDisplays) {
1776 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001777 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 if (!displayId) {
1779 continue;
1780 }
David Sodman79bba0e2018-08-05 18:07:49 -07001781
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001783 for (size_t i = 0; i < currentLayers.size(); i++) {
1784 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001785
Dominik Laskowski075d3172018-05-24 15:50:06 -07001786 if (!layer->hasHwcLayer(*displayId)) {
1787 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1788 layer->forceClientComposition(*displayId);
1789 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001790 }
1791 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792
Lloyd Pique32cbe282018-10-19 13:09:22 -07001793 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001794 if (mDebugDisableHWC || mDebugRegion) {
1795 layer->forceClientComposition(*displayId);
1796 }
David Sodman79bba0e2018-08-05 18:07:49 -07001797 }
1798 }
1799 }
1800
1801 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001802 for (const auto& [token, displayDevice] : mDisplays) {
1803 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001804 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001806 continue;
1807 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001808 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001809
1810 if (mDrawingState.colorMatrixChanged) {
1811 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001812 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001814 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1817 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001818 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001819 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1821 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001822 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001823 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001824 }
1825
Peiyong Lind3788632018-09-18 16:01:31 -07001826 // TODO(b/111562338) remove when composer 2.3 is shipped.
1827 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001828 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001829 }
1830
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001831 if (layer->getRoundedCornerState().radius > 0.0f) {
1832 layer->forceClientComposition(*displayId);
1833 }
1834
Dominik Laskowski075d3172018-05-24 15:50:06 -07001835 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001836 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001837 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001838 continue;
1839 }
1840
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 const auto& displayState = display->getState();
1842 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1843 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001844 }
1845
Peiyong Lin13effd12018-07-24 17:01:47 -07001846 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001847 ColorMode colorMode;
1848 Dataspace dataSpace;
1849 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001851 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001852 }
1853 }
1854
1855 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001856
1857 for (const auto& [token, display] : mDisplays) {
1858 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001859 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001860 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001861
1862 if (displayId) {
1863 if (!layer->setHwcLayer(*displayId)) {
1864 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1865 }
1866 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001867 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001868
Dominik Laskowski05275f12018-11-01 15:03:24 -07001869 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001870 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1871 }
1872 }
David Sodman79bba0e2018-08-05 18:07:49 -07001873}
1874
Lloyd Pique32cbe282018-10-19 13:09:22 -07001875void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1876 bool repaintEverything) {
1877 auto display = displayDevice->getCompositionDisplay();
1878 const auto& displayState = display->getState();
1879
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880 // is debugging enabled
1881 if (CC_LIKELY(!mDebugRegion))
1882 return;
1883
Lloyd Pique32cbe282018-10-19 13:09:22 -07001884 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001885 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001886 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001887 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001888 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001889 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001890 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001892 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893 }
1894 }
1895
Lloyd Pique32cbe282018-10-19 13:09:22 -07001896 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897
1898 if (mDebugRegion > 1) {
1899 usleep(mDebugRegion * 1000);
1900 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001901
Lloyd Pique32cbe282018-10-19 13:09:22 -07001902 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903}
1904
Adrian Roos1e1a1282017-11-01 19:05:31 +01001905void SurfaceFlinger::doTracing(const char* where) {
1906 ATRACE_CALL();
1907 ATRACE_NAME(where);
1908 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001909 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001910 }
1911}
1912
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001913void SurfaceFlinger::logLayerStats() {
1914 ATRACE_CALL();
1915 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001916 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001917 if (display->isPrimary()) {
1918 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001919 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001920 }
1921 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001922
1923 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001924 }
1925}
1926
David Sodman2b406362017-12-15 13:33:47 -08001927void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001928{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 ATRACE_CALL();
1930 ALOGV("preComposition");
1931
David Sodman2b406362017-12-15 13:33:47 -08001932 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001935 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001936 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 needExtraInvalidate = true;
1938 }
Robert Carr2047fae2016-11-28 14:09:09 -08001939 });
1940
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941 if (needExtraInvalidate) {
1942 signalLayerUpdate();
1943 }
1944}
1945
Ana Krulece588e312018-09-18 12:32:24 -07001946void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1947 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 // Update queue of past composite+present times and determine the
1949 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001950 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001952 while (!getBE().mCompositePresentTimes.empty()) {
1953 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Cached values should have been updated before calling this method,
1955 // which helps avoid duplicate syscalls.
1956 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1957 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1958 break;
1959 }
1960 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001961 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 }
1963
1964 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001965 while (getBE().mCompositePresentTimes.size() > 16) {
1966 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 }
1968
Ana Krulece588e312018-09-18 12:32:24 -07001969 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001970}
1971
Ana Krulece588e312018-09-18 12:32:24 -07001972void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1973 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974 // Integer division and modulo round toward 0 not -inf, so we need to
1975 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001976 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1977 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1978 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979
Ana Krulec757f63a2019-01-25 10:46:18 -08001980 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001981 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001982 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001983 }
1984
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // Snap the latency to a value that removes scheduling jitter from the
1986 // composition and present times, which often have >1ms of jitter.
1987 // Reducing jitter is important if an app attempts to extrapolate
1988 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001989 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001991 nsecs_t bias = stats.vsyncPeriod / 2;
1992 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1993 nsecs_t snappedCompositeToPresentLatency =
1994 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995
David Sodman99974d22017-11-28 12:04:33 -08001996 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001997 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1998 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001999 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002000}
2001
Ady Abraham8164d482019-01-11 14:47:59 -08002002// debug patch for b/119477596 - add stack guards to catch stack
2003// corruptions and disable clang optimizations.
2004// The code below is temporary and planned to be removed once stack
2005// corruptions are found.
2006#pragma clang optimize off
2007class StackGuard {
2008public:
2009 StackGuard(const char* name, const char* func, int line) {
2010 guarders.reserve(MIN_CAPACITY);
2011 guarders.push_back({this, name, func, line});
2012 validate();
2013 }
2014 ~StackGuard() {
2015 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2016 if (i->guard == this) {
2017 guarders.erase(i);
2018 break;
2019 }
2020 }
2021 }
2022
2023 static void validate() {
2024 for (const auto& guard : guarders) {
2025 if (guard.guard->cookie != COOKIE_VALUE) {
2026 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2027 CallStack stack(LOG_TAG);
2028 abort();
2029 }
2030 }
2031 }
2032
2033private:
2034 uint64_t cookie = COOKIE_VALUE;
2035 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2036 static constexpr size_t MIN_CAPACITY = 16;
2037
2038 struct GuarderElement {
2039 StackGuard* guard;
2040 const char* name;
2041 const char* func;
2042 int line;
2043 };
2044
2045 static std::vector<GuarderElement> guarders;
2046};
2047std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2048
2049#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2050
2051#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002052void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053{
Ady Abraham8164d482019-01-11 14:47:59 -08002054 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 ATRACE_CALL();
2056 ALOGV("postComposition");
2057
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002059 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002060 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002061 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002062 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002063 }
Ady Abraham8164d482019-01-11 14:47:59 -08002064 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002066 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 const auto displayDevice = getDefaultDisplayDeviceLocked();
2068 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002069
David Sodman73beded2017-11-15 11:56:06 -08002070 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002071 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002072 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2073
Lloyd Pique32cbe282018-10-19 13:09:22 -07002074 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002075 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002076 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2077 ->getRenderSurface()
2078 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002080 } else {
2081 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2082 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002083
Ady Abraham8164d482019-01-11 14:47:59 -08002084 ASSERT_ON_STACK_GUARD();
2085
David Sodman73beded2017-11-15 11:56:06 -08002086 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2088 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002089 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002090 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002091 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002092
Ana Krulece588e312018-09-18 12:32:24 -07002093 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002094 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002095 if (mUseScheduler) {
2096 mScheduler->getDisplayStatInfo(&stats);
2097 } else {
2098 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2099 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2100 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101
Ady Abraham8164d482019-01-11 14:47:59 -08002102 ASSERT_ON_STACK_GUARD();
2103
David Sodman2b406362017-12-15 13:33:47 -08002104 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002105 // when we started doing work for this frame, but that should be okay
2106 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002107 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002108 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(compositorTiming);
2110
Brian Andersond0010582017-03-07 13:20:31 -08002111 {
David Sodman99974d22017-11-28 12:04:33 -08002112 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002113 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002114 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002115
2116 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002117 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002118
Robert Carr2047fae2016-11-28 14:09:09 -08002119 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002120 bool frameLatched =
2121 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2122 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002123 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002124 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002125 recordBufferingStats(layer->getName().string(),
2126 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002127 }
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002129 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002130
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002131 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002133 if (mUseScheduler) {
2134 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002136 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002137 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2138 enableHardwareVsync();
2139 } else {
2140 disableHardwareVsync(false);
2141 }
Ady Abraham8164d482019-01-11 14:47:59 -08002142 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002143 }
2144 }
2145
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002146 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2148 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002149 if (mUseScheduler) {
2150 mScheduler->enableHardwareVsync();
2151 } else {
2152 enableHardwareVsync();
2153 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002154 }
2155 }
2156
Ady Abraham8164d482019-01-11 14:47:59 -08002157 ASSERT_ON_STACK_GUARD();
2158
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002159 if (mAnimCompositionPending) {
2160 mAnimCompositionPending = false;
2161
Brian Anderson4e606e32017-03-16 15:34:57 -07002162 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002163 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002164 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002165
2166 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002167 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002168 // The HWC doesn't support present fences, so use the refresh
2169 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002170 const nsecs_t presentTime =
2171 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002172 DEFINE_STACK_GUARD(presentTime);
2173
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002174 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002175 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002176 }
2177 mAnimFrameTracker.advanceFrame();
2178 }
Dan Stozab90cf072015-03-05 11:05:59 -08002179
Ady Abraham8164d482019-01-11 14:47:59 -08002180 ASSERT_ON_STACK_GUARD();
2181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002183 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002184 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002185 }
2186
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
2188
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002189 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002190
Ady Abraham8164d482019-01-11 14:47:59 -08002191 ASSERT_ON_STACK_GUARD();
2192
Lloyd Pique32cbe282018-10-19 13:09:22 -07002193 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2194 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002195 return;
2196 }
2197
2198 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002200 if (mHasPoweredOff) {
2201 mHasPoweredOff = false;
2202 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002203 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002204 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002205 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002206 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002207 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2208 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002209 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002210 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002211 }
David Sodman4a36e932017-11-07 14:29:47 -08002212 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002213
2214 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002215 }
David Sodman4a36e932017-11-07 14:29:47 -08002216 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002217 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002218
2219 {
2220 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002221 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002222 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002223 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002224 if (refillCount > 0) {
2225 const size_t offset = mTexturePool.size();
2226 mTexturePool.resize(mTexturePoolSize);
2227 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2228 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2229 }
Ady Abraham8164d482019-01-11 14:47:59 -08002230 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002231 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002232
Marissa Wallfda30bb2018-10-12 11:34:28 -07002233 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002234 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002235
2236 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002237}
Ady Abraham8164d482019-01-11 14:47:59 -08002238#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002239
Vishnu Nair4351ad52019-02-11 14:13:02 -08002240void SurfaceFlinger::computeLayerBounds() {
2241 for (const auto& pair : mDisplays) {
2242 const auto& displayDevice = pair.second;
2243 const auto display = displayDevice->getCompositionDisplay();
2244 for (const auto& layer : mDrawingState.layersSortedByZ) {
2245 // only consider the layers on the given layer stack
2246 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
2247 return;
2248 }
2249
2250 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2251 }
2252 }
2253}
2254
Mathias Agopiancd60f992012-08-16 16:28:27 -07002255void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002256 ATRACE_CALL();
2257 ALOGV("rebuildLayerStacks");
2258
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002259 // We need to clear these out now as these may be holding on to a
2260 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2261 // also holds a reference. When the set of visible layers is recomputed,
2262 // some layers may be destroyed if the only thing keeping them alive was
2263 // that list of visible layers associated with each display. The layer
2264 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2265 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2266 for (const auto& [token, display] : mDisplays) {
2267 getBE().mCompositionInfo[token].clear();
2268 }
2269
Mathias Agopiancd60f992012-08-16 16:28:27 -07002270 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002271 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002272 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002273 mVisibleRegionsDirty = false;
2274 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002275
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002276 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 const auto& displayDevice = pair.second;
2278 auto display = displayDevice->getCompositionDisplay();
2279 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002280 Region opaqueRegion;
2281 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002282 compositionengine::Output::OutputLayers layersSortedByZ;
2283 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002284 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002285 const ui::Transform& tr = displayState.transform;
2286 const Rect bounds = displayState.bounds;
2287 if (displayState.isEnabled) {
2288 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002289
Jeff Sharkey76488112017-02-27 14:15:18 -07002290 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002291 auto compositionLayer = layer->getCompositionLayer();
2292 if (compositionLayer == nullptr) {
2293 return;
2294 }
2295
Chia-I Wu83806892017-11-16 10:50:20 -08002296 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002297 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002298 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2299 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2300
Lloyd Piqueef36b002019-01-23 17:52:04 -08002301 if (display->belongsInOutput(layer->getLayerStack(),
2302 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002303 Region drawRegion(tr.transform(
2304 layer->visibleNonTransparentRegion));
2305 drawRegion.andSelf(bounds);
2306 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002307 layersSortedByZ.emplace_back(
2308 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2309 layerFE));
2310
2311 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002312 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002313 // Clear out the HWC layer if this layer was
2314 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002315 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002316 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002317 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002318 // WM changes display->layerStack upon sleep/awake.
2319 // Here we make sure we delete the HWC layers even if
2320 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002322 }
2323
2324 // If a layer is not going to get a release fence because
2325 // it is invisible, but it is also going to release its
2326 // old buffer, add it to the list of layers needing
2327 // fences.
2328 if (hwcLayerDestroyed) {
2329 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2330 mLayersWithQueuedFrames.cend(), layer);
2331 if (found != mLayersWithQueuedFrames.cend()) {
2332 layersNeedingFences.add(layer);
2333 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002334 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002335 });
2336 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002337
2338 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2339
2340 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002341 displayDevice->setLayersNeedingFences(layersNeedingFences);
2342
2343 Region undefinedRegion{bounds};
2344 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2345
2346 display->editState().undefinedRegion = undefinedRegion;
2347 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002348 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002349 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002350}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002351
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002352// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002354// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002356// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357// The returned HDR data space is one of
2358// - Dataspace::UNKNOWN
2359// - Dataspace::BT2020_HLG
2360// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2362 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002363 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002364 *outHdrDataSpace = Dataspace::UNKNOWN;
2365
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002367 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368 case Dataspace::V0_SCRGB:
2369 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002370 case Dataspace::BT2020:
2371 case Dataspace::BT2020_ITU:
2372 case Dataspace::BT2020_LINEAR:
2373 case Dataspace::DISPLAY_BT2020:
2374 bestDataSpace = Dataspace::DISPLAY_BT2020;
2375 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002377 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002378 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379 case Dataspace::BT2020_PQ:
2380 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002381 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002382 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002383 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002384 case Dataspace::BT2020_HLG:
2385 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002386 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002387 // When there's mixed PQ content and HLG content, we set the HDR
2388 // data space to be BT2020_PQ and convert HLG to PQ.
2389 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2390 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002391 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002392 break;
2393 default:
2394 break;
2395 }
Romain Guy54f154a2017-10-24 21:40:32 +01002396 }
2397
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002398 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002399}
2400
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002401// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2403 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2405 *outMode = ColorMode::NATIVE;
2406 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002407 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002408 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002409 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002410
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002411 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002413
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002414 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2415
Peiyong Lindfde5112018-06-05 10:58:41 -07002416 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002417 const bool isHdr =
2418 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002419 if (isHdr) {
2420 bestDataSpace = hdrDataSpace;
2421 }
2422
Chia-I Wu0d711262018-05-21 15:19:35 -07002423 RenderIntent intent;
2424 switch (mDisplayColorSetting) {
2425 case DisplayColorSetting::MANAGED:
2426 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002427 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002428 break;
2429 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002430 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002431 break;
2432 default: // vendor display color setting
2433 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2434 break;
2435 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002436
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002437 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002438}
2439
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2441 auto display = displayDevice->getCompositionDisplay();
2442 const auto& displayState = display->getState();
2443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002444 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2446 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002447
David Sodmanfa9b2af2017-12-24 13:28:59 -08002448 // If nothing has changed (!dirty), don't recompose.
2449 // If something changed, but we don't currently have any visible layers,
2450 // and didn't when we last did a composition, then skip it this time.
2451 // The second rule does two things:
2452 // - When all layers are removed from a display, we'll emit one black
2453 // frame, then nothing more until we get new layers.
2454 // - When a display is created with a private layer stack, we won't
2455 // emit any black frames until a layer is added to the layer stack.
2456 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 const char flagPrefix[] = {'-', '+'};
2459 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002460 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2461 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2462 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2463 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002464
Lloyd Pique31cb2942018-10-19 17:23:03 -07002465 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002466
David Sodmanfa9b2af2017-12-24 13:28:59 -08002467 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002469 }
2470}
2471
Lloyd Pique32cbe282018-10-19 13:09:22 -07002472void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2473 auto display = displayDevice->getCompositionDisplay();
2474 const auto& displayState = display->getState();
2475
2476 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002477 return;
David Sodman2b406362017-12-15 13:33:47 -08002478 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002479
Lloyd Pique31cb2942018-10-19 17:23:03 -07002480 status_t result = display->getRenderSurface()->prepareFrame(
2481 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002484}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002485
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002487 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 ALOGV("doComposition");
2489
Lloyd Pique32cbe282018-10-19 13:09:22 -07002490 auto display = displayDevice->getCompositionDisplay();
2491 const auto& displayState = display->getState();
2492
2493 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002494 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002495 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002496
David Sodmanfa9b2af2017-12-24 13:28:59 -08002497 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002499
Lloyd Pique32cbe282018-10-19 13:09:22 -07002500 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002501 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002502 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002504}
2505
David Sodmanfa9b2af2017-12-24 13:28:59 -08002506void SurfaceFlinger::postFrame()
2507{
2508 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 const auto display = getDefaultDisplayDeviceLocked();
2510 if (display && getHwComposer().isConnected(*display->getId())) {
2511 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002512 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2513 logFrameStats();
2514 }
2515 }
2516}
2517
Lloyd Pique32cbe282018-10-19 13:09:22 -07002518void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002519 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002520 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002521
Lloyd Pique32cbe282018-10-19 13:09:22 -07002522 auto display = displayDevice->getCompositionDisplay();
2523 const auto& displayState = display->getState();
2524 const auto displayId = display->getId();
2525
David Sodmanfa9b2af2017-12-24 13:28:59 -08002526 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002527
Lloyd Pique32cbe282018-10-19 13:09:22 -07002528 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 if (displayId) {
2530 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002531 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002532 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002533 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002534 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002535
Chia-I Wu7b549592017-11-15 09:14:57 -08002536 // The layer buffer from the previous frame (if any) is released
2537 // by HWC only when the release fence from this frame (if any) is
2538 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 if (displayId && layer->hasHwcLayer(*displayId)) {
2540 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2541 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002542 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002543
2544 // If the layer was client composited in the previous frame, we
2545 // need to merge with the previous client target acquire fence.
2546 // Since we do not track that, always merge with the current
2547 // client target acquire fence when it is available, even though
2548 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002549 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002550 releaseFence =
2551 Fence::merge("LayerRelease", releaseFence,
2552 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002553 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002554
David Sodman15094112018-10-11 09:39:37 -07002555 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 }
Chia-I Wu83806892017-11-16 10:50:20 -08002557
2558 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002560 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002561 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002563 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002564 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002565 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002566 }
2567 }
2568
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 if (displayId) {
2570 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002571 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002572 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573}
2574
Mathias Agopian87baae12012-07-31 12:38:26 -07002575void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576{
Mathias Agopian841cde52012-03-01 15:44:37 -08002577 ATRACE_CALL();
2578
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002579 // here we keep a copy of the drawing state (that is the state that's
2580 // going to be overwritten by handleTransactionLocked()) outside of
2581 // mStateLock so that the side-effects of the State assignment
2582 // don't happen with mStateLock held (which can cause deadlocks).
2583 State drawingState(mDrawingState);
2584
Mathias Agopianca4d3602011-05-19 15:38:14 -07002585 Mutex::Autolock _l(mStateLock);
2586 const nsecs_t now = systemTime();
2587 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588
Mathias Agopianca4d3602011-05-19 15:38:14 -07002589 // Here we're guaranteed that some transaction flags are set
2590 // so we can call handleTransactionLocked() unconditionally.
2591 // We call getTransactionFlags(), which will also clear the flags,
2592 // with mStateLock held to guarantee that mCurrentState won't change
2593 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002594
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002595 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002596 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002597 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002598
Mathias Agopianca4d3602011-05-19 15:38:14 -07002599 mLastTransactionTime = systemTime() - now;
2600 mDebugInTransaction = 0;
2601 invalidateHwcGeometry();
2602 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002603}
2604
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2606 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 const std::optional<DisplayIdentificationInfo> info =
2608 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002609
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002611 continue;
2612 }
2613
Lloyd Piqueba04e622017-12-14 17:11:26 -08002614 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002616 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 mPhysicalDisplayTokens[info->id] = new BBinder();
2618 DisplayDeviceState state;
2619 state.displayId = info->id;
2620 state.isSecure = true; // All physical displays are currently considered secure.
2621 state.displayName = info->name;
2622 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2623 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002624 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002625 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002626 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002627
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2629 if (index >= 0) {
2630 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2631 mInterceptor->saveDisplayDeletion(state.sequenceId);
2632 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002633 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002634 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002635 }
2636
2637 processDisplayChangesLocked();
2638 }
2639
2640 mPendingHotplugEvents.clear();
2641}
2642
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002643void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002644 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002645 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2646 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002647 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002648 mEventThread->onHotplugReceived(displayId, connected);
2649 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002650 }
2651}
2652
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002655 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 const sp<IGraphicBufferProducer>& producer) {
2657 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002658 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 creationArgs.isSecure = state.isSecure;
2661 creationArgs.displaySurface = dispSurface;
2662 creationArgs.hasWideColorGamut = false;
2663 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002664
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002665 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 creationArgs.isPrimary = isInternalDisplay;
2667
2668 if (useColorManagement && displayId) {
2669 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002670 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002671 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002672 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002674
Dominik Laskowski7e045462018-05-30 13:02:02 -07002675 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002677 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002678 }
tangrobin6753a022018-08-10 10:58:54 +08002679 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 if (displayId) {
2682 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002683 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002684 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002685 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002686
Lloyd Pique90c115d2018-09-18 21:39:42 -07002687 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002688 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002689 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691 // Make sure that composition can never be stalled by a virtual display
2692 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002693 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002694 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002695 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2696 }
2697
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 creationArgs.displayInstallOrientation =
2699 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002700
Lloyd Pique99d3da52018-01-22 17:48:03 -08002701 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002702 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002703
Lloyd Pique90c115d2018-09-18 21:39:42 -07002704 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002705
2706 if (maxFrameBufferAcquiredBuffers >= 3) {
2707 nativeWindowSurface->preallocateBuffers();
2708 }
2709
2710 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002711 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002712 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002713 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002714 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002715 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002716 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2717 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002718 if (!state.isVirtual()) {
2719 LOG_ALWAYS_FATAL_IF(!displayId);
2720 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002721 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 display->setLayerStack(state.layerStack);
2724 display->setProjection(state.orientation, state.viewport, state.frame);
2725 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002728}
2729
Lloyd Pique347200f2017-12-14 17:00:15 -08002730void SurfaceFlinger::processDisplayChangesLocked() {
2731 // here we take advantage of Vector's copy-on-write semantics to
2732 // improve performance by skipping the transaction entirely when
2733 // know that the lists are identical
2734 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2735 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2736 if (!curr.isIdenticalTo(draw)) {
2737 mVisibleRegionsDirty = true;
2738 const size_t cc = curr.size();
2739 size_t dc = draw.size();
2740
2741 // find the displays that were removed
2742 // (ie: in drawing state but not in current state)
2743 // also handle displays that changed
2744 // (ie: displays that are in both lists)
2745 for (size_t i = 0; i < dc;) {
2746 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2747 if (j < 0) {
2748 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002750 // Save display ID before disconnecting.
2751 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002752 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002753
2754 if (!display->isVirtual()) {
2755 LOG_ALWAYS_FATAL_IF(!displayId);
2756 dispatchDisplayHotplugEvent(displayId->value, false);
2757 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002759
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 } else {
2762 // this display is in both lists. see if something changed.
2763 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2766 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2767 if (state_binder != draw_binder) {
2768 // changing the surface is like destroying and
2769 // recreating the DisplayDevice, so we just remove it
2770 // from the drawing state, so that it get re-added
2771 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002773 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002775 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 mDrawingState.displays.removeItemsAt(i);
2777 dc--;
2778 // at this point we must loop to the next item
2779 continue;
2780 }
2781
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002784 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002785 }
2786 if ((state.orientation != draw[i].orientation) ||
2787 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002788 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002789 }
2790 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002791 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 }
2793 }
2794 }
2795 ++i;
2796 }
2797
2798 // find displays that were added
2799 // (ie: in current state but not in drawing state)
2800 for (size_t i = 0; i < cc; i++) {
2801 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2802 const DisplayDeviceState& state(curr[i]);
2803
Lloyd Pique542307f2018-10-19 13:24:08 -07002804 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002805 sp<IGraphicBufferProducer> producer;
2806 sp<IGraphicBufferProducer> bqProducer;
2807 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002808 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002809
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002811 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002812 // Virtual displays without a surface are dormant:
2813 // they have external state (layer stack, projection,
2814 // etc.) but no internal state (i.e. a DisplayDevice).
2815 if (state.surface != nullptr) {
2816 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002818 int width = 0;
2819 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2820 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2821 int height = 0;
2822 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2823 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2824 int intFormat = 0;
2825 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2826 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002827 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002828
Dominik Laskowski075d3172018-05-24 15:50:06 -07002829 displayId =
2830 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002831 }
2832
2833 // TODO: Plumb requested format back up to consumer
2834
2835 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002836 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002837 bqProducer, bqConsumer,
2838 state.displayName);
2839
2840 dispSurface = vds;
2841 producer = vds;
2842 }
2843 } else {
2844 ALOGE_IF(state.surface != nullptr,
2845 "adding a supported display, but rendering "
2846 "surface is provided (%p), ignoring it",
2847 state.surface.get());
2848
Dominik Laskowski075d3172018-05-24 15:50:06 -07002849 displayId = state.displayId;
2850 LOG_ALWAYS_FATAL_IF(!displayId);
2851 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002852 producer = bqProducer;
2853 }
2854
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002856 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002857 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002858 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002860 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002861 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002862 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002863 }
2864 }
2865 }
2866 }
2867 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002868
2869 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002870}
2871
Mathias Agopian87baae12012-07-31 12:38:26 -07002872void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002873{
Dan Stoza7dde5992015-05-22 09:51:44 -07002874 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002875 mCurrentState.traverseInZOrder([](Layer* layer) {
2876 layer->notifyAvailableFrames();
2877 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002878
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 /*
2880 * Traversal of the children
2881 * (perform the transaction for each of them if needed)
2882 */
2883
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002885 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002887 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888
2889 const uint32_t flags = layer->doTransaction(0);
2890 if (flags & Layer::eVisibleRegion)
2891 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002892
2893 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002894 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002895 }
Robert Carr2047fae2016-11-28 14:09:09 -08002896 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 }
2898
2899 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002900 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 */
2902
Mathias Agopiane57f2922012-08-09 16:29:12 -07002903 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002904 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002905 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002908 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002909 // The transform hint might have changed for some layers
2910 // (either because a display has changed, or because a layer
2911 // as changed).
2912 //
2913 // Walk through all the layers in currentLayers,
2914 // and update their transform hint.
2915 //
2916 // If a layer is visible only on a single display, then that
2917 // display is used to calculate the hint, otherwise we use the
2918 // default display.
2919 //
2920 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2921 // the hint is set before we acquire a buffer from the surface texture.
2922 //
2923 // NOTE: layer transactions have taken place already, so we use their
2924 // drawing state. However, SurfaceFlinger's own transaction has not
2925 // happened yet, so we must use the current state layer list
2926 // (soon to become the drawing state list).
2927 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002928 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002929 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002930 bool first = true;
2931 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002932 // NOTE: we rely on the fact that layers are sorted by
2933 // layerStack first (so we don't have to traverse the list
2934 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002936 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002937 currentlayerStack = layerStack;
2938 // figure out if this layerstack is mirrored
2939 // (more than one display) if so, pick the default display,
2940 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002941 hintDisplay = nullptr;
2942 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002943 if (display->getCompositionDisplay()
2944 ->belongsInOutput(layer->getLayerStack(),
2945 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002946 if (hintDisplay) {
2947 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002948 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002949 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002950 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002951 }
2952 }
2953 }
2954 }
Chet Haase91d25932013-04-11 15:24:55 -07002955
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002957 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2958 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002959
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002960 // could be null when this layer is using a layerStack
2961 // that is not visible on any display. Also can occur at
2962 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002963 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002964 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002965
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002966 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002967 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002968 if (hintDisplay) {
2969 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002970 }
Robert Carr2047fae2016-11-28 14:09:09 -08002971
2972 first = false;
2973 });
Mathias Agopian84300952012-11-21 16:02:13 -08002974 }
2975
2976
Mathias Agopian3559b072012-08-15 13:46:03 -07002977 /*
2978 * Perform our own transaction if needed
2979 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002980
2981 if (mLayersAdded) {
2982 mLayersAdded = false;
2983 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002984 mVisibleRegionsDirty = true;
2985 }
2986
2987 // some layers might have been removed, so
2988 // we need to update the regions they're exposing.
2989 if (mLayersRemoved) {
2990 mLayersRemoved = false;
2991 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002992 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002994 // this layer is not visible anymore
2995 // TODO: we could traverse the tree from front to back and
2996 // compute the actual visible region
2997 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002999 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003000 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003001 }
Robert Carr2047fae2016-11-28 14:09:09 -08003002 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 }
3004
3005 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003006}
3007
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003008void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003009 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003010 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003011 return;
3012 }
3013
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003014 if (mVisibleRegionsDirty || mInputInfoChanged) {
3015 mInputInfoChanged = false;
3016 updateInputWindowInfo();
3017 }
3018
3019 executeInputWindowCommands();
3020}
3021
3022void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003023 Vector<InputWindowInfo> inputHandles;
3024
3025 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3026 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003027 // When calculating the screen bounds we ignore the transparent region since it may
3028 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003029 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003030 }
3031 });
3032 mInputFlinger->setInputWindows(inputHandles);
3033}
3034
chaviwfbe5d9c2018-12-26 12:23:37 -08003035void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003036 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3037 if (transferTouchFocusCommand.fromToken != nullptr &&
3038 transferTouchFocusCommand.toToken != nullptr &&
3039 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3040 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3041 transferTouchFocusCommand.toToken);
3042 }
3043 }
3044
3045 mInputWindowCommands.clear();
3046}
3047
Riley Andrews03414a12014-07-01 14:22:59 -07003048void SurfaceFlinger::updateCursorAsync()
3049{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003050 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003051 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003052 continue;
3053 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3056 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003057 }
3058 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059}
3060
chaviw61626f22018-11-15 16:26:27 -08003061void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3062 if (layer->hasReadyFrame()) {
3063 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3064 if (layer->shouldPresentNow(expectedPresentTime)) {
3065 bool ignored = false;
3066 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3067 }
3068 }
3069 layer->releasePendingBuffer(systemTime());
3070}
3071
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072void SurfaceFlinger::commitTransaction()
3073{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003074 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003075 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 for (const auto& l : mLayersPendingRemoval) {
3077 recordBufferingStats(l->getName().string(),
3078 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003079
3080 // We need to release the HWC layers when the Layer is removed
3081 // from the current state otherwise the HWC layer just continues
3082 // showing at its last configured state until we eventually
3083 // abandon the buffer queue.
3084 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003085 l->destroyHwcLayersForAllDisplays();
3086 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003087 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003088 }
3089 mLayersPendingRemoval.clear();
3090 }
3091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003092 // If this transaction is part of a window animation then the next frame
3093 // we composite should be considered an animation as well.
3094 mAnimCompositionPending = mAnimTransactionPending;
3095
Mathias Agopian4fec8732012-06-29 14:12:52 -07003096 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003097 // clear the "changed" flags in current state
3098 mCurrentState.colorMatrixChanged = false;
3099
Robert Carr1f0a16a2016-10-24 16:27:39 -07003100 mDrawingState.traverseInZOrder([](Layer* layer) {
3101 layer->commitChildList();
3102 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003103 mTransactionPending = false;
3104 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106}
3107
Lloyd Pique32cbe282018-10-19 13:09:22 -07003108void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003109 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003110 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003111 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003112
Lloyd Pique32cbe282018-10-19 13:09:22 -07003113 auto display = displayDevice->getCompositionDisplay();
3114
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 Region aboveOpaqueLayers;
3116 Region aboveCoveredLayers;
3117 Region dirty;
3118
Mathias Agopian87baae12012-07-31 12:38:26 -07003119 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120
Robert Carr2047fae2016-11-28 14:09:09 -08003121 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003122 // start with the whole surface at its current location
3123 const Layer::State& s(layer->getDrawingState());
3124
Jesse Hall01e29052013-02-19 16:13:35 -08003125 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003126 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003127 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003128 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003129
Mathias Agopianab028732010-03-16 16:41:46 -07003130 /*
3131 * opaqueRegion: area of a surface that is fully opaque.
3132 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003134
3135 /*
3136 * visibleRegion: area of a surface that is visible on screen
3137 * and not fully transparent. This is essentially the layer's
3138 * footprint minus the opaque regions above it.
3139 * Areas covered by a translucent surface are considered visible.
3140 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003142
3143 /*
3144 * coveredRegion: area of a surface that is covered by all
3145 * visible regions above it (which includes the translucent areas).
3146 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003148
Jesse Halla8026d22012-09-25 13:25:04 -07003149 /*
3150 * transparentRegion: area of a surface that is hinted to be completely
3151 * transparent. This is only used to tell when the layer has no visible
3152 * non-transparent regions and can be removed from the layer list. It
3153 * does not affect the visibleRegion of this layer or any layers
3154 * beneath it. The hint may not be correct if apps don't respect the
3155 * SurfaceView restrictions (which, sadly, some don't).
3156 */
3157 Region transparentRegion;
3158
Mathias Agopianab028732010-03-16 16:41:46 -07003159
3160 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003161 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003162 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003163 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003166 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003167 if (!visibleRegion.isEmpty()) {
3168 // Remove the transparent area from the visible region
3169 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003170 if (tr.preserveRects()) {
3171 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003172 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003174 // transformation too complex, can't do the
3175 // transparent region optimization.
3176 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003177 }
Mathias Agopianab028732010-03-16 16:41:46 -07003178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179
Mathias Agopianab028732010-03-16 16:41:46 -07003180 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003182 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003183 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003184 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003185 // the opaque region is the layer's footprint
3186 opaqueRegion = visibleRegion;
3187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188 }
3189 }
3190
Robert Carre5f4f692018-01-12 13:12:28 -08003191 if (visibleRegion.isEmpty()) {
3192 layer->clearVisibilityRegions();
3193 return;
3194 }
3195
Mathias Agopianab028732010-03-16 16:41:46 -07003196 // Clip the covered region to the visible region
3197 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3198
3199 // Update aboveCoveredLayers for next (lower) layer
3200 aboveCoveredLayers.orSelf(visibleRegion);
3201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 // subtract the opaque region covered by the layers above us
3203 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204
3205 // compute this layer's dirty region
3206 if (layer->contentDirty) {
3207 // we need to invalidate the whole region
3208 dirty = visibleRegion;
3209 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003210 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 layer->contentDirty = false;
3212 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003213 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003214 * the exposed region consists of two components:
3215 * 1) what's VISIBLE now and was COVERED before
3216 * 2) what's EXPOSED now less what was EXPOSED before
3217 *
3218 * note that (1) is conservative, we start with the whole
3219 * visible region but only keep what used to be covered by
3220 * something -- which mean it may have been exposed.
3221 *
3222 * (2) handles areas that were not covered by anything but got
3223 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003224 */
Mathias Agopianab028732010-03-16 16:41:46 -07003225 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003226 const Region oldVisibleRegion = layer->visibleRegion;
3227 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003228 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3229 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 }
3231 dirty.subtractSelf(aboveOpaqueLayers);
3232
3233 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003234 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235
Mathias Agopianab028732010-03-16 16:41:46 -07003236 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003238
Jesse Halla8026d22012-09-25 13:25:04 -07003239 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 layer->setVisibleRegion(visibleRegion);
3241 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003242 layer->setVisibleNonTransparentRegion(
3243 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003244 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245
Mathias Agopian87baae12012-07-31 12:38:26 -07003246 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247}
3248
Chia-I Wuab0c3192017-08-01 11:29:00 -07003249void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003250 for (const auto& [token, displayDevice] : mDisplays) {
3251 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003252 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003253 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003254 }
3255 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003256}
3257
Daniel Solomon42d04562019-01-20 21:03:19 -08003258void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3259 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3260 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3261 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3262 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3263 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3264 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3265 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3266 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3267 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3268 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3269 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3270 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3271}
3272
Dan Stoza6b9454d2014-11-07 16:00:59 -08003273bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003275 ALOGV("handlePageFlip");
3276
Brian Andersond6927fb2016-07-23 23:37:30 -07003277 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278
Mathias Agopian4fec8732012-06-29 14:12:52 -07003279 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003280 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003281 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003282
3283 // Store the set of layers that need updates. This set must not change as
3284 // buffers are being latched, as this could result in a deadlock.
3285 // Example: Two producers share the same command stream and:
3286 // 1.) Layer 0 is latched
3287 // 2.) Layer 0 gets a new frame
3288 // 2.) Layer 1 gets a new frame
3289 // 3.) Layer 1 is latched.
3290 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3291 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003292 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003293 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003294 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003295 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3296 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003297 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003298 } else {
3299 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003300 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003301 } else {
3302 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003303 }
Robert Carr2047fae2016-11-28 14:09:09 -08003304 });
3305
Lloyd Piquef2c79392018-12-20 16:23:33 -08003306 if (!mLayersWithQueuedFrames.empty()) {
3307 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3308 // writes to Layer current state. See also b/119481871
3309 Mutex::Autolock lock(mStateLock);
3310
3311 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003312 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3313 mLayersPendingRefresh.push_back(layer);
3314 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003315 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003316 if (layer->isBufferLatched()) {
3317 newDataLatched = true;
3318 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003319 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003320 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003321
Alec Mouri86770e52018-09-24 22:40:58 +00003322 // Clear the renderengine fence here...
3323 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3324 // clear instead of sp::clear.
3325 getBE().flushFence = Fence::NO_FENCE;
3326
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003327 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003328
3329 // If we will need to wake up at some time in the future to deal with a
3330 // queued frame that shouldn't be displayed during this vsync period, wake
3331 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003332 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003333 signalLayerUpdate();
3334 }
3335
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003336 // enter boot animation on first buffer latch
3337 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3338 ALOGI("Enter boot animation");
3339 mBootStage = BootStage::BOOTANIMATION;
3340 }
3341
Dan Stoza6b9454d2014-11-07 16:00:59 -08003342 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003343 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344}
3345
Mathias Agopianad456f92011-01-13 17:53:01 -08003346void SurfaceFlinger::invalidateHwcGeometry()
3347{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003348 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003349}
3350
Lloyd Pique32cbe282018-10-19 13:09:22 -07003351void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003352 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003353 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003354 // We only need to actually compose the display if:
3355 // 1) It is being handled by hardware composer, which may need this to
3356 // keep its virtual display state machine in sync, or
3357 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003358 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003359 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003360 return;
3361 }
3362
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003364 base::unique_fd readyFence;
3365 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003366
3367 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003368 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369}
3370
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003371bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3372 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003373 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003374 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003375
Lloyd Pique32cbe282018-10-19 13:09:22 -07003376 auto display = displayDevice->getCompositionDisplay();
3377 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003378 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003379
3380 const Region bounds(displayState.bounds);
3381 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003382 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003383 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003384
Peiyong Lind3788632018-09-18 16:01:31 -07003385 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003386 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003387
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003388 renderengine::DisplaySettings clientCompositionDisplay;
3389 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3390 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003391
Dan Stoza9e56aa02015-11-02 13:00:03 -08003392 if (hasClientComposition) {
3393 ALOGV("hasClientComposition");
3394
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003395 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003396
3397 if (buf == nullptr) {
3398 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3399 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003400 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003401 return false;
3402 }
3403
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3405 clientCompositionDisplay.clip = displayState.scissor;
3406 const ui::Transform& displayTransform = displayState.transform;
3407 mat4 m;
3408 m[0][0] = displayTransform[0][0];
3409 m[0][1] = displayTransform[0][1];
3410 m[0][3] = displayTransform[0][2];
3411 m[1][0] = displayTransform[1][0];
3412 m[1][1] = displayTransform[1][1];
3413 m[1][3] = displayTransform[1][2];
3414 m[3][0] = displayTransform[2][0];
3415 m[3][1] = displayTransform[2][1];
3416 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003417
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003418 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003419
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003420 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003421 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003422 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003423 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003424 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003425 clientCompositionDisplay.outputDataspace = outputDataspace;
3426 clientCompositionDisplay.maxLuminance =
3427 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003428
Lloyd Pique441d5042018-10-18 16:49:51 -07003429 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003430 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003431 getHwComposer()
3432 .hasDisplayCapability(displayId,
3433 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003434
Peiyong Lind3788632018-09-18 16:01:31 -07003435 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003436 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3437 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003438 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003439 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003440 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003441
Mathias Agopian85d751c2012-08-29 16:59:24 -07003442 /*
3443 * and then, render the layers targeted at the framebuffer
3444 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003445
Dan Stoza9e56aa02015-11-02 13:00:03 -08003446 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003447 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003448 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003449 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003450 const Region viewportRegion(displayState.viewport);
3451 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003452 ALOGV("Layer: %s", layer->getName().string());
3453 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003454 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003455 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 case HWC2::Composition::Cursor:
3457 case HWC2::Composition::Device:
3458 case HWC2::Composition::Sideband:
3459 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003460 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003461 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003462 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003463 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003464 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003465 // never clear the very first layer since we're
3466 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003467 renderengine::LayerSettings layerSettings;
3468 Region dummyRegion;
3469 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3470 layerSettings);
3471
3472 if (prepared) {
3473 layerSettings.source.buffer.buffer = nullptr;
3474 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3475 layerSettings.alpha = half(0.0);
3476 layerSettings.disableBlending = true;
3477 clientCompositionLayers.push_back(layerSettings);
3478 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003479 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003480 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003481 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003482 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003483 renderengine::LayerSettings layerSettings;
3484 bool prepared =
3485 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3486 if (prepared) {
3487 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003488 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 break;
3490 }
3491 default:
3492 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003493 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003494 } else {
3495 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003496 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003497 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003498 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003499
Alec Mouri820c7402019-01-23 13:02:39 -08003500 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003501 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003502 clientCompositionDisplay.clearRegion = clearRegion;
3503 if (!debugRegion.isEmpty()) {
3504 Region::const_iterator it = debugRegion.begin();
3505 Region::const_iterator end = debugRegion.end();
3506 while (it != end) {
3507 const Rect& rect = *it++;
3508 renderengine::LayerSettings layerSettings;
3509 layerSettings.source.buffer.buffer = nullptr;
3510 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3511 layerSettings.geometry.boundaries = rect.toFloatRect();
3512 layerSettings.alpha = half(1.0);
3513 clientCompositionLayers.push_back(layerSettings);
3514 }
3515 }
3516 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3517 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003518 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003519 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520}
3521
Chia-I Wu28e3a252018-09-07 12:05:02 -07003522void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003523 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003524 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525}
3526
Dan Stoza7d89d062015-04-30 13:29:25 -07003527status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003528 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003529 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003530 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003531 const sp<Layer>& parent,
3532 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003533{
Dan Stoza7d89d062015-04-30 13:29:25 -07003534 // add this layer to the current state list
3535 {
3536 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003537 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003538 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3539 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003540 return NO_MEMORY;
3541 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003542 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003543 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003544 } else if (parent == nullptr) {
3545 lbc->onRemovedFromCurrentState();
3546 } else if (parent->isRemovedFromCurrentState()) {
3547 parent->addChild(lbc);
3548 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003549 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003550 parent->addChild(lbc);
3551 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003552
Yiwei Zhang243b3782018-05-15 17:40:04 -07003553 if (gbc != nullptr) {
3554 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3555 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3556 mMaxGraphicBufferProducerListSize,
3557 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3558 mGraphicBufferProducerList.size(),
3559 mMaxGraphicBufferProducerListSize, mNumLayers);
3560 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003561 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003562 }
3563
Mathias Agopian96f08192010-06-02 23:28:45 -07003564 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003565 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003566
Dan Stoza7d89d062015-04-30 13:29:25 -07003567 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003568}
3569
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003570uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003571 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003572}
3573
Mathias Agopian3f844832013-08-07 21:24:32 -07003574uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003575 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576}
3577
Mathias Agopian3f844832013-08-07 21:24:32 -07003578uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003579 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003580}
3581
3582uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003583 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003584 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003585 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003587 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 }
3589 return old;
3590}
3591
Marissa Wall713b63f2018-10-17 15:42:43 -07003592bool SurfaceFlinger::flushTransactionQueues() {
3593 Mutex::Autolock _l(mStateLock);
3594 auto it = mTransactionQueues.begin();
3595 while (it != mTransactionQueues.end()) {
3596 auto& [applyToken, transactionQueue] = *it;
3597
3598 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003599 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3600 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 break;
3602 }
chaviw273171b2018-12-26 11:46:30 -08003603 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003604 transactionQueue.pop();
3605 }
3606
3607 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3608 }
3609 return mTransactionQueues.empty();
3610}
3611
chaviwca27f252018-02-06 16:46:39 -08003612bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3613 for (const ComposerState& state : states) {
3614 // Here we need to check that the interface we're given is indeed
3615 // one of our own. A malicious client could give us a nullptr
3616 // IInterface, or one of its own or even one of our own but a
3617 // different type. All these situations would cause us to crash.
3618 if (state.client == nullptr) {
3619 return true;
3620 }
3621
3622 sp<IBinder> binder = IInterface::asBinder(state.client);
3623 if (binder == nullptr) {
3624 return true;
3625 }
3626
3627 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3628 return true;
3629 }
3630 }
3631 return false;
3632}
3633
Marissa Wall17b4e452018-12-26 16:32:34 -08003634bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3635 const Vector<ComposerState>& states) {
3636 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3637 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3638 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3639 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3640 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3641 return false;
3642 }
3643
Marissa Wall713b63f2018-10-17 15:42:43 -07003644 for (const ComposerState& state : states) {
3645 const layer_state_t& s = state.state;
3646 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3647 continue;
3648 }
3649 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003650 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003651 }
3652 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003653 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003654}
3655
3656void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3657 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003658 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003659 const InputWindowCommands& inputWindowCommands,
3660 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003661 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003662 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003663
chaviwca27f252018-02-06 16:46:39 -08003664 if (containsAnyInvalidClientState(states)) {
3665 return;
3666 }
3667
Marissa Wall713b63f2018-10-17 15:42:43 -07003668 // If its TransactionQueue already has a pending TransactionState or if it is pending
3669 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003670 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3671 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003672 setTransactionFlags(eTransactionNeeded);
3673 return;
3674 }
3675
chaviw273171b2018-12-26 11:46:30 -08003676 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003677}
3678
3679void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003680 const Vector<DisplayState>& displays, uint32_t flags,
3681 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003682 uint32_t transactionFlags = 0;
3683
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 if (flags & eAnimation) {
3685 // For window updates that are part of an animation we must wait for
3686 // previous animation "frames" to be handled.
3687 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003688 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003689 if (CC_UNLIKELY(err != NO_ERROR)) {
3690 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003691 // caller after a few seconds.
3692 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3693 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003694 mAnimTransactionPending = false;
3695 break;
3696 }
3697 }
3698 }
3699
chaviwca27f252018-02-06 16:46:39 -08003700 for (const DisplayState& display : displays) {
3701 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003702 }
3703
Marissa Walle2ffb422018-10-12 11:33:52 -07003704 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003705 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003706 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003707 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003708 // If the state doesn't require a traversal and there are callbacks, send them now
3709 if (!(clientStateFlags & eTraversalNeeded)) {
3710 mTransactionCompletedThread.sendCallbacks();
3711 }
3712 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003713
chaviw273171b2018-12-26 11:46:30 -08003714 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3715
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003716 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3717 // anyway. This can be used as a flush mechanism for previous async transactions.
3718 // Empty animation transaction can be used to simulate back-pressure, so also force a
3719 // transaction for empty animation transactions.
3720 if (transactionFlags == 0 &&
3721 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003722 transactionFlags = eTransactionNeeded;
3723 }
3724
Mathias Agopian386aa982011-11-07 21:58:03 -08003725 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003726 if (mInterceptor->isEnabled()) {
3727 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003728 }
Irvel468051e2016-06-13 16:44:44 -07003729
Mathias Agopian386aa982011-11-07 21:58:03 -08003730 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003731 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3732 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003733 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003734
3735 // if this is a synchronous transaction, wait for it to take effect
3736 // before returning.
3737 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003738 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003739 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003740 if (flags & eAnimation) {
3741 mAnimTransactionPending = true;
3742 }
3743 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003744 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3745 if (CC_UNLIKELY(err != NO_ERROR)) {
3746 // just in case something goes wrong in SF, return to the
3747 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003748 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3749 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003750 break;
3751 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 }
3754}
3755
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003756uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3757 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3758 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003759
Mathias Agopiane57f2922012-08-09 16:29:12 -07003760 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003761 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3762
3763 const uint32_t what = s.what;
3764 if (what & DisplayState::eSurfaceChanged) {
3765 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3766 state.surface = s.surface;
3767 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003768 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003769 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003770 if (what & DisplayState::eLayerStackChanged) {
3771 if (state.layerStack != s.layerStack) {
3772 state.layerStack = s.layerStack;
3773 flags |= eDisplayTransactionNeeded;
3774 }
3775 }
3776 if (what & DisplayState::eDisplayProjectionChanged) {
3777 if (state.orientation != s.orientation) {
3778 state.orientation = s.orientation;
3779 flags |= eDisplayTransactionNeeded;
3780 }
3781 if (state.frame != s.frame) {
3782 state.frame = s.frame;
3783 flags |= eDisplayTransactionNeeded;
3784 }
3785 if (state.viewport != s.viewport) {
3786 state.viewport = s.viewport;
3787 flags |= eDisplayTransactionNeeded;
3788 }
3789 }
3790 if (what & DisplayState::eDisplaySizeChanged) {
3791 if (state.width != s.width) {
3792 state.width = s.width;
3793 flags |= eDisplayTransactionNeeded;
3794 }
3795 if (state.height != s.height) {
3796 state.height = s.height;
3797 flags |= eDisplayTransactionNeeded;
3798 }
3799 }
3800
Mathias Agopiane57f2922012-08-09 16:29:12 -07003801 return flags;
3802}
3803
Robert Carrd4ae7f32018-06-07 16:10:57 -07003804bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3805 IPCThreadState* ipc = IPCThreadState::self();
3806 const int pid = ipc->getCallingPid();
3807 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003808 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003809 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003810 return false;
3811 }
3812 return true;
3813}
3814
chaviwca27f252018-02-06 16:46:39 -08003815uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3816 const layer_state_t& s = composerState.state;
3817 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3818
Mathias Agopian13127d82013-03-05 17:47:11 -08003819 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003820 if (layer == nullptr) {
3821 return 0;
3822 }
3823
chaviw8b3871a2017-11-01 17:41:01 -07003824 uint32_t flags = 0;
3825
Garfield Tan8a3083e2018-12-03 13:21:07 -08003826 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003827 bool geometryAppliesWithResize =
3828 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003829
3830 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3831 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003832 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003833 layer->pushPendingState();
3834 }
3835
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (what & layer_state_t::ePositionChanged) {
3837 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3838 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003839 }
chaviw8b3871a2017-11-01 17:41:01 -07003840 }
3841 if (what & layer_state_t::eLayerChanged) {
3842 // NOTE: index needs to be calculated before we update the state
3843 const auto& p = layer->getParent();
3844 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003845 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003846 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003847 mCurrentState.layersSortedByZ.removeAt(idx);
3848 mCurrentState.layersSortedByZ.add(layer);
3849 // we need traversal (state changed)
3850 // AND transaction (list changed)
3851 flags |= eTransactionNeeded|eTraversalNeeded;
3852 }
chaviw8b3871a2017-11-01 17:41:01 -07003853 } else {
3854 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003855 flags |= eTransactionNeeded|eTraversalNeeded;
3856 }
3857 }
chaviw8b3871a2017-11-01 17:41:01 -07003858 }
3859 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003860 // NOTE: index needs to be calculated before we update the state
3861 const auto& p = layer->getParent();
3862 if (p == nullptr) {
3863 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3864 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3865 mCurrentState.layersSortedByZ.removeAt(idx);
3866 mCurrentState.layersSortedByZ.add(layer);
3867 // we need traversal (state changed)
3868 // AND transaction (list changed)
3869 flags |= eTransactionNeeded|eTraversalNeeded;
3870 }
3871 } else {
3872 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3873 flags |= eTransactionNeeded|eTraversalNeeded;
3874 }
chaviw8b3871a2017-11-01 17:41:01 -07003875 }
3876 }
3877 if (what & layer_state_t::eSizeChanged) {
3878 if (layer->setSize(s.w, s.h)) {
3879 flags |= eTraversalNeeded;
3880 }
3881 }
3882 if (what & layer_state_t::eAlphaChanged) {
3883 if (layer->setAlpha(s.alpha))
3884 flags |= eTraversalNeeded;
3885 }
3886 if (what & layer_state_t::eColorChanged) {
3887 if (layer->setColor(s.color))
3888 flags |= eTraversalNeeded;
3889 }
Peiyong Lind3788632018-09-18 16:01:31 -07003890 if (what & layer_state_t::eColorTransformChanged) {
3891 if (layer->setColorTransform(s.colorTransform)) {
3892 flags |= eTraversalNeeded;
3893 }
3894 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003895 if (what & layer_state_t::eBackgroundColorChanged) {
3896 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3897 flags |= eTraversalNeeded;
3898 }
3899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003901 // TODO: b/109894387
3902 //
3903 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3904 // rotation. To see the problem observe that if we have a square parent, and a child
3905 // of the same size, then we rotate the child 45 degrees around it's center, the child
3906 // must now be cropped to a non rectangular 8 sided region.
3907 //
3908 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3909 // private API, and the WindowManager only uses rotation in one case, which is on a top
3910 // level layer in which cropping is not an issue.
3911 //
3912 // However given that abuse of rotation matrices could lead to surfaces extending outside
3913 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3914 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3915 // transformations.
3916 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003917 flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eTransparentRegionChanged) {
3920 if (layer->setTransparentRegionHint(s.transparentRegion))
3921 flags |= eTraversalNeeded;
3922 }
3923 if (what & layer_state_t::eFlagsChanged) {
3924 if (layer->setFlags(s.flags, s.mask))
3925 flags |= eTraversalNeeded;
3926 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003927 if (what & layer_state_t::eCropChanged_legacy) {
3928 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003929 flags |= eTraversalNeeded;
3930 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003931 if (what & layer_state_t::eCornerRadiusChanged) {
3932 if (layer->setCornerRadius(s.cornerRadius))
3933 flags |= eTraversalNeeded;
3934 }
chaviw8b3871a2017-11-01 17:41:01 -07003935 if (what & layer_state_t::eLayerStackChanged) {
3936 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3937 // We only allow setting layer stacks for top level layers,
3938 // everything else inherits layer stack from its parent.
3939 if (layer->hasParent()) {
3940 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3941 layer->getName().string());
3942 } else if (idx < 0) {
3943 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3944 "that also does not appear in the top level layer list. Something"
3945 " has gone wrong.", layer->getName().string());
3946 } else if (layer->setLayerStack(s.layerStack)) {
3947 mCurrentState.layersSortedByZ.removeAt(idx);
3948 mCurrentState.layersSortedByZ.add(layer);
3949 // we need traversal (state changed)
3950 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003951 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003952 }
3953 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003954 if (what & layer_state_t::eDeferTransaction_legacy) {
3955 if (s.barrierHandle_legacy != nullptr) {
3956 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3957 } else if (s.barrierGbp_legacy != nullptr) {
3958 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003959 if (authenticateSurfaceTextureLocked(gbp)) {
3960 const auto& otherLayer =
3961 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003962 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003963 } else {
3964 ALOGE("Attempt to defer transaction to to an"
3965 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003966 }
3967 }
chaviw8b3871a2017-11-01 17:41:01 -07003968 // We don't trigger a traversal here because if no other state is
3969 // changed, we don't want this to cause any more work
3970 }
3971 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003972 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003973 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003974 if (!hadParent) {
3975 mCurrentState.layersSortedByZ.remove(layer);
3976 }
chaviw8b3871a2017-11-01 17:41:01 -07003977 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003978 }
chaviw8b3871a2017-11-01 17:41:01 -07003979 }
3980 if (what & layer_state_t::eReparentChildren) {
3981 if (layer->reparentChildren(s.reparentHandle)) {
3982 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003983 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003984 }
chaviw8b3871a2017-11-01 17:41:01 -07003985 if (what & layer_state_t::eDetachChildren) {
3986 layer->detachChildren();
3987 }
3988 if (what & layer_state_t::eOverrideScalingModeChanged) {
3989 layer->setOverrideScalingMode(s.overrideScalingMode);
3990 // We don't trigger a traversal here because if no other state is
3991 // changed, we don't want this to cause any more work
3992 }
Marissa Wall61c58622018-07-18 10:12:20 -07003993 if (what & layer_state_t::eTransformChanged) {
3994 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3995 }
3996 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3997 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3998 flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eCropChanged) {
4001 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4002 }
Marissa Wall861616d2018-10-22 12:52:23 -07004003 if (what & layer_state_t::eFrameChanged) {
4004 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4005 }
Marissa Wall61c58622018-07-18 10:12:20 -07004006 if (what & layer_state_t::eAcquireFenceChanged) {
4007 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eDataspaceChanged) {
4010 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4011 }
4012 if (what & layer_state_t::eHdrMetadataChanged) {
4013 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4014 }
4015 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4016 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4017 }
4018 if (what & layer_state_t::eApiChanged) {
4019 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4020 }
4021 if (what & layer_state_t::eSidebandStreamChanged) {
4022 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4023 }
Robert Carr720e5062018-07-30 17:45:14 -07004024 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004025 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4026 layer->setInputInfo(s.inputInfo);
4027 flags |= eTraversalNeeded;
4028 } else {
4029 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4030 }
Robert Carr720e5062018-07-30 17:45:14 -07004031 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004032 if (what & layer_state_t::eMetadataChanged) {
4033 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4034 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004035 std::vector<sp<CallbackHandle>> callbackHandles;
4036 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4037 mTransactionCompletedThread.run();
4038 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4039 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4040 }
4041 }
Marissa Wall73411622019-01-25 10:45:41 -08004042
4043 if (what & layer_state_t::eBufferChanged) {
4044 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4045 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4046 s.buffer);
4047 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004048 if (what & layer_state_t::eCachedBufferChanged) {
4049 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004050 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4051 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004052 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4053 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004054 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4055 // Do not put anything that updates layer state or modifies flags after
4056 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004057 return flags;
4058}
4059
chaviw273171b2018-12-26 11:46:30 -08004060uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4061 uint32_t flags = 0;
4062 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4063 flags |= eTraversalNeeded;
4064 }
4065
4066 mInputWindowCommands.merge(inputWindowCommands);
4067 return flags;
4068}
4069
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004070status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4071 uint32_t h, PixelFormat format, uint32_t flags,
4072 LayerMetadata metadata, sp<IBinder>* handle,
4073 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004074 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004075 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004076 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004078 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004079
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004080 status_t result = NO_ERROR;
4081
4082 sp<Layer> layer;
4083
Cody Northropbc755282017-03-31 12:00:08 -06004084 String8 uniqueName = getUniqueLayerName(name);
4085
Mathias Agopian3165cc22012-08-08 19:42:09 -07004086 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004087 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004088 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4089 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004092 case ISurfaceComposerClient::eFXSurfaceBufferState:
4093 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4094 break;
chaviw13fdc492017-06-27 12:40:18 -07004095 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004096 // check if buffer size is set for color layer.
4097 if (w > 0 || h > 0) {
4098 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4099 int(w), int(h));
4100 return BAD_VALUE;
4101 }
4102
chaviw13fdc492017-06-27 12:40:18 -07004103 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004104 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004105 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004107 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004108 // check if buffer size is set for container layer.
4109 if (w > 0 || h > 0) {
4110 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4111 int(w), int(h));
4112 return BAD_VALUE;
4113 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004114 result = createContainerLayer(client,
4115 uniqueName, w, h, flags,
4116 handle, &layer);
4117 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004118 default:
4119 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 break;
4121 }
4122
Dan Stoza7d89d062015-04-30 13:29:25 -07004123 if (result != NO_ERROR) {
4124 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004126
Chia-I Wuab0c3192017-08-01 11:29:00 -07004127 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4128 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004129 if (metadata.has(METADATA_WINDOW_TYPE)) {
4130 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4131 if (windowType == 441731) {
4132 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4133 layer->setPrimaryDisplayOnly();
4134 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004135 }
4136
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004137 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004138
Robert Carrb89ea9d2018-12-10 13:01:14 -08004139 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4140 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4141 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004142 if (result != NO_ERROR) {
4143 return result;
4144 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004145 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004146
4147 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149}
4150
Cody Northropbc755282017-03-31 12:00:08 -06004151String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4152{
4153 bool matchFound = true;
4154 uint32_t dupeCounter = 0;
4155
4156 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4157 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4158
Dan Stoza436ccf32018-06-21 12:10:12 -07004159 // Grab the state lock since we're accessing mCurrentState
4160 Mutex::Autolock lock(mStateLock);
4161
Cody Northropbc755282017-03-31 12:00:08 -06004162 // Loop over layers until we're sure there is no matching name
4163 while (matchFound) {
4164 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004166 if (layer->getName() == uniqueName) {
4167 matchFound = true;
4168 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4169 }
4170 });
4171 }
4172
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004173 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4174 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004175
4176 return uniqueName;
4177}
4178
Marissa Wallfd668622018-05-10 10:21:13 -07004179status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4180 uint32_t w, uint32_t h, uint32_t flags,
4181 PixelFormat& format, sp<IBinder>* handle,
4182 sp<IGraphicBufferProducer>* gbp,
4183 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004185 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 case PIXEL_FORMAT_TRANSPARENT:
4187 case PIXEL_FORMAT_TRANSLUCENT:
4188 format = PIXEL_FORMAT_RGBA_8888;
4189 break;
4190 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004191 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 break;
4193 }
4194
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004195 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004196 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004197 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004199 *handle = layer->getHandle();
4200 *gbp = layer->getProducer();
4201 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203
Marissa Wallfd668622018-05-10 10:21:13 -07004204 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004205 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206}
4207
Marissa Wall61c58622018-07-18 10:12:20 -07004208status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4209 uint32_t w, uint32_t h, uint32_t flags,
4210 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004211 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004212 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004213 *handle = layer->getHandle();
4214 *outLayer = layer;
4215
4216 return NO_ERROR;
4217}
4218
chaviw13fdc492017-06-27 12:40:18 -07004219status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004220 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004221 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004223 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004224 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004225 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004226}
4227
Robert Carr6b3f6c52018-08-13 13:05:17 -07004228status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4229 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4230 sp<IBinder>* handle, sp<Layer>* outLayer)
4231{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004232 *outLayer =
4233 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004234 *handle = (*outLayer)->getHandle();
4235 return NO_ERROR;
4236}
4237
4238
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004239void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004240 mLayersPendingRemoval.add(layer);
4241 mLayersRemoved = true;
4242 setTransactionFlags(eTransactionNeeded);
4243}
4244
Robert Carr695d5282018-12-18 15:27:58 -08004245void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004246{
Robert Carr2e102c92018-10-23 12:11:15 -07004247 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004248 // If a layer has a parent, we allow it to out-live it's handle
4249 // with the idea that the parent holds a reference and will eventually
4250 // be cleaned up. However no one cleans up the top-level so we do so
4251 // here.
4252 if (layer->getParent() == nullptr) {
4253 mCurrentState.layersSortedByZ.remove(layer);
4254 }
4255 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004256 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004257}
4258
Mathias Agopianb60314a2012-04-10 22:09:54 -07004259// ---------------------------------------------------------------------------
4260
Andy McFadden13a082e2012-08-24 10:16:42 -07004261void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004262 const auto display = getDefaultDisplayDeviceLocked();
4263 if (!display) return;
4264
4265 const sp<IBinder> token = display->getDisplayToken().promote();
4266 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004267
Jesse Hall01e29052013-02-19 16:13:35 -08004268 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004269 Vector<ComposerState> state;
4270 Vector<DisplayState> displays;
4271 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004272 d.what = DisplayState::eDisplayProjectionChanged |
4273 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004274 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004275 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004276 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004277 d.frame.makeInvalid();
4278 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004279 d.width = 0;
4280 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004281 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004282 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004283
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004285
Dominik Laskowski83b88212018-12-11 13:34:06 -08004286 const nsecs_t vsyncPeriod = getVsyncPeriod();
4287 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004288
Brian Andersond0010582017-03-07 13:20:31 -08004289 // Use phase of 0 since phase is not known.
4290 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004291 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004292 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004293}
4294
4295void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004296 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004297 postMessageAsync(
4298 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004299}
4300
Dominik Laskowskie9774092018-12-11 10:04:24 -08004301void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 if (display->isVirtual()) {
4303 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304 return;
4305 }
4306
Dominik Laskowski075d3172018-05-24 15:50:06 -07004307 const auto displayId = display->getId();
4308 LOG_ALWAYS_FATAL_IF(!displayId);
4309
Dominik Laskowski34157762018-10-31 13:07:19 -07004310 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311
4312 int currentMode = display->getPowerMode();
4313 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004314 return;
4315 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 display->setPowerMode(mode);
4318
Lloyd Pique4dccc412018-01-22 17:21:36 -08004319 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004320 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004321 }
4322
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004324 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004327 if (mUseScheduler) {
4328 mScheduler->onScreenAcquired(mAppConnectionHandle);
4329 } else {
4330 mEventThread->onScreenAcquired();
4331 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004332 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004333 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004334
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004335 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004336 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004337 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004338
4339 struct sched_param param = {0};
4340 param.sched_priority = 1;
4341 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4342 ALOGW("Couldn't set SCHED_FIFO on display on");
4343 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004344 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004345 // Turn off the display
4346 struct sched_param param = {0};
4347 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4348 ALOGW("Couldn't set SCHED_OTHER on display off");
4349 }
4350
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004351 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004352 if (mUseScheduler) {
4353 mScheduler->disableHardwareVsync(true);
4354 } else {
4355 disableHardwareVsync(true); // also cancels any in-progress resync
4356 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004357 if (mUseScheduler) {
4358 mScheduler->onScreenReleased(mAppConnectionHandle);
4359 } else {
4360 mEventThread->onScreenReleased();
4361 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004362 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004363
Dominik Laskowski075d3172018-05-24 15:50:06 -07004364 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004365 mVisibleRegionsDirty = true;
4366 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004367 } else if (mode == HWC_POWER_MODE_DOZE ||
4368 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004369 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004370 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004372 if (mUseScheduler) {
4373 mScheduler->onScreenAcquired(mAppConnectionHandle);
4374 } else {
4375 mEventThread->onScreenAcquired();
4376 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004377 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004378 }
4379 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4380 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004382 if (mUseScheduler) {
4383 mScheduler->disableHardwareVsync(true);
4384 } else {
4385 disableHardwareVsync(true); // also cancels any in-progress resync
4386 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004387 if (mUseScheduler) {
4388 mScheduler->onScreenReleased(mAppConnectionHandle);
4389 } else {
4390 mEventThread->onScreenReleased();
4391 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004392 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004393 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004394 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004395 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004396 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004397 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004398
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004399 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004400 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004401 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004402 // Update refresh rate stats.
4403 mRefreshRateStats->setPowerMode(mode);
4404 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004405 }
4406
Dominik Laskowski34157762018-10-31 13:07:19 -07004407 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004408}
4409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004411 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004412 const auto display = getDisplayDevice(displayToken);
4413 if (!display) {
4414 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4415 displayToken.get());
4416 } else if (display->isVirtual()) {
4417 ALOGW("Attempt to set power mode %d for virtual display", mode);
4418 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004419 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004420 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004422}
4423
4424// ---------------------------------------------------------------------------
4425
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4427 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004429
Mathias Agopianbd115332013-04-18 16:41:04 -07004430 IPCThreadState* ipc = IPCThreadState::self();
4431 const int pid = ipc->getCallingPid();
4432 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004433
Mathias Agopianbd115332013-04-18 16:41:04 -07004434 if ((uid != AID_SHELL) &&
4435 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4437 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004439 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004440 // (this would indicate SF is stuck, but we want to be able to
4441 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004442 status_t err = mStateLock.timedLock(s2ns(1));
4443 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004444 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result,
4446 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4447 "(no locks held)\n",
4448 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004449 }
4450
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004452
Dominik Laskowskic2867142019-01-21 11:33:38 -08004453 static const std::unordered_map<std::string, Dumper> dumpers = {
4454 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4455 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4456 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4457 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4458 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4459 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4460 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4461 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4462 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4463 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4464 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4465 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4466 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004467 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004468 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4469 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004472
Dominik Laskowskic2867142019-01-21 11:33:38 -08004473 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4474 (it->second)(args, asProto, result);
4475 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004476 if (asProto) {
4477 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4478 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4479 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004481 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004482 }
4483
Mathias Agopian9795c422009-08-26 16:36:26 -07004484 if (locked) {
4485 mStateLock.unlock();
4486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004489 return NO_ERROR;
4490}
4491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 mCurrentState.traverseInZOrder(
4494 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004495}
4496
Dominik Laskowskic2867142019-01-21 11:33:38 -08004497void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004498 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004499
Dominik Laskowskic2867142019-01-21 11:33:38 -08004500 if (args.size() > 1) {
4501 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004502 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004503 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004504 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004505 }
Robert Carr2047fae2016-11-28 14:09:09 -08004506 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004507 } else {
4508 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509 }
4510}
4511
Dominik Laskowskic2867142019-01-21 11:33:38 -08004512void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004513 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004514 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004515 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004516 }
Robert Carr2047fae2016-11-28 14:09:09 -08004517 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004518
Svetoslavd85084b2014-03-20 10:28:31 -07004519 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004520}
4521
Dominik Laskowskic2867142019-01-21 11:33:38 -08004522void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4523 mTimeStats->parseArgs(asProto, args, result);
4524}
4525
Jamie Gennis6547ff42013-07-16 20:12:42 -07004526// This should only be called from the main thread. Otherwise it would need
4527// the lock and should use mCurrentState rather than mDrawingState.
4528void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004530 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004531 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004532
4533 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4534}
4535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004537 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004538
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004539 if (isLayerTripleBufferingDisabled())
4540 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4543 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4544 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4545 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4546 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4547 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004548 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004549}
4550
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004552 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004553 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004554 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004555 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004556
4557 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4558
4559 if (mUseScheduler) {
4560 mScheduler->dump(mAppConnectionHandle, result);
4561 } else {
4562 mEventThread->dump(result);
4563 }
4564}
4565
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4567 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004568 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4569 float bucketTimeSec = getBE().mFrameBuckets[b] / 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[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004573 }
David Sodman4a36e932017-11-07 14:29:47 -08004574 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004575 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004576 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4578 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004579}
4580
Dan Stozae77c7662016-05-13 11:37:28 -07004581void SurfaceFlinger::recordBufferingStats(const char* layerName,
4582 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004583 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4584 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004585 for (const auto& segment : history) {
4586 if (!segment.usedThirdBuffer) {
4587 stats.twoBufferTime += segment.totalTime;
4588 }
4589 if (segment.occupancyAverage < 1.0f) {
4590 stats.doubleBufferedTime += segment.totalTime;
4591 } else if (segment.occupancyAverage < 2.0f) {
4592 stats.tripleBufferedTime += segment.totalTime;
4593 }
4594 ++stats.numSegments;
4595 stats.totalTime += segment.totalTime;
4596 }
4597}
4598
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4600 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004601
4602 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4603 const size_t count = currentLayers.size();
4604 for (size_t i=0 ; i<count ; i++) {
4605 currentLayers[i]->dumpFrameEvents(result);
4606 }
4607}
4608
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004610 result.append("Buffering stats:\n");
4611 result.append(" [Layer name] <Active time> <Two buffer> "
4612 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004613 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004614 typedef std::tuple<std::string, float, float, float> BufferTuple;
4615 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004616 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004617 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004618 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004619 if (stats.numSegments == 0) {
4620 continue;
4621 }
4622 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4623 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4624 stats.totalTime;
4625 float doubleBufferRatio = static_cast<float>(
4626 stats.doubleBufferedTime) / stats.totalTime;
4627 float tripleBufferRatio = static_cast<float>(
4628 stats.tripleBufferedTime) / stats.totalTime;
4629 sorted.insert({activeTime, {name, twoBufferRatio,
4630 doubleBufferRatio, tripleBufferRatio}});
4631 }
4632 for (const auto& sortedPair : sorted) {
4633 float activeTime = sortedPair.first;
4634 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4636 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004637 }
4638 result.append("\n");
4639}
4640
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004642 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004643 const auto displayId = display->getId();
4644 if (!displayId) {
4645 continue;
4646 }
4647 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004648 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649 continue;
4650 }
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result,
4653 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4654 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004655 uint8_t port;
4656 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004657 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 result.append("no identification data\n");
4659 continue;
4660 }
4661
4662 if (!isEdid(data)) {
4663 result.append("unknown identification data: ");
4664 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004666 }
4667 result.append("\n");
4668 continue;
4669 }
4670
4671 const auto edid = parseEdid(data);
4672 if (!edid) {
4673 result.append("invalid EDID: ");
4674 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004676 }
4677 result.append("\n");
4678 continue;
4679 }
4680
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004682 result.append(edid->displayName.data(), edid->displayName.length());
4683 result.append("\"\n");
4684 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004685}
4686
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4688 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4689 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4690 StringAppendF(&result, "DisplayColorSetting: %s\n",
4691 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004692
4693 // TODO: print out if wide-color mode is active or not
4694
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004695 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004696 const auto displayId = display->getId();
4697 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004698 continue;
4699 }
4700
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004702 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004703 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004705 }
4706
Lloyd Pique32cbe282018-10-19 13:09:22 -07004707 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 StringAppendF(&result, " Current color mode: %s (%d)\n",
4709 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004710 }
4711 result.append("\n");
4712}
4713
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004715 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004716 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4717 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004718 continue;
4719 }
4720
Dominik Laskowski05275f12018-11-01 15:03:24 -07004721 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4723 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004724 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 compositionInfo.dump(result, nullptr);
4726 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004727 }
4728 }
David Sodman7e4ae112018-02-09 15:02:28 -08004729}
4730
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004731LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004732 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004733 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4734 const State& state = useDrawing ? mDrawingState : mCurrentState;
4735 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004736 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004737 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004738 });
4739
4740 return layersProto;
4741}
4742
Lloyd Pique32cbe282018-10-19 13:09:22 -07004743LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004745
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004746 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004747 resolution->set_w(displayDevice.getWidth());
4748 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004749
Lloyd Pique32cbe282018-10-19 13:09:22 -07004750 auto display = displayDevice.getCompositionDisplay();
4751 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004752
Lloyd Pique32cbe282018-10-19 13:09:22 -07004753 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4754 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4755 layersProto.set_global_transform(displayState.orientation);
4756
4757 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004759 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004761 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004762 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004763 }
4764 });
4765
4766 return layersProto;
4767}
4768
Dominik Laskowskic2867142019-01-21 11:33:38 -08004769void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4770 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004771 Colorizer colorizer(colorize);
4772
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773 // figure out if we're stuck somewhere
4774 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004775 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4777
4778 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004779 * Dump library configuration.
4780 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781
4782 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004783 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004784 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004785 appendSfConfigString(result);
4786 appendUiConfigString(result);
4787 appendGuiConfigString(result);
4788 result.append("\n");
4789
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004790 result.append("\nDisplay identification data:\n");
4791 dumpDisplayIdentificationData(result);
4792
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004793 result.append("\nWide-Color information:\n");
4794 dumpWideColorInfo(result);
4795
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004796 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004797 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004798 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004799 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004800 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004801
Andy McFadden41d67d72014-04-25 16:58:34 -07004802 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004803 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004804 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004805 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004806 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004807
Dan Stozab90cf072015-03-05 11:05:59 -08004808 dumpStaticScreenStats(result);
4809 result.append("\n");
4810
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004812
Dan Stozae77c7662016-05-13 11:37:28 -07004813 dumpBufferingStats(result);
4814
Andy McFadden4803b742012-09-24 19:07:20 -07004815 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816 * Dump the visible layer list
4817 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004818 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4820 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4821 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004823
Chia-I Wu2f884132018-09-13 15:17:58 -07004824 {
4825 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4826 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004828 result.append("\n");
4829 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
David Sodman7e4ae112018-02-09 15:02:28 -08004831 result.append("\nFrame-Composition information:\n");
4832 dumpFrameCompositionInfo(result);
4833 result.append("\n");
4834
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004836 * Dump Display state
4837 */
4838
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004840 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004841 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004844 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004845 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004846
4847 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848 * Dump SurfaceFlinger global state
4849 */
4850
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004851 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004852 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004853 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004855 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004856
Dominik Laskowski075d3172018-05-24 15:50:06 -07004857 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004858 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4859 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4861 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004862 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result,
4864 " transaction-flags : %08x\n"
4865 " gpu_to_cpu_unsupported : %d\n",
4866 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004867
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004868 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004869 displayId && getHwComposer().isConnected(*displayId)) {
4870 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result,
4872 " refresh-rate : %f fps\n"
4873 " x-dpi : %f\n"
4874 " y-dpi : %f\n",
4875 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4876 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004877 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004880
Dan Stozae22aec72016-08-01 13:20:59 -07004881 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004882 * Tracing state
4883 */
4884 mTracing.dump(result);
4885 result.append("\n");
4886
4887 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004888 * HWC layer minidump
4889 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004890 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 const auto displayId = display->getId();
4892 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004893 continue;
4894 }
4895
Yiwei Zhang5434a782018-12-05 18:06:32 -08004896 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004897 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004898 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004899 result.append("\n");
4900 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004901
4902 /*
4903 * Dump HWComposer state
4904 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004905 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004906 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004907 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004908 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004910 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911
4912 /*
4913 * Dump gralloc state
4914 */
4915 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4916 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004917
4918 /*
4919 * Dump VrFlinger state if in use.
4920 */
4921 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4922 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004923 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004924 result.append("\n");
4925 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004926
4927 /**
4928 * Scheduler dump state.
4929 */
4930 if (mUseScheduler) {
4931 result.append("\nScheduler state:\n");
4932 result.append(mScheduler->doDump() + "\n");
4933 result.append(mRefreshRateStats->doDump() + "\n");
4934 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935}
4936
Dominik Laskowski075d3172018-05-24 15:50:06 -07004937const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004938 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004940 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004941 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004942 }
4943 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944
Dominik Laskowski34157762018-10-31 13:07:19 -07004945 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004946 static const Vector<sp<Layer>> empty;
4947 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004948}
4949
Chia-I Wu28f320b2018-05-03 11:02:56 -07004950void SurfaceFlinger::updateColorMatrixLocked() {
4951 mat4 colorMatrix;
4952 if (mGlobalSaturationFactor != 1.0f) {
4953 // Rec.709 luma coefficients
4954 float3 luminance{0.213f, 0.715f, 0.072f};
4955 luminance *= 1.0f - mGlobalSaturationFactor;
4956 mat4 saturationMatrix = mat4(
4957 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4958 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4959 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4960 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4961 );
4962 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4963 } else {
4964 colorMatrix = mClientColorMatrix * mDaltonizer();
4965 }
4966
4967 if (mCurrentState.colorMatrix != colorMatrix) {
4968 mCurrentState.colorMatrix = colorMatrix;
4969 mCurrentState.colorMatrixChanged = true;
4970 setTransactionFlags(eTransactionNeeded);
4971 }
4972}
4973
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004974status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004975#pragma clang diagnostic push
4976#pragma clang diagnostic error "-Wswitch-enum"
4977 switch (static_cast<ISurfaceComposerTag>(code)) {
4978 // These methods should at minimum make sure that the client requested
4979 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004980 case BOOT_FINISHED:
4981 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004982 case CREATE_DISPLAY:
4983 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004984 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004985 case GET_ACTIVE_COLOR_MODE:
4986 case GET_ANIMATION_FRAME_STATS:
4987 case GET_HDR_CAPABILITIES:
4988 case SET_ACTIVE_CONFIG:
4989 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004990 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004991 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004992 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004993 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4994 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004995 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4996 IPCThreadState* ipc = IPCThreadState::self();
4997 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4998 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004999 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005000 }
Robert Carr1db73f62016-12-21 12:58:51 -08005001 return OK;
5002 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005003 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005004 IPCThreadState* ipc = IPCThreadState::self();
5005 const int pid = ipc->getCallingPid();
5006 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5008 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005009 return PERMISSION_DENIED;
5010 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005011 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005012 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013 // Used by apps to hook Choreographer to SurfaceFlinger.
5014 case CREATE_DISPLAY_EVENT_CONNECTION:
5015 // The following calls are currently used by clients that do not
5016 // request necessary permissions. However, they do not expose any secret
5017 // information, so it is OK to pass them.
5018 case AUTHENTICATE_SURFACE:
5019 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005020 case GET_PHYSICAL_DISPLAY_IDS:
5021 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005023 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024 case GET_DISPLAY_CONFIGS:
5025 case GET_DISPLAY_STATS:
5026 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5027 // Calling setTransactionState is safe, because you need to have been
5028 // granted a reference to Client* and Handle* to do anything with it.
5029 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005030 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005031 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005032 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005033 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005034 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005035 return OK;
5036 }
5037 case CAPTURE_LAYERS:
5038 case CAPTURE_SCREEN: {
5039 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005040 IPCThreadState* ipc = IPCThreadState::self();
5041 const int pid = ipc->getCallingPid();
5042 const int uid = ipc->getCallingUid();
5043 if ((uid != AID_GRAPHICS) &&
5044 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5045 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5046 return PERMISSION_DENIED;
5047 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048 return OK;
5049 }
5050 // The following codes are deprecated and should never be allowed to access SF.
5051 case CONNECT_DISPLAY_UNUSED:
5052 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5053 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5054 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005055 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005057
5058 // These codes are used for the IBinder protocol to either interrogate the recipient
5059 // side of the transaction for its canonical interface descriptor or to dump its state.
5060 // We let them pass by default.
5061 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5062 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5063 code == IBinder::SYSPROPS_TRANSACTION) {
5064 return OK;
5065 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005066 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005068 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005069 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5070 return OK;
5071 }
5072 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5073 return PERMISSION_DENIED;
5074#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005075}
5076
Ana Krulec13be8ad2018-08-21 02:43:56 +00005077status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5078 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005079 status_t credentialCheck = CheckTransactCodeCredentials(code);
5080 if (credentialCheck != OK) {
5081 return credentialCheck;
5082 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5085 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005086 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005087 IPCThreadState* ipc = IPCThreadState::self();
5088 const int uid = ipc->getCallingUid();
5089 if (CC_UNLIKELY(uid != AID_SYSTEM
5090 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005091 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005092 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005093 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 return PERMISSION_DENIED;
5095 }
5096 int n;
5097 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005098 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005099 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 return NO_ERROR;
5101 case 1002: // SHOW_UPDATES
5102 n = data.readInt32();
5103 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005104 invalidateHwcGeometry();
5105 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005106 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005107 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005108 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005109 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005111 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005112 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005113 setTransactionFlags(
5114 eTransactionNeeded|
5115 eDisplayTransactionNeeded|
5116 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005117 return NO_ERROR;
5118 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005119 case 1006:{ // send empty update
5120 signalRefresh();
5121 return NO_ERROR;
5122 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005123 case 1008: // toggle use of hw composer
5124 n = data.readInt32();
5125 mDebugDisableHWC = n ? 1 : 0;
5126 invalidateHwcGeometry();
5127 repaintEverything();
5128 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005129 case 1009: // toggle use of transform hint
5130 n = data.readInt32();
5131 mDebugDisableTransformHint = n ? 1 : 0;
5132 invalidateHwcGeometry();
5133 repaintEverything();
5134 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005135 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005136 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005137 reply->writeInt32(0);
5138 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005139 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005140 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005141 return NO_ERROR;
5142 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005143 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005144 if (!display) {
5145 return NAME_NOT_FOUND;
5146 }
5147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005148 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005149 return NO_ERROR;
5150 }
5151 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005152 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005153 // daltonize
5154 n = data.readInt32();
5155 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005156 case 1:
5157 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5158 break;
5159 case 2:
5160 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5161 break;
5162 case 3:
5163 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5164 break;
5165 default:
5166 mDaltonizer.setType(ColorBlindnessType::None);
5167 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 }
5169 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005170 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005171 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005173 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174
5175 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005177 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005180 // apply a color matrix
5181 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005183 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005184 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005185 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005186 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005187 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005188 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005189 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005192
5193 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5194 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005196 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5197 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5198 }
5199
Chia-I Wu28f320b2018-05-03 11:02:56 -07005200 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005201 return NO_ERROR;
5202 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005203 // This is an experimental interface
5204 // Needs to be shifted to proper binder interface when we productize
5205 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005206 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005207 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005208 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005209 return NO_ERROR;
5210 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005211 case 1017: {
5212 n = data.readInt32();
5213 mForceFullDamage = static_cast<bool>(n);
5214 return NO_ERROR;
5215 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005216 case 1018: { // Modify Choreographer's phase offset
5217 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005218 if (mUseScheduler) {
5219 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5220 } else {
5221 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5222 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005223 return NO_ERROR;
5224 }
5225 case 1019: { // Modify SurfaceFlinger's phase offset
5226 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005227 if (mUseScheduler) {
5228 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5229 } else {
5230 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5231 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005232 return NO_ERROR;
5233 }
Irvel468051e2016-06-13 16:44:44 -07005234 case 1020: { // Layer updates interceptor
5235 n = data.readInt32();
5236 if (n) {
5237 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005238 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005239 }
5240 else{
5241 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005242 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005243 }
5244 return NO_ERROR;
5245 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005246 case 1021: { // Disable HWC virtual displays
5247 n = data.readInt32();
5248 mUseHwcVirtualDisplays = !n;
5249 return NO_ERROR;
5250 }
Romain Guy0147a172017-06-01 13:53:56 -07005251 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005252 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005253 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005254
Chia-I Wu28f320b2018-05-03 11:02:56 -07005255 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005256 return NO_ERROR;
5257 }
Romain Guy54f154a2017-10-24 21:40:32 +01005258 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005259 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005260 invalidateHwcGeometry();
5261 repaintEverything();
5262 return NO_ERROR;
5263 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005264 // Deprecate, use 1030 to check whether the device is color managed.
5265 case 1024: {
5266 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005267 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005268 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005269 n = data.readInt32();
5270 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005271 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005272 mTracing.enable();
5273 doTracing("tracing.enable");
5274 reply->writeInt32(NO_ERROR);
5275 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005276 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005277 status_t err = mTracing.disable();
5278 reply->writeInt32(err);
5279 }
5280 return NO_ERROR;
5281 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005282 case 1026: { // Get layer tracing status
5283 reply->writeBool(mTracing.isEnabled());
5284 return NO_ERROR;
5285 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005286 // Is a DisplayColorSetting supported?
5287 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005288 const auto display = getDefaultDisplayDevice();
5289 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005291 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005292
5293 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5294 switch (setting) {
5295 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005296 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005297 break;
5298 case DisplayColorSetting::UNMANAGED:
5299 reply->writeBool(true);
5300 break;
5301 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005302 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005303 break;
5304 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005305 reply->writeBool(
5306 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005307 break;
5308 }
5309 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005310 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005311 // Is VrFlinger active?
5312 case 1028: {
5313 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005314 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005315 return NO_ERROR;
5316 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005317 // Is device color managed?
5318 case 1030: {
5319 reply->writeBool(useColorManagement);
5320 return NO_ERROR;
5321 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005322 // Override default composition data space
5323 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5324 // && adb shell stop zygote && adb shell start zygote
5325 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5326 // adb shell stop zygote && adb shell start zygote
5327 case 1031: {
5328 Mutex::Autolock _l(mStateLock);
5329 n = data.readInt32();
5330 if (n) {
5331 n = data.readInt32();
5332 if (n) {
5333 Dataspace dataspace = static_cast<Dataspace>(n);
5334 if (!validateCompositionDataspace(dataspace)) {
5335 return BAD_VALUE;
5336 }
5337 mDefaultCompositionDataspace = dataspace;
5338 }
5339 n = data.readInt32();
5340 if (n) {
5341 Dataspace dataspace = static_cast<Dataspace>(n);
5342 if (!validateCompositionDataspace(dataspace)) {
5343 return BAD_VALUE;
5344 }
5345 mWideColorGamutCompositionDataspace = dataspace;
5346 }
5347 } else {
5348 // restore composition data space.
5349 mDefaultCompositionDataspace = defaultCompositionDataspace;
5350 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5351 }
5352 return NO_ERROR;
5353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005354 }
5355 }
5356 return err;
5357}
5358
Steven Thomas6d8110b2017-08-31 18:24:21 -07005359void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005360 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005361 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005362}
5363
Ana Krulec7d1d6832018-12-27 11:10:09 -08005364void SurfaceFlinger::repaintEverythingForHWC() {
5365 mRepaintEverything = true;
5366 mEventQueue->invalidateForHWC();
5367}
5368
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5370class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005371public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5373 ~WindowDisconnector() {
5374 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005375 }
5376
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005377private:
5378 ANativeWindow* mWindow;
5379 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005380};
5381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005382status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005383 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5384 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005385 uint32_t reqWidth, uint32_t reqHeight,
5386 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005387 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005389
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005390 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005391
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005392 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5393
Chia-I Wu20261cb2018-08-23 12:55:44 -07005394 sp<DisplayDevice> display;
5395 {
5396 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005397
Chia-I Wu20261cb2018-08-23 12:55:44 -07005398 display = getDisplayDeviceLocked(displayToken);
5399 if (!display) return BAD_VALUE;
5400
Chia-I Wucb023152018-08-28 12:57:23 -07005401 // set the requested width/height to the logical display viewport size
5402 // by default
5403 if (reqWidth == 0 || reqHeight == 0) {
5404 reqWidth = uint32_t(display->getViewport().width());
5405 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005406 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005407 }
5408
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5410 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005411
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005412 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5413 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5415 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005416}
5417
5418status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005419 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5420 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005421 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005422 ATRACE_CALL();
5423
5424 class LayerRenderArea : public RenderArea {
5425 public:
Robert Carr578038f2018-03-09 12:25:24 -08005426 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005427 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5428 bool childrenOnly)
5429 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005430 mLayer(layer),
5431 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005432 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005433 mFlinger(flinger),
5434 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005435 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 Rect getBounds() const override {
5437 const Layer::State& layerState(mLayer->getDrawingState());
5438 return mLayer->getBufferSize(layerState);
5439 }
Marissa Wall61c58622018-07-18 10:12:20 -07005440 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005441 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005442 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005443 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005444 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005445 }
chaviwa76b2712017-09-20 12:02:26 -07005446 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005447 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005448 Rect getSourceCrop() const override {
5449 if (mCrop.isEmpty()) {
5450 return getBounds();
5451 } else {
5452 return mCrop;
5453 }
5454 }
Robert Carr578038f2018-03-09 12:25:24 -08005455 class ReparentForDrawing {
5456 public:
5457 const sp<Layer>& oldParent;
5458 const sp<Layer>& newParent;
5459
Vishnu Nair4351ad52019-02-11 14:13:02 -08005460 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5461 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005462 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005463 // Compute and cache the bounds for the new parent layer.
5464 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005465 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005466 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005467 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005468 };
5469
5470 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005471 const Rect sourceCrop = getSourceCrop();
5472 // no need to check rotation because there is none
5473 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5474 sourceCrop.height() != getReqHeight();
5475
Robert Carr578038f2018-03-09 12:25:24 -08005476 if (!mChildrenOnly) {
5477 mTransform = mLayer->getTransform().inverse();
5478 drawLayers();
5479 } else {
5480 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005481 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005482 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5483 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005484
Vishnu Nair4351ad52019-02-11 14:13:02 -08005485 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005486 drawLayers();
5487 }
5488 }
chaviwa76b2712017-09-20 12:02:26 -07005489
chaviwa76b2712017-09-20 12:02:26 -07005490 private:
chaviw7206d492017-11-10 16:16:12 -08005491 const sp<Layer> mLayer;
5492 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005493
5494 // In the "childrenOnly" case we reparent the children to a screenshot
5495 // layer which has no properties set and which does not draw.
5496 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005497 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005498 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005499
5500 SurfaceFlinger* mFlinger;
5501 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005502 };
5503
5504 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5505 auto parent = layerHandle->owner.promote();
5506
Robert Carr2e102c92018-10-23 12:11:15 -07005507 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005508 ALOGE("captureLayers called with a removed parent");
5509 return NAME_NOT_FOUND;
5510 }
5511
Robert Carr578038f2018-03-09 12:25:24 -08005512 const int uid = IPCThreadState::self()->getCallingUid();
5513 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005514 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005515 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5516 return PERMISSION_DENIED;
5517 }
5518
chaviw7206d492017-11-10 16:16:12 -08005519 Rect crop(sourceCrop);
5520 if (sourceCrop.width() <= 0) {
5521 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005522 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005523 }
5524
5525 if (sourceCrop.height() <= 0) {
5526 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005527 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005528 }
5529
5530 int32_t reqWidth = crop.width() * frameScale;
5531 int32_t reqHeight = crop.height() * frameScale;
5532
Chia-I Wu20261cb2018-08-23 12:55:44 -07005533 // really small crop or frameScale
5534 if (reqWidth <= 0) {
5535 reqWidth = 1;
5536 }
5537 if (reqHeight <= 0) {
5538 reqHeight = 1;
5539 }
5540
Peiyong Lin0e003c92018-09-17 11:09:51 -07005541 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005542
Robert Carr578038f2018-03-09 12:25:24 -08005543 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005544 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5545 if (!layer->isVisible()) {
5546 return;
Robert Carr578038f2018-03-09 12:25:24 -08005547 } else if (childrenOnly && layer == parent.get()) {
5548 return;
chaviwa76b2712017-09-20 12:02:26 -07005549 }
5550 visitor(layer);
5551 });
5552 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005553 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005554}
5555
5556status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5557 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005558 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005559 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005560 bool useIdentityTransform) {
5561 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005562
Peiyong Lin0e003c92018-09-17 11:09:51 -07005563 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005564 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5565 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005566 *outBuffer =
5567 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5568 static_cast<android_pixel_format>(reqPixelFormat), 1,
5569 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005570
5571 // This mutex protects syncFd and captureResult for communication of the return values from the
5572 // main thread back to this Binder thread
5573 std::mutex captureMutex;
5574 std::condition_variable captureCondition;
5575 std::unique_lock<std::mutex> captureLock(captureMutex);
5576 int syncFd = -1;
5577 std::optional<status_t> captureResult;
5578
Robert Carr03480e22018-01-04 16:02:06 -08005579 const int uid = IPCThreadState::self()->getCallingUid();
5580 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5581
Dominik Laskowski8c001672018-05-30 16:52:06 -07005582 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 // If there is a refresh pending, bug out early and tell the binder thread to try again
5584 // after the refresh.
5585 if (mRefreshPending) {
5586 ATRACE_NAME("Skipping screenshot for now");
5587 std::unique_lock<std::mutex> captureLock(captureMutex);
5588 captureResult = std::make_optional<status_t>(EAGAIN);
5589 captureCondition.notify_one();
5590 return;
5591 }
5592
5593 status_t result = NO_ERROR;
5594 int fd = -1;
5595 {
5596 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005597 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005598 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5599 useIdentityTransform, forSystem, &fd);
5600 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 }
5602
5603 {
5604 std::unique_lock<std::mutex> captureLock(captureMutex);
5605 syncFd = fd;
5606 captureResult = std::make_optional<status_t>(result);
5607 captureCondition.notify_one();
5608 }
5609 });
5610
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005611 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005613 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614 while (*captureResult == EAGAIN) {
5615 captureResult.reset();
5616 result = postMessageAsync(message);
5617 if (result != NO_ERROR) {
5618 return result;
5619 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005620 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005621 }
5622 result = *captureResult;
5623 }
5624
5625 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005626 sync_wait(syncFd, -1);
5627 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005629
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005630 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005631}
5632
chaviwa76b2712017-09-20 12:02:26 -07005633void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005634 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005635 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5636 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005638
chaviwa76b2712017-09-20 12:02:26 -07005639 const auto reqWidth = renderArea.getReqWidth();
5640 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005641 const auto sourceCrop = renderArea.getSourceCrop();
5642 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005643
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005644 renderengine::DisplaySettings clientCompositionDisplay;
5645 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005646
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005647 // assume that bounds are never offset, and that they are the same as the
5648 // buffer bounds.
5649 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5650 ui::Transform transform = renderArea.getTransform();
5651 mat4 m;
5652 m[0][0] = transform[0][0];
5653 m[0][1] = transform[0][1];
5654 m[0][3] = transform[0][2];
5655 m[1][0] = transform[1][0];
5656 m[1][1] = transform[1][1];
5657 m[1][3] = transform[1][2];
5658 m[3][0] = transform[2][0];
5659 m[3][1] = transform[2][1];
5660 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005661
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005662 clientCompositionDisplay.globalTransform = m;
5663 mat4 rotMatrix;
5664 // Displacement for repositioning the clipping rectangle after rotating it
5665 // with the rotation hint.
5666 int displacementX = 0;
5667 int displacementY = 0;
5668 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5669 switch (rotation) {
5670 case ui::Transform::ROT_90:
5671 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5672 displacementX = reqWidth;
5673 break;
5674 case ui::Transform::ROT_180:
5675 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5676 displacementX = reqWidth;
5677 displacementY = reqHeight;
5678 break;
5679 case ui::Transform::ROT_270:
5680 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5681 displacementY = reqHeight;
5682 break;
5683 default:
5684 break;
5685 }
5686 // We need to transform the clipping window into the right spot.
5687 // First, rotate the clipping rectangle by the rotation hint to get the
5688 // right orientation
5689 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5690 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5691 const vec4 rotClipTL = rotMatrix * clipTL;
5692 const vec4 rotClipBR = rotMatrix * clipBR;
5693 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5694 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5695 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5696 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5697
5698 // Now reposition the clipping rectangle with the displacement vector
5699 // computed above.
5700 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5701
5702 clientCompositionDisplay.clip =
5703 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5704 newClipRight + displacementX, newClipBottom + displacementY);
5705
5706 // We need to perform the same transformation in layer space, so propagate
5707 // it to the global transform.
5708 mat4 clipTransform = displacementMat * rotMatrix;
5709 clientCompositionDisplay.globalTransform *= clipTransform;
5710 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5711 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005712
chaviw50da5042018-04-09 13:49:37 -07005713 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005714
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005715 renderengine::LayerSettings fillLayer;
5716 fillLayer.source.buffer.buffer = nullptr;
5717 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5718 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5719 fillLayer.alpha = half(alpha);
5720 clientCompositionLayers.push_back(fillLayer);
5721
5722 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005723 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005724 renderengine::LayerSettings layerSettings;
5725 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5726 layerSettings);
5727 if (prepared) {
5728 clientCompositionLayers.push_back(layerSettings);
5729 }
chaviwa76b2712017-09-20 12:02:26 -07005730 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005731
5732 clientCompositionDisplay.clearRegion = clearRegion;
5733 base::unique_fd drawFence;
5734 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5735 &drawFence);
5736
5737 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005738}
5739
chaviwa76b2712017-09-20 12:02:26 -07005740status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5741 TraverseLayersFunction traverseLayers,
5742 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005743 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005744 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005745 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005746 ATRACE_CALL();
5747
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005748 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005749
5750 traverseLayers([&](Layer* layer) {
5751 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5752 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005753
Robert Carr03480e22018-01-04 16:02:06 -08005754 // We allow the system server to take screenshots of secure layers for
5755 // use in situations like the Screen-rotation animation and place
5756 // the impetus on WindowManager to not persist them.
5757 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005758 ALOGW("FB is protected: PERMISSION_DENIED");
5759 return PERMISSION_DENIED;
5760 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005761 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005762 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005763}
5764
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005765// ---------------------------------------------------------------------------
5766
Dan Stoza412903f2017-04-27 13:42:17 -07005767void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5768 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005769}
5770
Dan Stoza412903f2017-04-27 13:42:17 -07005771void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5772 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005773}
5774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005775void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005776 const LayerVector::Visitor& visitor) {
5777 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005778 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005779 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005780 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005781 continue;
5782 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005783 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005784 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005785 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005786 return;
5787 }
chaviwa76b2712017-09-20 12:02:26 -07005788 if (!layer->isVisible()) {
5789 return;
5790 }
5791 visitor(layer);
5792 });
5793 }
5794}
5795
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005796}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005797
Lloyd Pique074e8122018-07-26 12:57:23 -07005798
Mathias Agopian3f844832013-08-07 21:24:32 -07005799#if defined(__gl_h_)
5800#error "don't include gl/gl.h in this file"
5801#endif
5802
5803#if defined(__gl2_h_)
5804#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005805#endif