blob: c1bc4da9b77af9d8e07696facdf5eacb7a2f1030 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mouri79108df2019-02-04 19:33:44 +000017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800123using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700124using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700125using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800126using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700127using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700128using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900129
Steven Thomasb02664d2017-07-26 18:48:28 -0700130namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700131
132#pragma clang diagnostic push
133#pragma clang diagnostic error "-Wswitch-enum"
134
135bool isWideColorMode(const ColorMode colorMode) {
136 switch (colorMode) {
137 case ColorMode::DISPLAY_P3:
138 case ColorMode::ADOBE_RGB:
139 case ColorMode::DCI_P3:
140 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700141 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700142 case ColorMode::BT2100_PQ:
143 case ColorMode::BT2100_HLG:
144 return true;
145 case ColorMode::NATIVE:
146 case ColorMode::STANDARD_BT601_625:
147 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
148 case ColorMode::STANDARD_BT601_525:
149 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
150 case ColorMode::STANDARD_BT709:
151 case ColorMode::SRGB:
152 return false;
153 }
154 return false;
155}
156
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700157ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
158 switch (rotation) {
159 case ISurfaceComposer::eRotateNone:
160 return ui::Transform::ROT_0;
161 case ISurfaceComposer::eRotate90:
162 return ui::Transform::ROT_90;
163 case ISurfaceComposer::eRotate180:
164 return ui::Transform::ROT_180;
165 case ISurfaceComposer::eRotate270:
166 return ui::Transform::ROT_270;
167 }
168 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
169 return ui::Transform::ROT_0;
170}
171
Peiyong Linfca547f2018-07-09 13:03:33 -0700172#pragma clang diagnostic pop
173
Steven Thomasb02664d2017-07-26 18:48:28 -0700174class ConditionalLock {
175public:
176 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
177 if (lock) {
178 mMutex.lock();
179 }
180 }
181 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
182private:
183 Mutex& mMutex;
184 bool mLocked;
185};
Peiyong Linfca547f2018-07-09 13:03:33 -0700186
Peiyong Lin9d846a52018-11-05 13:18:20 -0800187// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
188bool validateCompositionDataspace(Dataspace dataspace) {
189 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
190}
191
Steven Thomasb02664d2017-07-26 18:48:28 -0700192} // namespace anonymous
193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194// ---------------------------------------------------------------------------
195
Mathias Agopian99b49842011-06-27 16:05:52 -0700196const String16 sHardwareTest("android.permission.HARDWARE_TEST");
197const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
198const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
199const String16 sDump("android.permission.DUMP");
200
Daniel Solomon42d04562019-01-20 21:03:19 -0800201constexpr float kSrgbRedX = 0.4123f;
202constexpr float kSrgbRedY = 0.2126f;
203constexpr float kSrgbRedZ = 0.0193f;
204constexpr float kSrgbGreenX = 0.3576f;
205constexpr float kSrgbGreenY = 0.7152f;
206constexpr float kSrgbGreenZ = 0.1192f;
207constexpr float kSrgbBlueX = 0.1805f;
208constexpr float kSrgbBlueY = 0.0722f;
209constexpr float kSrgbBlueZ = 0.9506f;
210constexpr float kSrgbWhiteX = 0.9505f;
211constexpr float kSrgbWhiteY = 1.0000f;
212constexpr float kSrgbWhiteZ = 1.0891f;
213
Mathias Agopian99b49842011-06-27 16:05:52 -0700214// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700215int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700216bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800218bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800219bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800220int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600221bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700222int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700223bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700224bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700225Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
226ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
227Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
228ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700229
Kalle Raitaa099a242017-01-11 11:17:29 -0800230std::string getHwcServiceName() {
231 char value[PROPERTY_VALUE_MAX] = {};
232 property_get("debug.sf.hwc_service_name", value, "default");
233 ALOGI("Using HWComposer service: '%s'", value);
234 return std::string(value);
235}
236
237bool useTrebleTestingOverride() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.treble_testing_override", value, "false");
240 ALOGI("Treble testing override: '%s'", value);
241 return std::string(value) == "true";
242}
243
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
245 switch(displayColorSetting) {
246 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800248 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Enhanced");
252 default:
253 return std::string("Unknown ") +
254 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256}
257
David Sodmanbc815282017-11-05 18:57:52 -0800258SurfaceFlingerBE::SurfaceFlingerBE()
259 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800260 mFrameBuckets(),
261 mTotalTime(0),
262 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800263 mComposerSequenceId(0) {
264}
265
Lloyd Pique90c115d2018-09-18 21:39:42 -0700266SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
267 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800268 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700269 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700270 mTransactionPending(false),
271 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700272 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700273 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800275 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800277 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800278 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800279 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700281 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700282 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700283 mDebugInTransaction(0),
284 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700285 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800286 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700287 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700288 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800289 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800290 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800291 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700292 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700293 mMainThreadId(std::this_thread::get_id()),
294 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800295
Lloyd Pique90c115d2018-09-18 21:39:42 -0700296SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
297 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800307
Steven Thomas050b2c82017-03-06 11:45:16 -0800308 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 mDefaultCompositionDataspace =
318 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
319 mWideColorGamutCompositionDataspace =
320 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
321 defaultCompositionDataspace = mDefaultCompositionDataspace;
322 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
323 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
324 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
325 wideColorGamutCompositionPixelFormat =
326 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700327
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
331 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
332 switch (tmpPrimaryDisplayOrientation) {
333 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
Daniel Solomon42d04562019-01-20 21:03:19 -0800352 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
353 if (surfaceFlingerConfigsServiceV1_2) {
354 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
355 [&](auto tmpPrimaries) {
356 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
357 });
358 } else {
359 initDefaultDisplayNativePrimaries();
360 }
361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362 // debugging stuff...
363 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364
Mathias Agopianb4b17302013-03-20 18:36:41 -0700365 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700366 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 property_get("debug.sf.showupdates", value, "0");
369 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000372
373 // DDMS debugging deprecated (b/120782499)
374 property_get("debug.sf.ddms", value, "0");
375 int debugDdms = atoi(value);
376 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700377
378 property_get("debug.sf.disable_backpressure", value, "0");
379 mPropagateBackpressure = !atoi(value);
380 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700381
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800382 property_get("debug.sf.enable_hwc_vds", value, "0");
383 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800384 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800385
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800386 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800387 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800388 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700389
Yiwei Zhang243b3782018-05-15 17:40:04 -0700390 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700391 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
392 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
393
Ana Krulec98b5b242018-08-10 15:03:23 -0700394 property_get("debug.sf.use_scheduler", value, "0");
395 mUseScheduler = atoi(value);
396
Ana Krulec757f63a2019-01-25 10:46:18 -0800397 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
398 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415void SurfaceFlinger::onFirstRef()
416{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420SurfaceFlinger::~SurfaceFlinger()
421{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Robert Carr1db73f62016-12-21 12:58:51 -0800435static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700436 status_t err = client->initCheck();
437 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return nullptr;
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
444 return initClient(new Client(this));
445}
446
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700447sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
448 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449{
450 class DisplayToken : public BBinder {
451 sp<SurfaceFlinger> flinger;
452 virtual ~DisplayToken() {
453 // no more references, this display must be terminated
454 Mutex::Autolock _l(flinger->mStateLock);
455 flinger->mCurrentState.displays.removeItem(this);
456 flinger->setTransactionFlags(eDisplayTransactionNeeded);
457 }
458 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700459 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 : flinger(flinger) {
461 }
462 };
463
464 sp<BBinder> token = new DisplayToken(this);
465
466 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 // Display ID is assigned when virtual display is allocated by HWC.
468 DisplayDeviceState state;
469 state.isSecure = secure;
470 state.displayName = displayName;
471 mCurrentState.displays.add(token, state);
472 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 return token;
474}
475
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700476void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 Mutex::Autolock _l(mStateLock);
478
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
480 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 return;
483 }
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
486 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 ALOGE("destroyDisplay called for non-virtual display");
488 return;
489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 mInterceptor->saveDisplayDeletion(state.sequenceId);
491 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 setTransactionFlags(eDisplayTransactionNeeded);
493}
494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
496 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 const auto internalDisplayId = getInternalDisplayIdLocked();
499 if (!internalDisplayId) {
500 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 }
502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503 std::vector<PhysicalDisplayId> displayIds;
504 displayIds.reserve(mPhysicalDisplayTokens.size());
505 displayIds.push_back(internalDisplayId->value);
506
507 for (const auto& [id, token] : mPhysicalDisplayTokens) {
508 if (id != *internalDisplayId) {
509 displayIds.push_back(id.value);
510 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 return displayIds;
514}
515
516sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
517 Mutex::Autolock lock(mStateLock);
518 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519}
520
Ady Abraham37965d42018-11-01 13:43:32 -0700521status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
522 if (!outGetColorManagement) {
523 return BAD_VALUE;
524 }
525 *outGetColorManagement = useColorManagement;
526 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700527}
528
Lloyd Pique441d5042018-10-18 16:49:51 -0700529HWComposer& SurfaceFlinger::getHwComposer() const {
530 return mCompositionEngine->getHwComposer();
531}
532
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700533renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
534 return mCompositionEngine->getRenderEngine();
535}
536
Lloyd Pique70d91362018-10-18 16:02:55 -0700537compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
538 return *mCompositionEngine.get();
539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541void SurfaceFlinger::bootFinished()
542{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700543 if (mStartPropertySetThread->join() != NO_ERROR) {
544 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 const nsecs_t now = systemTime();
547 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000548 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
550 // wait patiently for the window manager death
551 const String16 name("window");
552 sp<IBinder> window(defaultServiceManager()->getService(name));
553 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700554 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 }
Robert Carr720e5062018-07-30 17:45:14 -0700556 sp<IBinder> input(defaultServiceManager()->getService(
557 String16("inputflinger")));
558 if (input == nullptr) {
559 ALOGE("Failed to link to input service");
560 } else {
561 mInputFlinger = interface_cast<IInputFlinger>(input);
562 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563
Steven Thomas050b2c82017-03-06 11:45:16 -0800564 if (mVrFlinger) {
565 mVrFlinger->OnBootFinished();
566 }
567
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700569 // formerly we would just kill the process, but we now ask it to exit so it
570 // can choose where to stop the animation.
571 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700572
573 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
574 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
575 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700576
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800577 postMessageAsync(new LambdaMessage([this] {
578 readPersistentProperties();
579 mBootStage = BootStage::FINISHED;
580 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581}
582
Dan Stoza436ccf32018-06-21 12:10:12 -0700583uint32_t SurfaceFlinger::getNewTexture() {
584 {
585 std::lock_guard lock(mTexturePoolMutex);
586 if (!mTexturePool.empty()) {
587 uint32_t name = mTexturePool.back();
588 mTexturePool.pop_back();
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
590 return name;
591 }
592
593 // The pool was too small, so increase it for the future
594 ++mTexturePoolSize;
595 }
596
597 // The pool was empty, so we need to get a new texture name directly using a
598 // blocking call to the main thread
599 uint32_t name = 0;
600 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
601 return name;
602}
603
Mathias Agopian3f844832013-08-07 21:24:32 -0700604void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700605 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Ana Krulec757f63a2019-01-25 10:46:18 -0800614 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617
Dominik Laskowski83b88212018-12-11 13:34:06 -0800618 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800622 mScheduler = getFactory().createScheduler(
623 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
624
Ana Krulec757f63a2019-01-25 10:46:18 -0800625 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
626 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
627 mPhaseOffsets->setRefreshRateType(
628 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800631 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800632 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 impl::EventThread::InterceptVSyncsCallback());
634 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800635 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800636 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mInterceptor->saveVSyncEvent(timestamp);
638 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800639
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700641 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
642 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 } else {
644 mEventThreadSource =
645 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800646 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mEventThread =
648 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700649 impl::EventThread::InterceptVSyncsCallback(),
650 "appEventThread");
651 mSfEventThreadSource =
652 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800653 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700654
655 mSFEventThread =
656 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 [this](nsecs_t timestamp) {
658 mInterceptor->saveVSyncEvent(timestamp);
659 },
660 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800661 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700662 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700666 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700667 renderEngineFeature |= (useColorManagement ?
668 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700669 renderEngineFeature |= (useContextPriority ?
670 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700671
672 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700675 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800713 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700724
725 const bool presentFenceReliable =
726 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
727 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728
729 if (mStartPropertySetThread->Start() != NO_ERROR) {
730 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732
Ana Krulec7d1d6832018-12-27 11:10:09 -0800733 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800734 mScheduler->setExpiredIdleTimerCallback([this]() {
735 mPhaseOffsets->setRefreshRateType(
736 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
737 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
738 mVsyncModulator.setPhaseOffsets(early, gl, late);
739 setRefreshRateTo(60.f /* fps */);
740 });
741 mScheduler->setResetIdleTimerCallback([this]() {
742 mPhaseOffsets->setRefreshRateType(
743 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
744 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
745 mVsyncModulator.setPhaseOffsets(early, gl, late);
746 setRefreshRateTo(90.f /* fps */);
747 });
Alec Mourifb571ea2019-01-24 18:42:10 -0800748 mRefreshRateStats =
749 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
750 *display->getId()),
751 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800752 }
753
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700755}
756
Romain Guy11d63f42017-07-20 12:47:14 -0700757void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700758 Mutex::Autolock _l(mStateLock);
759
Romain Guy11d63f42017-07-20 12:47:14 -0700760 char value[PROPERTY_VALUE_MAX];
761
762 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800763 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700764 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800765 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100766
767 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700768 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700769}
770
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800772 // Start boot animation service by setting a property mailbox
773 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700774 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800775 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 if (mStartPropertySetThread->join() != NO_ERROR) {
777 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800778 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700779}
780
Mathias Agopian875d8e12013-06-07 15:35:48 -0700781size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700782 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700783}
784
Mathias Agopian875d8e12013-06-07 15:35:48 -0700785size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700786 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700787}
788
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800789// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800790
Jamie Gennis582270d2011-08-17 18:19:00 -0700791bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800792 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800793 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800794 return authenticateSurfaceTextureLocked(bufferProducer);
795}
796
797bool SurfaceFlinger::authenticateSurfaceTextureLocked(
798 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800799 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800800 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800801}
802
Brian Anderson6b376712017-04-04 10:51:39 -0700803status_t SurfaceFlinger::getSupportedFrameTimestamps(
804 std::vector<FrameEvent>* outSupported) const {
805 *outSupported = {
806 FrameEvent::REQUESTED_PRESENT,
807 FrameEvent::ACQUIRE,
808 FrameEvent::LATCH,
809 FrameEvent::FIRST_REFRESH_START,
810 FrameEvent::LAST_REFRESH_START,
811 FrameEvent::GPU_COMPOSITION_DONE,
812 FrameEvent::DEQUEUE_READY,
813 FrameEvent::RELEASE,
814 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 ConditionalLock _l(mStateLock,
816 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700817 if (!getHwComposer().hasCapability(
818 HWC2::Capability::PresentFenceIsNotReliable)) {
819 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
820 }
821 return NO_ERROR;
822}
823
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
825 Vector<DisplayInfo>* configs) {
826 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return BAD_VALUE;
828 }
829
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800830 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
831
832 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700833 if (!displayId) {
834 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 // TODO: Not sure if display density should handled by SF any longer
838 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700841 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700843 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 }
845 return density;
846 }
847 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700850 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851 return getDensityFromProperty("ro.sf.lcd_density"); }
852 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 DisplayInfo info = DisplayInfo();
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 float xdpi = hwConfig->getDpiX();
860 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862 info.w = hwConfig->getWidth();
863 info.h = hwConfig->getHeight();
864 // Default display viewport to display width and height
865 info.viewportW = info.w;
866 info.viewportH = info.h;
867
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800868 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 // The density of the device is provided by a build property
870 float density = Density::getBuildDensity() / 160.0f;
871 if (density == 0) {
872 // the build doesn't provide a density -- this is wrong!
873 // use xdpi instead
874 ALOGE("ro.sf.lcd_density must be defined as a build property");
875 density = xdpi / 160.0f;
876 }
877 if (Density::getEmuDensity()) {
878 // if "qemu.sf.lcd_density" is specified, it overrides everything
879 xdpi = ydpi = density = Density::getEmuDensity();
880 density /= 160.0f;
881 }
882 info.density = density;
883
884 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 const auto display = getDefaultDisplayDeviceLocked();
886 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700887
888 // This is for screenrecord
889 const Rect viewport = display->getViewport();
890 if (viewport.isValid()) {
891 info.viewportW = uint32_t(viewport.getWidth());
892 info.viewportH = uint32_t(viewport.getHeight());
893 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 } else {
895 // TODO: where should this value come from?
896 static const int TV_DENSITY = 213;
897 info.density = TV_DENSITY / 160.0f;
898 info.orientation = 0;
899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 info.xdpi = xdpi;
902 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800904 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800918 info.presentationDeadline =
919 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700920
921 // All non-virtual displays are currently considered secure.
922 info.secure = true;
923
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800924 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700925 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800926 std::swap(info.w, info.h);
927 }
928
Michael Wright28f24d02016-07-12 13:30:53 -0700929 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700930 }
931
Dan Stoza7f7da322014-05-02 15:26:25 -0700932 return NO_ERROR;
933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
936 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return BAD_VALUE;
938 }
939
Ana Krulece588e312018-09-18 12:32:24 -0700940 if (mUseScheduler) {
941 mScheduler->getDisplayStatInfo(stats);
942 } else {
943 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
944 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
945 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700946 return NO_ERROR;
947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
950 const auto display = getDisplayDevice(displayToken);
951 if (!display) {
952 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800953 return BAD_VALUE;
954 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700958
Ana Krulec7d1d6832018-12-27 11:10:09 -0800959status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
960 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800961 postMessageAsync(new LambdaMessage(
962 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800963 return NO_ERROR;
964}
965
966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
967 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800968 postMessageSync(new LambdaMessage(
969 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 return NO_ERROR;
971}
972
973void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
974 Vector<DisplayInfo> configs;
975 getDisplayConfigs(displayToken, &configs);
976 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
977 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
978 return;
979 }
980
981 const auto display = getDisplayDevice(displayToken);
982 if (!display) {
983 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
984 displayToken.get());
985 return;
986 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988 ALOGW("Attempt to set active config %d for virtual display", mode);
989 return;
990 }
991 int currentDisplayPowerMode = display->getPowerMode();
992 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
993 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700994 return;
995 }
996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800999 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001000 return;
1001 }
Ana Krulecb43429d2019-01-09 14:28:51 -08001002 if (mUseScheduler) {
1003 mRefreshRateStats->setConfigMode(mode);
1004 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006 const auto displayId = display->getId();
1007 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001011
Ana Krulec7d1d6832018-12-27 11:10:09 -08001012 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001013 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001014}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1017 Vector<ColorMode>* outColorModes) {
1018 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001019 return BAD_VALUE;
1020 }
1021
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001024 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1025
1026 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1027 if (!displayId) {
1028 return NAME_NOT_FOUND;
1029 }
1030
Dominik Laskowski075d3172018-05-24 15:50:06 -07001031 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001032 }
Michael Wright28f24d02016-07-12 13:30:53 -07001033 outColorModes->clear();
1034 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1035
1036 return NO_ERROR;
1037}
1038
Daniel Solomon42d04562019-01-20 21:03:19 -08001039status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1040 ui::DisplayPrimaries &primaries) {
1041 if (!displayToken) {
1042 return BAD_VALUE;
1043 }
1044
1045 // Currently we only support this API for a single internal display.
1046 if (getInternalDisplayToken() != displayToken) {
1047 return BAD_VALUE;
1048 }
1049
1050 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1051 return NO_ERROR;
1052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1055 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001056 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001059}
1060
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001062 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 Vector<ColorMode> modes;
1064 getDisplayColorModes(displayToken, &modes);
1065 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1066 if (mode < ColorMode::NATIVE || !exists) {
1067 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1068 decodeColorMode(mode).c_str(), mode, displayToken.get());
1069 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001070 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 const auto display = getDisplayDevice(displayToken);
1072 if (!display) {
1073 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1074 decodeColorMode(mode).c_str(), mode, displayToken.get());
1075 } else if (display->isVirtual()) {
1076 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1077 decodeColorMode(mode).c_str(), mode);
1078 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001079 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1080 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081 }
1082 }));
1083
Michael Wright28f24d02016-07-12 13:30:53 -07001084 return NO_ERROR;
1085}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001086
Svetoslavd85084b2014-03-20 10:28:31 -07001087status_t SurfaceFlinger::clearAnimationFrameStats() {
1088 Mutex::Autolock _l(mStateLock);
1089 mAnimFrameTracker.clearStats();
1090 return NO_ERROR;
1091}
1092
1093status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1094 Mutex::Autolock _l(mStateLock);
1095 mAnimFrameTracker.getStats(outStats);
1096 return NO_ERROR;
1097}
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1100 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001101 Mutex::Autolock _l(mStateLock);
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const auto display = getDisplayDeviceLocked(displayToken);
1104 if (!display) {
1105 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001106 return BAD_VALUE;
1107 }
1108
Peiyong Linfb069302018-04-25 14:34:31 -07001109 // At this point the DisplayDeivce should already be set up,
1110 // meaning the luminance information is already queried from
1111 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001113 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1114 capabilities.getDesiredMaxLuminance(),
1115 capabilities.getDesiredMaxAverageLuminance(),
1116 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001117
1118 return NO_ERROR;
1119}
1120
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1122 ui::PixelFormat* outFormat,
1123 ui::Dataspace* outDataspace,
1124 uint8_t* outComponentMask) const {
1125 if (!outFormat || !outDataspace || !outComponentMask) {
1126 return BAD_VALUE;
1127 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001128 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001129 if (!display || !display->getId()) {
1130 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1131 return BAD_VALUE;
1132 }
1133 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1134 outDataspace, outComponentMask);
1135}
1136
Kevin DuBois74e53772018-11-19 10:52:38 -08001137status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1138 bool enable, uint8_t componentMask,
1139 uint64_t maxFrames) const {
1140 const auto display = getDisplayDevice(displayToken);
1141 if (!display || !display->getId()) {
1142 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1143 return BAD_VALUE;
1144 }
1145
1146 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1147 componentMask, maxFrames);
1148}
1149
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001150status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1151 uint64_t maxFrames, uint64_t timestamp,
1152 DisplayedFrameStats* outStats) const {
1153 const auto display = getDisplayDevice(displayToken);
1154 if (!display || !display->getId()) {
1155 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1156 return BAD_VALUE;
1157 }
1158
1159 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1160 outStats);
1161}
1162
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001163status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1164 if (!outSupported) {
1165 return BAD_VALUE;
1166 }
1167 *outSupported = getRenderEngine().supportsProtectedContent();
1168 return NO_ERROR;
1169}
1170
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001171status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1172 bool* outIsWideColorDisplay) const {
1173 if (!displayToken || !outIsWideColorDisplay) {
1174 return BAD_VALUE;
1175 }
1176 Mutex::Autolock _l(mStateLock);
1177 const auto display = getDisplayDeviceLocked(displayToken);
1178 if (!display) {
1179 return BAD_VALUE;
1180 }
1181 *outIsWideColorDisplay = display->hasWideColorGamut();
1182 return NO_ERROR;
1183}
1184
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001186 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001188
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 if (mInjectVSyncs == enable) {
1190 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001191 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001192
Dominik Laskowski83b88212018-12-11 13:34:06 -08001193 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001194
Ana Krulec98b5b242018-08-10 15:03:23 -07001195 // TODO(akrulec): Part of the Injector should be refactored, so that it
1196 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 if (enable) {
1198 ALOGV("VSync Injections enabled");
1199 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001200 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001201 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001202 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001203 impl::EventThread::InterceptVSyncsCallback(),
1204 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001205 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001206 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001207 } else {
1208 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001209 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001210 }
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001213 }));
1214
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215 return NO_ERROR;
1216}
1217
1218status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219 Mutex::Autolock _l(mStateLock);
1220
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001221 if (!mInjectVSyncs) {
1222 ALOGE("VSync Injections not enabled");
1223 return BAD_VALUE;
1224 }
1225 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1226 ALOGV("Injecting VSync inside SurfaceFlinger");
1227 mVSyncInjector->onInjectSyncEvent(when);
1228 }
1229 return NO_ERROR;
1230}
1231
Lloyd Pique755e3192018-01-31 16:46:15 -08001232status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1233 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001234 // Try to acquire a lock for 1s, fail gracefully
1235 const status_t err = mStateLock.timedLock(s2ns(1));
1236 const bool locked = (err == NO_ERROR);
1237 if (!locked) {
1238 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1239 return TIMED_OUT;
1240 }
1241
1242 outLayers->clear();
1243 mCurrentState.traverseInZOrder([&](Layer* layer) {
1244 outLayers->push_back(layer->getLayerDebugInfo());
1245 });
1246
1247 mStateLock.unlock();
1248 return NO_ERROR;
1249}
1250
Peiyong Linc6780972018-10-28 15:24:08 -07001251status_t SurfaceFlinger::getCompositionPreference(
1252 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1253 Dataspace* outWideColorGamutDataspace,
1254 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001255 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001256 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001257 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001258 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001259 return NO_ERROR;
1260}
1261
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001262// ----------------------------------------------------------------------------
1263
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001264sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1265 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001266 auto resyncCallback = makeResyncCallback([this] {
1267 Mutex::Autolock lock(mStateLock);
1268 return getVsyncPeriod();
1269 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270
Ana Krulec98b5b242018-08-10 15:03:23 -07001271 if (mUseScheduler) {
1272 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001273 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001274 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001275 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001276 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001277 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001278 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001279 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001280 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001281 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001283 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001284}
1285
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287
1288void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001289 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001290}
1291
1292void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001293 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001294}
1295
1296void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001297 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298}
1299
1300void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001301 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001302 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303}
1304
1305status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001306 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001307 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001308}
1309
1310status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001311 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001312 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001313 if (res == NO_ERROR) {
1314 msg->wait();
1315 }
1316 return res;
1317}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001318
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001319void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001320 do {
1321 waitForEvent();
1322 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001323}
1324
Dominik Laskowski83b88212018-12-11 13:34:06 -08001325nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001326 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1328 return 0;
1329 }
1330
1331 const auto config = getHwComposer().getActiveConfig(*displayId);
1332 return config ? config->getVsyncPeriod() : 0;
1333}
1334
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335void SurfaceFlinger::enableHardwareVsync() {
1336 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001338 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Dominik Laskowski83b88212018-12-11 13:34:06 -08001344void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 Mutex::Autolock _l(mHWVsyncLock);
1346
Jesse Hall948fe0c2013-10-14 12:56:09 -07001347 if (makeAvailable) {
1348 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001349 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1350 if (mUseScheduler) {
1351 mScheduler->makeHWSyncAvailable(true);
1352 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001354 // Hardware vsync is not currently available, so abort the resync
1355 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001356 return;
1357 }
1358
Dominik Laskowski83b88212018-12-11 13:34:06 -08001359 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001360 return;
1361 }
1362
Ana Krulece588e312018-09-18 12:32:24 -07001363 if (mUseScheduler) {
1364 mScheduler->setVsyncPeriod(period);
1365 } else {
1366 mPrimaryDispSync->reset();
1367 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368
Ana Krulece588e312018-09-18 12:32:24 -07001369 if (!mPrimaryHWVsyncEnabled) {
1370 mPrimaryDispSync->beginResync();
1371 mEventControlThread->setVsyncEnabled(true);
1372 mPrimaryHWVsyncEnabled = true;
1373 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001374 }
1375}
1376
Jesse Hall948fe0c2013-10-14 12:56:09 -07001377void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001378 Mutex::Autolock _l(mHWVsyncLock);
1379 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001380 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001381 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 mPrimaryHWVsyncEnabled = false;
1383 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001384 if (makeUnavailable) {
1385 mHWVsyncAvailable = false;
1386 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001387}
1388
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001390 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001391
Dan Stoza57164302017-05-08 14:03:54 -07001392 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001393 const nsecs_t last = lastResyncTime.exchange(now);
1394
1395 if (now - last > kIgnoreDelay) {
1396 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001397 }
1398}
1399
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001400void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1401 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001402 ATRACE_NAME("SF onVsync");
1403
Steven Thomas3cfac282017-02-06 12:29:30 -08001404 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 return;
1408 }
1409
Dominik Laskowski075d3172018-05-24 15:50:06 -07001410 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001411 return;
1412 }
1413
Dominik Laskowski075d3172018-05-24 15:50:06 -07001414 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001415 // For now, we don't do anything with external display vsyncs.
1416 return;
1417 }
1418
Ana Krulece588e312018-09-18 12:32:24 -07001419 if (mUseScheduler) {
1420 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001421 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001422 bool needsHwVsync = false;
1423 { // Scope for the lock
1424 Mutex::Autolock _l(mHWVsyncLock);
1425 if (mPrimaryHWVsyncEnabled) {
1426 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1427 }
1428 }
1429
1430 if (needsHwVsync) {
1431 enableHardwareVsync();
1432 } else {
1433 disableHardwareVsync(false);
1434 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001435 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001436}
1437
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001439 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1440 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001441}
1442
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001443// TODO(b/123715322): Fix thread safety.
1444void SurfaceFlinger::setRefreshRateTo(float newFps) NO_THREAD_SAFETY_ANALYSIS {
1445 const auto display = getDefaultDisplayDeviceLocked();
1446 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001447 return;
1448 }
1449 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1450 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1451 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1452 // refresh cycle.
1453
1454 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001455 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 if (currentVsyncPeriod == 0) {
1457 return;
1458 }
1459 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1460 // floating numbers.
1461 const float currentFps = 1e9 / currentVsyncPeriod;
1462 if (std::abs(currentFps - newFps) <= 1) {
1463 return;
1464 }
1465
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001466 auto configs = getHwComposer().getConfigs(*display->getId());
Ana Krulec7d1d6832018-12-27 11:10:09 -08001467 for (int i = 0; i < configs.size(); i++) {
1468 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1469 if (vsyncPeriod == 0) {
1470 continue;
1471 }
1472 const float fps = 1e9 / vsyncPeriod;
1473 // TODO(b/113612090): There should be a better way at determining which config
1474 // has the right refresh rate.
1475 if (std::abs(fps - newFps) <= 1) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001476 const sp<IBinder> token = display->getDisplayToken().promote();
1477 LOG_ALWAYS_FATAL_IF(token == nullptr);
1478
Ana Krulec7d1d6832018-12-27 11:10:09 -08001479 // This is posted in async function to avoid deadlock when getDisplayDevice
1480 // requires mStateLock.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001481 setActiveConfigAsync(token, i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001482 ATRACE_INT("FPS", newFps);
1483 }
1484 }
1485}
1486
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001487void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001488 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001489 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001490 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491
Lloyd Piqueba04e622017-12-14 17:11:26 -08001492 // Ignore events that do not have the right sequenceId.
1493 if (sequenceId != getBE().mComposerSequenceId) {
1494 return;
1495 }
1496
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 // Only lock if we're not on the main thread. This function is normally
1498 // called on a hwbinder thread, but for the primary display it's called on
1499 // the main thread with the state lock already held, so don't attempt to
1500 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001501 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001504
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001505 if (std::this_thread::get_id() == mMainThreadId) {
1506 // Process all pending hot plug events immediately if we are on the main thread.
1507 processDisplayHotplugEventsLocked();
1508 }
1509
Lloyd Piqueba04e622017-12-14 17:11:26 -08001510 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001511}
1512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001514 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001515 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001517 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001518 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001519}
1520
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001521void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001522 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001524 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001525 getHwComposer().setVsyncEnabled(*displayId,
1526 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1527 }
Mathias Agopian86303202012-07-24 22:46:10 -07001528}
1529
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001531void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001532 if (mUseScheduler) {
1533 mScheduler->disableHardwareVsync(true);
1534 } else {
1535 disableHardwareVsync(true);
1536 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001537 // Clear the drawing state so that the logic inside of
1538 // handleTransactionLocked will fire. It will determine the delta between
1539 // mCurrentState and mDrawingState and re-apply all changes when we make the
1540 // transition.
1541 mDrawingState.displays.clear();
1542 mDisplays.clear();
1543}
1544
Steven Thomas050b2c82017-03-06 11:45:16 -08001545void SurfaceFlinger::updateVrFlinger() {
1546 if (!mVrFlinger)
1547 return;
1548 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001549 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001550 return;
1551 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 ALOGE("Vr flinger is only supported for remote hardware composer"
1555 " service connections. Ignoring request to transition to vr"
1556 " flinger.");
1557 mVrFlingerRequestsDisplay = false;
1558 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001559 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001560
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562
Steven Thomas0123ac62018-07-12 11:32:34 -07001563 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001564 LOG_ALWAYS_FATAL_IF(!display);
1565 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001566 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1567 // called below. Clear the reference now so we don't accidentally use it
1568 // later.
1569 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001572 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 // Delete the current instance before creating the new one
1577 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1578 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1579 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1580 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581
Lloyd Pique441d5042018-10-18 16:49:51 -07001582 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001583 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001584
1585 if (vrFlingerRequestsDisplay) {
1586 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001587 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588
1589 mVisibleRegionsDirty = true;
1590 invalidateHwcGeometry();
1591
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001592 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001593 display = getDefaultDisplayDeviceLocked();
1594 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001595 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001596
Steven Thomasb02664d2017-07-26 18:48:28 -07001597 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001598 const nsecs_t vsyncPeriod = getVsyncPeriod();
1599 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001600
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001601 // The present fences returned from vr_hwc are not an accurate
1602 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001603 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001604 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1605 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001606 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001607 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001608 !hasSyncFramework);
1609 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001610
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 // Use phase of 0 since phase is not known.
1612 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001613 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001614 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001615
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001617
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001618 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001619 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001620}
1621
Mathias Agopian4fec8732012-06-29 14:12:52 -07001622void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001623 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001624 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001626 if (mUseScheduler) {
1627 // This call is made each time SF wakes up and creates a new frame.
1628 mScheduler->incrementFrameCounter();
1629 }
Dan Stoza50182882016-07-08 12:02:20 -07001630 bool frameMissed = !mHadClientComposition &&
1631 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 (mPreviousPresentFence->getSignalTime() ==
1633 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001634 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001635 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001636 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001637 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001638 if (mPropagateBackpressure) {
1639 signalLayerUpdate();
1640 break;
1641 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001642 }
Dan Stoza50182882016-07-08 12:02:20 -07001643
Steven Thomas050b2c82017-03-06 11:45:16 -08001644 // Now that we're going to make it to the handleMessageTransaction()
1645 // call below it's safe to call updateVrFlinger(), which will
1646 // potentially trigger a display handoff.
1647 updateVrFlinger();
1648
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649 bool refreshNeeded = handleMessageTransaction();
1650 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001651
1652 updateCursorAsync();
1653 updateInputFlinger();
1654
Dan Stoza58784442014-12-02 16:58:17 -08001655 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001656 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001657 // Signal a refresh if a transaction modified the window state,
1658 // a new buffer was latched, or if HWC has requested a full
1659 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001660 signalRefresh();
1661 }
1662 break;
1663 }
1664 case MessageQueue::REFRESH: {
1665 handleMessageRefresh();
1666 break;
1667 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001668 }
1669}
1670
Dan Stoza6b9454d2014-11-07 16:00:59 -08001671bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001672 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001673
1674 // Apply any ready transactions in the queues if there are still transactions that have not been
1675 // applied, wake up during the next vsync period and check again
1676 bool transactionNeeded = false;
1677 if (!flushTransactionQueues()) {
1678 transactionNeeded = true;
1679 }
1680
Mathias Agopian4fec8732012-06-29 14:12:52 -07001681 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001682 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001684
1685 if (transactionNeeded) {
1686 setTransactionFlags(eTransactionNeeded);
1687 }
1688
1689 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690}
1691
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001694
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001695 mRefreshPending = false;
1696
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001697 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001698 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001699 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001700 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 for (const auto& [token, display] : mDisplays) {
1702 beginFrame(display);
1703 prepareFrame(display);
1704 doDebugFlashRegions(display, repaintEverything);
1705 doComposition(display, repaintEverything);
1706 }
1707
Adrian Roos1e1a1282017-11-01 19:05:31 +01001708 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001709 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710
1711 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001712 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001713
Dan Stozabfbffeb2016-07-21 14:49:33 -07001714 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 for (const auto& [token, displayDevice] : mDisplays) {
1716 auto display = displayDevice->getCompositionDisplay();
1717 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001719 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001720 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001721
Alec Mouri86770e52018-09-24 22:40:58 +00001722 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001723 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001724 if (mHadClientComposition) {
1725 base::unique_fd flushFence(getRenderEngine().flush());
1726 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1727 getBE().flushFence = new Fence(std::move(flushFence));
1728 } else {
1729 // Cleanup for hygiene.
1730 getBE().flushFence = Fence::NO_FENCE;
1731 }
1732 }
1733
Jorim Jaggi90535212018-05-23 23:44:06 +02001734 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001735
David Sodman7e4ae112018-02-09 15:02:28 -08001736 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001738 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001739 compositionInfo.hwc.hwcLayer = nullptr;
1740 }
David Sodmanba340492018-08-05 21:51:33 -07001741 }
David Sodman7e4ae112018-02-09 15:02:28 -08001742
1743 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001745
David Sodmanfa9b2af2017-12-24 13:28:59 -08001746
1747bool SurfaceFlinger::handleMessageInvalidate() {
1748 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001749 bool refreshNeeded = handlePageFlip();
1750
1751 for (auto& layer : mLayersPendingRefresh) {
1752 Region visibleReg;
1753 visibleReg.set(layer->computeScreenBounds());
1754 invalidateLayerStack(layer, visibleReg);
1755 }
1756 mLayersPendingRefresh.clear();
1757 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001758}
1759
David Sodman79bba0e2018-08-05 18:07:49 -07001760void SurfaceFlinger::calculateWorkingSet() {
1761 ATRACE_CALL();
1762 ALOGV(__FUNCTION__);
1763
David Sodman79bba0e2018-08-05 18:07:49 -07001764 // build the h/w work list
1765 if (CC_UNLIKELY(mGeometryInvalid)) {
1766 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001767 for (const auto& [token, displayDevice] : mDisplays) {
1768 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001769 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001770 if (!displayId) {
1771 continue;
1772 }
David Sodman79bba0e2018-08-05 18:07:49 -07001773
Lloyd Pique32cbe282018-10-19 13:09:22 -07001774 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001775 for (size_t i = 0; i < currentLayers.size(); i++) {
1776 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001777
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 if (!layer->hasHwcLayer(*displayId)) {
1779 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1780 layer->forceClientComposition(*displayId);
1781 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001782 }
1783 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784
Lloyd Pique32cbe282018-10-19 13:09:22 -07001785 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001786 if (mDebugDisableHWC || mDebugRegion) {
1787 layer->forceClientComposition(*displayId);
1788 }
David Sodman79bba0e2018-08-05 18:07:49 -07001789 }
1790 }
1791 }
1792
1793 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001794 for (const auto& [token, displayDevice] : mDisplays) {
1795 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001796 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001798 continue;
1799 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001800 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001801
1802 if (mDrawingState.colorMatrixChanged) {
1803 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001804 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001806 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001807 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1809 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001810 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001811 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001812 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1813 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001814 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 }
1817
Peiyong Lind3788632018-09-18 16:01:31 -07001818 // TODO(b/111562338) remove when composer 2.3 is shipped.
1819 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001820 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001821 }
1822
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001823 if (layer->getRoundedCornerState().radius > 0.0f) {
1824 layer->forceClientComposition(*displayId);
1825 }
1826
Dominik Laskowski075d3172018-05-24 15:50:06 -07001827 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001828 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001829 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001830 continue;
1831 }
1832
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 const auto& displayState = display->getState();
1834 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1835 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001836 }
1837
Peiyong Lin13effd12018-07-24 17:01:47 -07001838 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001839 ColorMode colorMode;
1840 Dataspace dataSpace;
1841 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001842 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001844 }
1845 }
1846
1847 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001848
1849 for (const auto& [token, display] : mDisplays) {
1850 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001851 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001852 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001853
1854 if (displayId) {
1855 if (!layer->setHwcLayer(*displayId)) {
1856 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1857 }
1858 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001859 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001860
Dominik Laskowski05275f12018-11-01 15:03:24 -07001861 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001862 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1863 }
1864 }
David Sodman79bba0e2018-08-05 18:07:49 -07001865}
1866
Lloyd Pique32cbe282018-10-19 13:09:22 -07001867void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1868 bool repaintEverything) {
1869 auto display = displayDevice->getCompositionDisplay();
1870 const auto& displayState = display->getState();
1871
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872 // is debugging enabled
1873 if (CC_LIKELY(!mDebugRegion))
1874 return;
1875
Lloyd Pique32cbe282018-10-19 13:09:22 -07001876 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00001878 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001879 if (!dirtyRegion.isEmpty()) {
1880 // redraw the whole screen
Alec Mouri79108df2019-02-04 19:33:44 +00001881 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882
Alec Mouri79108df2019-02-04 19:33:44 +00001883 // and draw the dirty region
1884 auto& engine(getRenderEngine());
1885 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
1886
1887 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 }
1889 }
1890
Lloyd Pique32cbe282018-10-19 13:09:22 -07001891 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892
1893 if (mDebugRegion > 1) {
1894 usleep(mDebugRegion * 1000);
1895 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001896
Lloyd Pique32cbe282018-10-19 13:09:22 -07001897 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898}
1899
Adrian Roos1e1a1282017-11-01 19:05:31 +01001900void SurfaceFlinger::doTracing(const char* where) {
1901 ATRACE_CALL();
1902 ATRACE_NAME(where);
1903 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001904 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001905 }
1906}
1907
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001908void SurfaceFlinger::logLayerStats() {
1909 ATRACE_CALL();
1910 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001911 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 if (display->isPrimary()) {
1913 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001914 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001915 }
1916 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001917
1918 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001919 }
1920}
1921
David Sodman2b406362017-12-15 13:33:47 -08001922void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001923{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 ATRACE_CALL();
1925 ALOGV("preComposition");
1926
David Sodman2b406362017-12-15 13:33:47 -08001927 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1928
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001930 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001931 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932 needExtraInvalidate = true;
1933 }
Robert Carr2047fae2016-11-28 14:09:09 -08001934 });
1935
Mathias Agopiancd60f992012-08-16 16:28:27 -07001936 if (needExtraInvalidate) {
1937 signalLayerUpdate();
1938 }
1939}
1940
Ana Krulece588e312018-09-18 12:32:24 -07001941void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1942 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943 // Update queue of past composite+present times and determine the
1944 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001945 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001947 while (!getBE().mCompositePresentTimes.empty()) {
1948 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949 // Cached values should have been updated before calling this method,
1950 // which helps avoid duplicate syscalls.
1951 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1952 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1953 break;
1954 }
1955 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001956 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 }
1958
1959 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001960 while (getBE().mCompositePresentTimes.size() > 16) {
1961 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 }
1963
Ana Krulece588e312018-09-18 12:32:24 -07001964 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001965}
1966
Ana Krulece588e312018-09-18 12:32:24 -07001967void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1968 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001969 // Integer division and modulo round toward 0 not -inf, so we need to
1970 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001971 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1972 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1973 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974
Ana Krulec757f63a2019-01-25 10:46:18 -08001975 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001976 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001977 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001978 }
1979
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // Snap the latency to a value that removes scheduling jitter from the
1981 // composition and present times, which often have >1ms of jitter.
1982 // Reducing jitter is important if an app attempts to extrapolate
1983 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001984 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001986 nsecs_t bias = stats.vsyncPeriod / 2;
1987 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1988 nsecs_t snappedCompositeToPresentLatency =
1989 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990
David Sodman99974d22017-11-28 12:04:33 -08001991 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001992 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1993 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001994 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995}
1996
Ady Abraham8164d482019-01-11 14:47:59 -08001997// debug patch for b/119477596 - add stack guards to catch stack
1998// corruptions and disable clang optimizations.
1999// The code below is temporary and planned to be removed once stack
2000// corruptions are found.
2001#pragma clang optimize off
2002class StackGuard {
2003public:
2004 StackGuard(const char* name, const char* func, int line) {
2005 guarders.reserve(MIN_CAPACITY);
2006 guarders.push_back({this, name, func, line});
2007 validate();
2008 }
2009 ~StackGuard() {
2010 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2011 if (i->guard == this) {
2012 guarders.erase(i);
2013 break;
2014 }
2015 }
2016 }
2017
2018 static void validate() {
2019 for (const auto& guard : guarders) {
2020 if (guard.guard->cookie != COOKIE_VALUE) {
2021 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2022 CallStack stack(LOG_TAG);
2023 abort();
2024 }
2025 }
2026 }
2027
2028private:
2029 uint64_t cookie = COOKIE_VALUE;
2030 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2031 static constexpr size_t MIN_CAPACITY = 16;
2032
2033 struct GuarderElement {
2034 StackGuard* guard;
2035 const char* name;
2036 const char* func;
2037 int line;
2038 };
2039
2040 static std::vector<GuarderElement> guarders;
2041};
2042std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2043
2044#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2045
2046#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002047void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048{
Ady Abraham8164d482019-01-11 14:47:59 -08002049 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ATRACE_CALL();
2051 ALOGV("postComposition");
2052
Brian Anderson3546a3f2016-07-14 11:51:14 -07002053 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002054 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002055 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002057 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058 }
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002060
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002061 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002062 const auto displayDevice = getDefaultDisplayDeviceLocked();
2063 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064
David Sodman73beded2017-11-15 11:56:06 -08002065 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2068
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002070 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002071 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2072 ->getRenderSurface()
2073 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002074 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002075 } else {
2076 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2077 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002078
Ady Abraham8164d482019-01-11 14:47:59 -08002079 ASSERT_ON_STACK_GUARD();
2080
David Sodman73beded2017-11-15 11:56:06 -08002081 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2083 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002084 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002085 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002086 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002087
Ana Krulece588e312018-09-18 12:32:24 -07002088 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002089 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002090 if (mUseScheduler) {
2091 mScheduler->getDisplayStatInfo(&stats);
2092 } else {
2093 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2094 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2095 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002096
Ady Abraham8164d482019-01-11 14:47:59 -08002097 ASSERT_ON_STACK_GUARD();
2098
David Sodman2b406362017-12-15 13:33:47 -08002099 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002100 // when we started doing work for this frame, but that should be okay
2101 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002102 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002103 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002104 DEFINE_STACK_GUARD(compositorTiming);
2105
Brian Andersond0010582017-03-07 13:20:31 -08002106 {
David Sodman99974d22017-11-28 12:04:33 -08002107 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002108 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002109 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002110
2111 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002112 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002113
Robert Carr2047fae2016-11-28 14:09:09 -08002114 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002115 bool frameLatched =
2116 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2117 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002118 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002119 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002120 recordBufferingStats(layer->getName().string(),
2121 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002122 }
Ady Abraham8164d482019-01-11 14:47:59 -08002123 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002124 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002125
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002126 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002128 if (mUseScheduler) {
2129 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002130 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002131 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002132 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2133 enableHardwareVsync();
2134 } else {
2135 disableHardwareVsync(false);
2136 }
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002138 }
2139 }
2140
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002141 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002142 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2143 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002144 if (mUseScheduler) {
2145 mScheduler->enableHardwareVsync();
2146 } else {
2147 enableHardwareVsync();
2148 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002149 }
2150 }
2151
Ady Abraham8164d482019-01-11 14:47:59 -08002152 ASSERT_ON_STACK_GUARD();
2153
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002154 if (mAnimCompositionPending) {
2155 mAnimCompositionPending = false;
2156
Brian Anderson4e606e32017-03-16 15:34:57 -07002157 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002158 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002159 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002160
2161 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002162 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002163 // The HWC doesn't support present fences, so use the refresh
2164 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 const nsecs_t presentTime =
2166 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002167 DEFINE_STACK_GUARD(presentTime);
2168
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002169 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002170 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002171 }
2172 mAnimFrameTracker.advanceFrame();
2173 }
Dan Stozab90cf072015-03-05 11:05:59 -08002174
Ady Abraham8164d482019-01-11 14:47:59 -08002175 ASSERT_ON_STACK_GUARD();
2176
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002178 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002179 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002180 }
2181
Ady Abraham8164d482019-01-11 14:47:59 -08002182 ASSERT_ON_STACK_GUARD();
2183
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002184 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002185
Ady Abraham8164d482019-01-11 14:47:59 -08002186 ASSERT_ON_STACK_GUARD();
2187
Lloyd Pique32cbe282018-10-19 13:09:22 -07002188 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2189 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002190 return;
2191 }
2192
2193 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002194 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002195 if (mHasPoweredOff) {
2196 mHasPoweredOff = false;
2197 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002198 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002200 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002201 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002202 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2203 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002204 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002205 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002206 }
David Sodman4a36e932017-11-07 14:29:47 -08002207 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002208
2209 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002210 }
David Sodman4a36e932017-11-07 14:29:47 -08002211 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002212 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002213
2214 {
2215 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002216 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002217 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002218 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002219 if (refillCount > 0) {
2220 const size_t offset = mTexturePool.size();
2221 mTexturePool.resize(mTexturePoolSize);
2222 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2223 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2224 }
Ady Abraham8164d482019-01-11 14:47:59 -08002225 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002226 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002227
Marissa Wallfda30bb2018-10-12 11:34:28 -07002228 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002229 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002230
2231 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232}
Ady Abraham8164d482019-01-11 14:47:59 -08002233#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002234
2235void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 ATRACE_CALL();
2237 ALOGV("rebuildLayerStacks");
2238
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002239 // We need to clear these out now as these may be holding on to a
2240 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2241 // also holds a reference. When the set of visible layers is recomputed,
2242 // some layers may be destroyed if the only thing keeping them alive was
2243 // that list of visible layers associated with each display. The layer
2244 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2245 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2246 for (const auto& [token, display] : mDisplays) {
2247 getBE().mCompositionInfo[token].clear();
2248 }
2249
Mathias Agopiancd60f992012-08-16 16:28:27 -07002250 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002252 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002253 mVisibleRegionsDirty = false;
2254 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002255
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002256 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 const auto& displayDevice = pair.second;
2258 auto display = displayDevice->getCompositionDisplay();
2259 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002260 Region opaqueRegion;
2261 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002262 compositionengine::Output::OutputLayers layersSortedByZ;
2263 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002264 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 const ui::Transform& tr = displayState.transform;
2266 const Rect bounds = displayState.bounds;
2267 if (displayState.isEnabled) {
2268 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002271 auto compositionLayer = layer->getCompositionLayer();
2272 if (compositionLayer == nullptr) {
2273 return;
2274 }
2275
Chia-I Wu83806892017-11-16 10:50:20 -08002276 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002278 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2279 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2280
Lloyd Piqueef36b002019-01-23 17:52:04 -08002281 if (display->belongsInOutput(layer->getLayerStack(),
2282 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002283 Region drawRegion(tr.transform(
2284 layer->visibleNonTransparentRegion));
2285 drawRegion.andSelf(bounds);
2286 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002287 layersSortedByZ.emplace_back(
2288 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2289 layerFE));
2290
2291 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002292 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002293 // Clear out the HWC layer if this layer was
2294 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002295 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002296 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002297 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002298 // WM changes display->layerStack upon sleep/awake.
2299 // Here we make sure we delete the HWC layers even if
2300 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002301 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002302 }
2303
2304 // If a layer is not going to get a release fence because
2305 // it is invisible, but it is also going to release its
2306 // old buffer, add it to the list of layers needing
2307 // fences.
2308 if (hwcLayerDestroyed) {
2309 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2310 mLayersWithQueuedFrames.cend(), layer);
2311 if (found != mLayersWithQueuedFrames.cend()) {
2312 layersNeedingFences.add(layer);
2313 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002314 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002315 });
2316 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002317
2318 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2319
2320 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002321 displayDevice->setLayersNeedingFences(layersNeedingFences);
2322
2323 Region undefinedRegion{bounds};
2324 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2325
2326 display->editState().undefinedRegion = undefinedRegion;
2327 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002328 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002329 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002330}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002331
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002334// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002336// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337// The returned HDR data space is one of
2338// - Dataspace::UNKNOWN
2339// - Dataspace::BT2020_HLG
2340// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2342 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002343 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002344 *outHdrDataSpace = Dataspace::UNKNOWN;
2345
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002347 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 case Dataspace::V0_SCRGB:
2349 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002350 case Dataspace::BT2020:
2351 case Dataspace::BT2020_ITU:
2352 case Dataspace::BT2020_LINEAR:
2353 case Dataspace::DISPLAY_BT2020:
2354 bestDataSpace = Dataspace::DISPLAY_BT2020;
2355 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002357 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002359 case Dataspace::BT2020_PQ:
2360 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002361 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002362 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002363 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002364 case Dataspace::BT2020_HLG:
2365 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002366 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002367 // When there's mixed PQ content and HLG content, we set the HDR
2368 // data space to be BT2020_PQ and convert HLG to PQ.
2369 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2370 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002371 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002372 break;
2373 default:
2374 break;
2375 }
Romain Guy54f154a2017-10-24 21:40:32 +01002376 }
2377
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002378 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002379}
2380
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002381// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2383 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002384 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2385 *outMode = ColorMode::NATIVE;
2386 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002387 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002389 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002390
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002392 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002393
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002394 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2395
Peiyong Lindfde5112018-06-05 10:58:41 -07002396 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002397 const bool isHdr =
2398 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002399 if (isHdr) {
2400 bestDataSpace = hdrDataSpace;
2401 }
2402
Chia-I Wu0d711262018-05-21 15:19:35 -07002403 RenderIntent intent;
2404 switch (mDisplayColorSetting) {
2405 case DisplayColorSetting::MANAGED:
2406 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002407 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002408 break;
2409 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002410 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002411 break;
2412 default: // vendor display color setting
2413 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2414 break;
2415 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002416
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002417 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002418}
2419
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2421 auto display = displayDevice->getCompositionDisplay();
2422 const auto& displayState = display->getState();
2423
Alec Mouri79108df2019-02-04 19:33:44 +00002424 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2426 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 // If nothing has changed (!dirty), don't recompose.
2429 // If something changed, but we don't currently have any visible layers,
2430 // and didn't when we last did a composition, then skip it this time.
2431 // The second rule does two things:
2432 // - When all layers are removed from a display, we'll emit one black
2433 // frame, then nothing more until we get new layers.
2434 // - When a display is created with a private layer stack, we won't
2435 // emit any black frames until a layer is added to the layer stack.
2436 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002437
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 const char flagPrefix[] = {'-', '+'};
2439 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2441 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2442 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2443 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002444
Lloyd Pique31cb2942018-10-19 17:23:03 -07002445 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002446
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002449 }
2450}
2451
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2453 auto display = displayDevice->getCompositionDisplay();
2454 const auto& displayState = display->getState();
2455
2456 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 return;
David Sodman2b406362017-12-15 13:33:47 -08002458 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459
Lloyd Pique31cb2942018-10-19 17:23:03 -07002460 status_t result = display->getRenderSurface()->prepareFrame(
2461 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002464}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002465
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002467 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 ALOGV("doComposition");
2469
Lloyd Pique32cbe282018-10-19 13:09:22 -07002470 auto display = displayDevice->getCompositionDisplay();
2471 const auto& displayState = display->getState();
2472
2473 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002474 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00002475 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002476
David Sodmanfa9b2af2017-12-24 13:28:59 -08002477 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002479
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002481 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002482 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002484}
2485
David Sodmanfa9b2af2017-12-24 13:28:59 -08002486void SurfaceFlinger::postFrame()
2487{
2488 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 const auto display = getDefaultDisplayDeviceLocked();
2490 if (display && getHwComposer().isConnected(*display->getId())) {
2491 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002492 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2493 logFrameStats();
2494 }
2495 }
2496}
2497
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002499 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002501
Lloyd Pique32cbe282018-10-19 13:09:22 -07002502 auto display = displayDevice->getCompositionDisplay();
2503 const auto& displayState = display->getState();
2504 const auto displayId = display->getId();
2505
David Sodmanfa9b2af2017-12-24 13:28:59 -08002506 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002507
Lloyd Pique32cbe282018-10-19 13:09:22 -07002508 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 if (displayId) {
2510 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002511 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002512 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002513 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002514 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002515
Chia-I Wu7b549592017-11-15 09:14:57 -08002516 // The layer buffer from the previous frame (if any) is released
2517 // by HWC only when the release fence from this frame (if any) is
2518 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 if (displayId && layer->hasHwcLayer(*displayId)) {
2520 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2521 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002522 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002523
2524 // If the layer was client composited in the previous frame, we
2525 // need to merge with the previous client target acquire fence.
2526 // Since we do not track that, always merge with the current
2527 // client target acquire fence when it is available, even though
2528 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002529 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002530 releaseFence =
2531 Fence::merge("LayerRelease", releaseFence,
2532 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002533 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002534
David Sodman15094112018-10-11 09:39:37 -07002535 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536 }
Chia-I Wu83806892017-11-16 10:50:20 -08002537
2538 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002540 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002541 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002543 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002545 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002546 }
2547 }
2548
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 if (displayId) {
2550 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002551 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553}
2554
Mathias Agopian87baae12012-07-31 12:38:26 -07002555void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556{
Mathias Agopian841cde52012-03-01 15:44:37 -08002557 ATRACE_CALL();
2558
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002559 // here we keep a copy of the drawing state (that is the state that's
2560 // going to be overwritten by handleTransactionLocked()) outside of
2561 // mStateLock so that the side-effects of the State assignment
2562 // don't happen with mStateLock held (which can cause deadlocks).
2563 State drawingState(mDrawingState);
2564
Mathias Agopianca4d3602011-05-19 15:38:14 -07002565 Mutex::Autolock _l(mStateLock);
2566 const nsecs_t now = systemTime();
2567 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
Mathias Agopianca4d3602011-05-19 15:38:14 -07002569 // Here we're guaranteed that some transaction flags are set
2570 // so we can call handleTransactionLocked() unconditionally.
2571 // We call getTransactionFlags(), which will also clear the flags,
2572 // with mStateLock held to guarantee that mCurrentState won't change
2573 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002574
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002575 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002576 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002577 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002578
Mathias Agopianca4d3602011-05-19 15:38:14 -07002579 mLastTransactionTime = systemTime() - now;
2580 mDebugInTransaction = 0;
2581 invalidateHwcGeometry();
2582 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002583}
2584
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2586 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 const std::optional<DisplayIdentificationInfo> info =
2588 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002589
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002591 continue;
2592 }
2593
Lloyd Piqueba04e622017-12-14 17:11:26 -08002594 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002596 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 mPhysicalDisplayTokens[info->id] = new BBinder();
2598 DisplayDeviceState state;
2599 state.displayId = info->id;
2600 state.isSecure = true; // All physical displays are currently considered secure.
2601 state.displayName = info->name;
2602 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2603 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002604 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002606 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002607
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2609 if (index >= 0) {
2610 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2611 mInterceptor->saveDisplayDeletion(state.sequenceId);
2612 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002613 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002614 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002615 }
2616
2617 processDisplayChangesLocked();
2618 }
2619
2620 mPendingHotplugEvents.clear();
2621}
2622
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002623void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002624 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002625 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2626 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002627 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002628 mEventThread->onHotplugReceived(displayId, connected);
2629 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002630 }
2631}
2632
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002634 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002635 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 const sp<IGraphicBufferProducer>& producer) {
2637 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002638 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002640 creationArgs.isSecure = state.isSecure;
2641 creationArgs.displaySurface = dispSurface;
2642 creationArgs.hasWideColorGamut = false;
2643 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002644
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002645 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002646 creationArgs.isPrimary = isInternalDisplay;
2647
2648 if (useColorManagement && displayId) {
2649 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002651 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002652 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002654
Dominik Laskowski7e045462018-05-30 13:02:02 -07002655 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002657 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 }
tangrobin6753a022018-08-10 10:58:54 +08002659 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 if (displayId) {
2662 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002663 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002665 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Lloyd Pique90c115d2018-09-18 21:39:42 -07002667 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002669 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002670
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671 // Make sure that composition can never be stalled by a virtual display
2672 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002673 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002674 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2676 }
2677
Dominik Laskowski075d3172018-05-24 15:50:06 -07002678 creationArgs.displayInstallOrientation =
2679 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002680
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002682 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002683
Lloyd Pique90c115d2018-09-18 21:39:42 -07002684 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002685
2686 if (maxFrameBufferAcquiredBuffers >= 3) {
2687 nativeWindowSurface->preallocateBuffers();
2688 }
2689
2690 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002691 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002692 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002693 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002694 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002695 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002696 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2697 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 if (!state.isVirtual()) {
2699 LOG_ALWAYS_FATAL_IF(!displayId);
2700 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002701 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setLayerStack(state.layerStack);
2704 display->setProjection(state.orientation, state.viewport, state.frame);
2705 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002708}
2709
Lloyd Pique347200f2017-12-14 17:00:15 -08002710void SurfaceFlinger::processDisplayChangesLocked() {
2711 // here we take advantage of Vector's copy-on-write semantics to
2712 // improve performance by skipping the transaction entirely when
2713 // know that the lists are identical
2714 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2715 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2716 if (!curr.isIdenticalTo(draw)) {
2717 mVisibleRegionsDirty = true;
2718 const size_t cc = curr.size();
2719 size_t dc = draw.size();
2720
2721 // find the displays that were removed
2722 // (ie: in drawing state but not in current state)
2723 // also handle displays that changed
2724 // (ie: displays that are in both lists)
2725 for (size_t i = 0; i < dc;) {
2726 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2727 if (j < 0) {
2728 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002730 // Save display ID before disconnecting.
2731 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002732 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733
2734 if (!display->isVirtual()) {
2735 LOG_ALWAYS_FATAL_IF(!displayId);
2736 dispatchDisplayHotplugEvent(displayId->value, false);
2737 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002739
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 } else {
2742 // this display is in both lists. see if something changed.
2743 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2746 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2747 if (state_binder != draw_binder) {
2748 // changing the surface is like destroying and
2749 // recreating the DisplayDevice, so we just remove it
2750 // from the drawing state, so that it get re-added
2751 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002752 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002753 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 mDrawingState.displays.removeItemsAt(i);
2757 dc--;
2758 // at this point we must loop to the next item
2759 continue;
2760 }
2761
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 if ((state.orientation != draw[i].orientation) ||
2767 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002768 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 }
2770 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002771 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 }
2773 }
2774 }
2775 ++i;
2776 }
2777
2778 // find displays that were added
2779 // (ie: in current state but not in drawing state)
2780 for (size_t i = 0; i < cc; i++) {
2781 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2782 const DisplayDeviceState& state(curr[i]);
2783
Lloyd Pique542307f2018-10-19 13:24:08 -07002784 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002785 sp<IGraphicBufferProducer> producer;
2786 sp<IGraphicBufferProducer> bqProducer;
2787 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002788 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002789
Dominik Laskowski075d3172018-05-24 15:50:06 -07002790 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002791 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 // Virtual displays without a surface are dormant:
2793 // they have external state (layer stack, projection,
2794 // etc.) but no internal state (i.e. a DisplayDevice).
2795 if (state.surface != nullptr) {
2796 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002797 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002798 int width = 0;
2799 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2800 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2801 int height = 0;
2802 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2803 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2804 int intFormat = 0;
2805 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2806 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002807 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002808
Dominik Laskowski075d3172018-05-24 15:50:06 -07002809 displayId =
2810 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002811 }
2812
2813 // TODO: Plumb requested format back up to consumer
2814
2815 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002816 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 bqProducer, bqConsumer,
2818 state.displayName);
2819
2820 dispSurface = vds;
2821 producer = vds;
2822 }
2823 } else {
2824 ALOGE_IF(state.surface != nullptr,
2825 "adding a supported display, but rendering "
2826 "surface is provided (%p), ignoring it",
2827 state.surface.get());
2828
Dominik Laskowski075d3172018-05-24 15:50:06 -07002829 displayId = state.displayId;
2830 LOG_ALWAYS_FATAL_IF(!displayId);
2831 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 producer = bqProducer;
2833 }
2834
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002835 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002836 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002838 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002840 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002841 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002842 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002843 }
2844 }
2845 }
2846 }
2847 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002848
2849 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002850}
2851
Mathias Agopian87baae12012-07-31 12:38:26 -07002852void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002853{
Dan Stoza7dde5992015-05-22 09:51:44 -07002854 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002855 mCurrentState.traverseInZOrder([](Layer* layer) {
2856 layer->notifyAvailableFrames();
2857 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 /*
2860 * Traversal of the children
2861 * (perform the transaction for each of them if needed)
2862 */
2863
Mathias Agopian3559b072012-08-15 13:46:03 -07002864 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002865 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002867 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868
2869 const uint32_t flags = layer->doTransaction(0);
2870 if (flags & Layer::eVisibleRegion)
2871 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002872
2873 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002874 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002875 }
Robert Carr2047fae2016-11-28 14:09:09 -08002876 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 }
2878
2879 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002880 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 */
2882
Mathias Agopiane57f2922012-08-09 16:29:12 -07002883 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002884 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002885 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002886 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002888 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002889 // The transform hint might have changed for some layers
2890 // (either because a display has changed, or because a layer
2891 // as changed).
2892 //
2893 // Walk through all the layers in currentLayers,
2894 // and update their transform hint.
2895 //
2896 // If a layer is visible only on a single display, then that
2897 // display is used to calculate the hint, otherwise we use the
2898 // default display.
2899 //
2900 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2901 // the hint is set before we acquire a buffer from the surface texture.
2902 //
2903 // NOTE: layer transactions have taken place already, so we use their
2904 // drawing state. However, SurfaceFlinger's own transaction has not
2905 // happened yet, so we must use the current state layer list
2906 // (soon to become the drawing state list).
2907 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002909 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002910 bool first = true;
2911 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002912 // NOTE: we rely on the fact that layers are sorted by
2913 // layerStack first (so we don't have to traverse the list
2914 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002915 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002916 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002917 currentlayerStack = layerStack;
2918 // figure out if this layerstack is mirrored
2919 // (more than one display) if so, pick the default display,
2920 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002921 hintDisplay = nullptr;
2922 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002923 if (display->getCompositionDisplay()
2924 ->belongsInOutput(layer->getLayerStack(),
2925 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002926 if (hintDisplay) {
2927 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002928 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002929 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002930 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002931 }
2932 }
2933 }
2934 }
Chet Haase91d25932013-04-11 15:24:55 -07002935
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002937 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2938 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002939
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002940 // could be null when this layer is using a layerStack
2941 // that is not visible on any display. Also can occur at
2942 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002943 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002944 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002945
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002946 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002947 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002948 if (hintDisplay) {
2949 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002950 }
Robert Carr2047fae2016-11-28 14:09:09 -08002951
2952 first = false;
2953 });
Mathias Agopian84300952012-11-21 16:02:13 -08002954 }
2955
2956
Mathias Agopian3559b072012-08-15 13:46:03 -07002957 /*
2958 * Perform our own transaction if needed
2959 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002960
2961 if (mLayersAdded) {
2962 mLayersAdded = false;
2963 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002964 mVisibleRegionsDirty = true;
2965 }
2966
2967 // some layers might have been removed, so
2968 // we need to update the regions they're exposing.
2969 if (mLayersRemoved) {
2970 mLayersRemoved = false;
2971 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002972 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002973 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002974 // this layer is not visible anymore
2975 // TODO: we could traverse the tree from front to back and
2976 // compute the actual visible region
2977 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 Region visibleReg;
2979 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002980 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002981 }
Robert Carr2047fae2016-11-28 14:09:09 -08002982 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 }
2984
2985 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002986}
2987
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002988void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002989 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002990 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002991 return;
2992 }
2993
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002994 if (mVisibleRegionsDirty || mInputInfoChanged) {
2995 mInputInfoChanged = false;
2996 updateInputWindowInfo();
2997 }
2998
2999 executeInputWindowCommands();
3000}
3001
3002void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003003 Vector<InputWindowInfo> inputHandles;
3004
3005 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3006 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003007 // When calculating the screen bounds we ignore the transparent region since it may
3008 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003009 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003010 }
3011 });
3012 mInputFlinger->setInputWindows(inputHandles);
3013}
3014
chaviwfbe5d9c2018-12-26 12:23:37 -08003015void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003016 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3017 if (transferTouchFocusCommand.fromToken != nullptr &&
3018 transferTouchFocusCommand.toToken != nullptr &&
3019 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3020 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3021 transferTouchFocusCommand.toToken);
3022 }
3023 }
3024
3025 mInputWindowCommands.clear();
3026}
3027
Riley Andrews03414a12014-07-01 14:22:59 -07003028void SurfaceFlinger::updateCursorAsync()
3029{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003030 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003031 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003032 continue;
3033 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003035 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3036 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003037 }
3038 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039}
3040
chaviw61626f22018-11-15 16:26:27 -08003041void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3042 if (layer->hasReadyFrame()) {
3043 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3044 if (layer->shouldPresentNow(expectedPresentTime)) {
3045 bool ignored = false;
3046 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3047 }
3048 }
3049 layer->releasePendingBuffer(systemTime());
3050}
3051
Mathias Agopian4fec8732012-06-29 14:12:52 -07003052void SurfaceFlinger::commitTransaction()
3053{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003054 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 for (const auto& l : mLayersPendingRemoval) {
3057 recordBufferingStats(l->getName().string(),
3058 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003059
3060 // We need to release the HWC layers when the Layer is removed
3061 // from the current state otherwise the HWC layer just continues
3062 // showing at its last configured state until we eventually
3063 // abandon the buffer queue.
3064 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003065 l->destroyHwcLayersForAllDisplays();
3066 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003067 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003068 }
3069 mLayersPendingRemoval.clear();
3070 }
3071
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003072 // If this transaction is part of a window animation then the next frame
3073 // we composite should be considered an animation as well.
3074 mAnimCompositionPending = mAnimTransactionPending;
3075
Mathias Agopian4fec8732012-06-29 14:12:52 -07003076 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003077 // clear the "changed" flags in current state
3078 mCurrentState.colorMatrixChanged = false;
3079
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 mDrawingState.traverseInZOrder([](Layer* layer) {
3081 layer->commitChildList();
3082 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003083 mTransactionPending = false;
3084 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086}
3087
Lloyd Pique32cbe282018-10-19 13:09:22 -07003088void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003089 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003090 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003092
Lloyd Pique32cbe282018-10-19 13:09:22 -07003093 auto display = displayDevice->getCompositionDisplay();
3094
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095 Region aboveOpaqueLayers;
3096 Region aboveCoveredLayers;
3097 Region dirty;
3098
Mathias Agopian87baae12012-07-31 12:38:26 -07003099 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100
Robert Carr2047fae2016-11-28 14:09:09 -08003101 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003102 // start with the whole surface at its current location
3103 const Layer::State& s(layer->getDrawingState());
3104
Jesse Hall01e29052013-02-19 16:13:35 -08003105 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003106 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003107 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003108 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003109
Mathias Agopianab028732010-03-16 16:41:46 -07003110 /*
3111 * opaqueRegion: area of a surface that is fully opaque.
3112 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003114
3115 /*
3116 * visibleRegion: area of a surface that is visible on screen
3117 * and not fully transparent. This is essentially the layer's
3118 * footprint minus the opaque regions above it.
3119 * Areas covered by a translucent surface are considered visible.
3120 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003122
3123 /*
3124 * coveredRegion: area of a surface that is covered by all
3125 * visible regions above it (which includes the translucent areas).
3126 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003128
Jesse Halla8026d22012-09-25 13:25:04 -07003129 /*
3130 * transparentRegion: area of a surface that is hinted to be completely
3131 * transparent. This is only used to tell when the layer has no visible
3132 * non-transparent regions and can be removed from the layer list. It
3133 * does not affect the visibleRegion of this layer or any layers
3134 * beneath it. The hint may not be correct if apps don't respect the
3135 * SurfaceView restrictions (which, sadly, some don't).
3136 */
3137 Region transparentRegion;
3138
Mathias Agopianab028732010-03-16 16:41:46 -07003139
3140 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003141 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003142 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003146 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003147 if (!visibleRegion.isEmpty()) {
3148 // Remove the transparent area from the visible region
3149 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003150 if (tr.preserveRects()) {
3151 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003152 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003154 // transformation too complex, can't do the
3155 // transparent region optimization.
3156 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003157 }
Mathias Agopianab028732010-03-16 16:41:46 -07003158 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159
Mathias Agopianab028732010-03-16 16:41:46 -07003160 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003162 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003163 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003164 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003165 // the opaque region is the layer's footprint
3166 opaqueRegion = visibleRegion;
3167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 }
3170
Robert Carre5f4f692018-01-12 13:12:28 -08003171 if (visibleRegion.isEmpty()) {
3172 layer->clearVisibilityRegions();
3173 return;
3174 }
3175
Mathias Agopianab028732010-03-16 16:41:46 -07003176 // Clip the covered region to the visible region
3177 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3178
3179 // Update aboveCoveredLayers for next (lower) layer
3180 aboveCoveredLayers.orSelf(visibleRegion);
3181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 // subtract the opaque region covered by the layers above us
3183 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184
3185 // compute this layer's dirty region
3186 if (layer->contentDirty) {
3187 // we need to invalidate the whole region
3188 dirty = visibleRegion;
3189 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003190 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 layer->contentDirty = false;
3192 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003193 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003194 * the exposed region consists of two components:
3195 * 1) what's VISIBLE now and was COVERED before
3196 * 2) what's EXPOSED now less what was EXPOSED before
3197 *
3198 * note that (1) is conservative, we start with the whole
3199 * visible region but only keep what used to be covered by
3200 * something -- which mean it may have been exposed.
3201 *
3202 * (2) handles areas that were not covered by anything but got
3203 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003204 */
Mathias Agopianab028732010-03-16 16:41:46 -07003205 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003206 const Region oldVisibleRegion = layer->visibleRegion;
3207 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003208 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3209 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 }
3211 dirty.subtractSelf(aboveOpaqueLayers);
3212
3213 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003214 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215
Mathias Agopianab028732010-03-16 16:41:46 -07003216 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003218
Jesse Halla8026d22012-09-25 13:25:04 -07003219 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 layer->setVisibleRegion(visibleRegion);
3221 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003222 layer->setVisibleNonTransparentRegion(
3223 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003224 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225
Mathias Agopian87baae12012-07-31 12:38:26 -07003226 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227}
3228
Chia-I Wuab0c3192017-08-01 11:29:00 -07003229void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003230 for (const auto& [token, displayDevice] : mDisplays) {
3231 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003232 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003233 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003234 }
3235 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003236}
3237
Daniel Solomon42d04562019-01-20 21:03:19 -08003238void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3239 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3240 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3241 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3242 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3243 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3244 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3245 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3246 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3247 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3248 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3249 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3250 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3251}
3252
Dan Stoza6b9454d2014-11-07 16:00:59 -08003253bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003255 ALOGV("handlePageFlip");
3256
Brian Andersond6927fb2016-07-23 23:37:30 -07003257 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258
Mathias Agopian4fec8732012-06-29 14:12:52 -07003259 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003260 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003261 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003262
3263 // Store the set of layers that need updates. This set must not change as
3264 // buffers are being latched, as this could result in a deadlock.
3265 // Example: Two producers share the same command stream and:
3266 // 1.) Layer 0 is latched
3267 // 2.) Layer 0 gets a new frame
3268 // 2.) Layer 1 gets a new frame
3269 // 3.) Layer 1 is latched.
3270 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3271 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003272 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003273 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003274 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003275 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3276 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003277 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003278 } else {
3279 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003280 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003281 } else {
3282 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003283 }
Robert Carr2047fae2016-11-28 14:09:09 -08003284 });
3285
Lloyd Piquef2c79392018-12-20 16:23:33 -08003286 if (!mLayersWithQueuedFrames.empty()) {
3287 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3288 // writes to Layer current state. See also b/119481871
3289 Mutex::Autolock lock(mStateLock);
3290
3291 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003292 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3293 mLayersPendingRefresh.push_back(layer);
3294 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003295 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003296 if (layer->isBufferLatched()) {
3297 newDataLatched = true;
3298 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003299 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003300 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003301
Alec Mouri86770e52018-09-24 22:40:58 +00003302 // Clear the renderengine fence here...
3303 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3304 // clear instead of sp::clear.
3305 getBE().flushFence = Fence::NO_FENCE;
3306
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003307 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003308
3309 // If we will need to wake up at some time in the future to deal with a
3310 // queued frame that shouldn't be displayed during this vsync period, wake
3311 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003312 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003313 signalLayerUpdate();
3314 }
3315
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003316 // enter boot animation on first buffer latch
3317 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3318 ALOGI("Enter boot animation");
3319 mBootStage = BootStage::BOOTANIMATION;
3320 }
3321
Dan Stoza6b9454d2014-11-07 16:00:59 -08003322 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003323 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324}
3325
Mathias Agopianad456f92011-01-13 17:53:01 -08003326void SurfaceFlinger::invalidateHwcGeometry()
3327{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003328 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003329}
3330
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003332 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003333 auto display = displayDevice->getCompositionDisplay();
3334
Dan Stoza71433162014-02-04 16:22:36 -08003335 // We only need to actually compose the display if:
3336 // 1) It is being handled by hardware composer, which may need this to
3337 // keep its virtual display state machine in sync, or
3338 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003340 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003341 return;
3342 }
3343
Dan Stoza9e56aa02015-11-02 13:00:03 -08003344 ALOGV("doDisplayComposition");
Alec Mouri79108df2019-02-04 19:33:44 +00003345 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003346
3347 // swap buffers (presentation)
Alec Mouri79108df2019-02-04 19:33:44 +00003348 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349}
3350
Alec Mouri79108df2019-02-04 19:33:44 +00003351bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003352 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003353
Lloyd Pique32cbe282018-10-19 13:09:22 -07003354 auto display = displayDevice->getCompositionDisplay();
3355 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003356 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003357
3358 const Region bounds(displayState.bounds);
3359 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003360 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003361 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003362
Peiyong Lind3788632018-09-18 16:01:31 -07003363 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003364 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003365
Alec Mouri79108df2019-02-04 19:33:44 +00003366 // Framebuffer will live in this scope for GPU composition.
3367 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003368
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 if (hasClientComposition) {
3370 ALOGV("hasClientComposition");
3371
Alec Mouri79108df2019-02-04 19:33:44 +00003372 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003373
3374 if (buf == nullptr) {
3375 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3376 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003377 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003378 return false;
3379 }
3380
Alec Mouri79108df2019-02-04 19:33:44 +00003381 // Bind the framebuffer in this scope.
3382 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3383 buf->getNativeBuffer());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003384
Alec Mouri79108df2019-02-04 19:33:44 +00003385 if (fbo->getStatus() != NO_ERROR) {
3386 ALOGW("Binding buffer for display [%s] failed with status: %d",
3387 displayDevice->getDisplayName().c_str(), fbo->getStatus());
3388 return false;
3389 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003390
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003391 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003392 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003393 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003394 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003395 }
Alec Mouri79108df2019-02-04 19:33:44 +00003396 getRenderEngine().setOutputDataSpace(outputDataspace);
3397 getRenderEngine().setDisplayMaxLuminance(
3398 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003399
Lloyd Pique441d5042018-10-18 16:49:51 -07003400 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003401 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003402 getHwComposer()
3403 .hasDisplayCapability(displayId,
3404 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003405
Peiyong Lind3788632018-09-18 16:01:31 -07003406 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003407 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3408 if (applyColorMatrix) {
Alec Mouri79108df2019-02-04 19:33:44 +00003409 colorMatrix = mDrawingState.colorMatrix;
3410 }
3411
3412 display->getRenderSurface()->setViewportAndProjection();
3413
3414 // Never touch the framebuffer if we don't have any framebuffer layers
3415 if (hasDeviceComposition) {
3416 // when using overlays, we assume a fully transparent framebuffer
3417 // NOTE: we could reduce how much we need to clear, for instance
3418 // remove where there are opaque FB layers. however, on some
3419 // GPUs doing a "clean slate" clear might be more efficient.
3420 // We'll revisit later if needed.
3421 getRenderEngine().clearWithColor(0, 0, 0, 0);
3422 } else {
3423 // we start with the whole screen area and remove the scissor part
3424 // we're left with the letterbox region
3425 // (common case is that letterbox ends-up being empty)
3426 const Region letterbox = bounds.subtract(displayState.scissor);
3427
3428 // compute the area to clear
3429 const Region region = displayState.undefinedRegion.merge(letterbox);
3430
3431 // screen is already cleared here
3432 if (!region.isEmpty()) {
3433 // can happen with SurfaceView
3434 drawWormhole(region);
3435 }
3436 }
3437
3438 const Rect& bounds = displayState.bounds;
3439 const Rect& scissor = displayState.scissor;
3440 if (scissor != bounds) {
3441 // scissor doesn't match the screen's dimensions, so we
3442 // need to clear everything outside of it and enable
3443 // the GL scissor so we don't draw anything where we shouldn't
3444
3445 // enable scissor for this frame
3446 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003447 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003448 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003449
Mathias Agopian85d751c2012-08-29 16:59:24 -07003450 /*
3451 * and then, render the layers targeted at the framebuffer
3452 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003453
Dan Stoza9e56aa02015-11-02 13:00:03 -08003454 ALOGV("Rendering client layers");
Alec Mouri79108df2019-02-04 19:33:44 +00003455 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003457 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri79108df2019-02-04 19:33:44 +00003458 const Region clip(bounds.intersect(displayTransform.transform(layer->visibleRegion)));
David Sodmanc1498e62018-09-12 14:36:26 -07003459 ALOGV("Layer: %s", layer->getName().string());
3460 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003461 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003462 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003463 case HWC2::Composition::Cursor:
3464 case HWC2::Composition::Device:
3465 case HWC2::Composition::Sideband:
3466 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003467 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003468 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003469 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003470 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003471 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003472 // never clear the very first layer since we're
3473 // guaranteed the FB is already cleared
Alec Mouri79108df2019-02-04 19:33:44 +00003474 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003475 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003476 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003477 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003478 case HWC2::Composition::Client: {
Alec Mouri79108df2019-02-04 19:33:44 +00003479 if (layer->hasColorTransform()) {
3480 mat4 tmpMatrix;
3481 if (applyColorMatrix) {
3482 tmpMatrix = mDrawingState.colorMatrix;
3483 }
3484 tmpMatrix *= layer->getColorTransform();
3485 getRenderEngine().setColorTransform(tmpMatrix);
3486 } else {
3487 getRenderEngine().setColorTransform(colorMatrix);
Peiyong Lind3788632018-09-18 16:01:31 -07003488 }
Alec Mouri79108df2019-02-04 19:33:44 +00003489 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003490 break;
3491 }
3492 default:
3493 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003494 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003495 } else {
3496 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003497 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003498 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003499 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003500
Alec Mouri79108df2019-02-04 19:33:44 +00003501 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003502 if (hasClientComposition) {
Alec Mouri79108df2019-02-04 19:33:44 +00003503 getRenderEngine().setColorTransform(mat4());
3504 getRenderEngine().disableScissor();
3505 display->getRenderSurface()->finishBuffer();
3506 // Clear out error flags here so that we don't wait until next
3507 // composition to log.
3508 getRenderEngine().checkErrors();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003509 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003510 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511}
3512
Chia-I Wu28e3a252018-09-07 12:05:02 -07003513void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003514 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003515 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516}
3517
Dan Stoza7d89d062015-04-30 13:29:25 -07003518status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003519 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003520 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003521 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003522 const sp<Layer>& parent,
3523 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003524{
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 // add this layer to the current state list
3526 {
3527 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003528 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003529 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3530 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003531 return NO_MEMORY;
3532 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003533 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003535 } else if (parent == nullptr) {
3536 lbc->onRemovedFromCurrentState();
3537 } else if (parent->isRemovedFromCurrentState()) {
3538 parent->addChild(lbc);
3539 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003540 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003541 parent->addChild(lbc);
3542 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003543
Yiwei Zhang243b3782018-05-15 17:40:04 -07003544 if (gbc != nullptr) {
3545 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3546 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3547 mMaxGraphicBufferProducerListSize,
3548 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3549 mGraphicBufferProducerList.size(),
3550 mMaxGraphicBufferProducerListSize, mNumLayers);
3551 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003552 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003553 }
3554
Mathias Agopian96f08192010-06-02 23:28:45 -07003555 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003556 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003557
Dan Stoza7d89d062015-04-30 13:29:25 -07003558 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003559}
3560
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003561uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003562 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003563}
3564
Mathias Agopian3f844832013-08-07 21:24:32 -07003565uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003566 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567}
3568
Mathias Agopian3f844832013-08-07 21:24:32 -07003569uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003570 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003571}
3572
3573uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003574 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003575 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003576 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003577 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003578 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 }
3580 return old;
3581}
3582
Marissa Wall713b63f2018-10-17 15:42:43 -07003583bool SurfaceFlinger::flushTransactionQueues() {
3584 Mutex::Autolock _l(mStateLock);
3585 auto it = mTransactionQueues.begin();
3586 while (it != mTransactionQueues.end()) {
3587 auto& [applyToken, transactionQueue] = *it;
3588
3589 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003590 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3591 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003592 break;
3593 }
chaviw273171b2018-12-26 11:46:30 -08003594 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003595 transactionQueue.pop();
3596 }
3597
3598 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3599 }
3600 return mTransactionQueues.empty();
3601}
3602
chaviwca27f252018-02-06 16:46:39 -08003603bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3604 for (const ComposerState& state : states) {
3605 // Here we need to check that the interface we're given is indeed
3606 // one of our own. A malicious client could give us a nullptr
3607 // IInterface, or one of its own or even one of our own but a
3608 // different type. All these situations would cause us to crash.
3609 if (state.client == nullptr) {
3610 return true;
3611 }
3612
3613 sp<IBinder> binder = IInterface::asBinder(state.client);
3614 if (binder == nullptr) {
3615 return true;
3616 }
3617
3618 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3619 return true;
3620 }
3621 }
3622 return false;
3623}
3624
Marissa Wall17b4e452018-12-26 16:32:34 -08003625bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3626 const Vector<ComposerState>& states) {
3627 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3628 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3629 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3630 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3631 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3632 return false;
3633 }
3634
Marissa Wall713b63f2018-10-17 15:42:43 -07003635 for (const ComposerState& state : states) {
3636 const layer_state_t& s = state.state;
3637 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3638 continue;
3639 }
3640 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003641 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003642 }
3643 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003644 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003645}
3646
3647void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3648 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003649 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003650 const InputWindowCommands& inputWindowCommands,
3651 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003652 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003653 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003654
chaviwca27f252018-02-06 16:46:39 -08003655 if (containsAnyInvalidClientState(states)) {
3656 return;
3657 }
3658
Marissa Wall713b63f2018-10-17 15:42:43 -07003659 // If its TransactionQueue already has a pending TransactionState or if it is pending
3660 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003661 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3662 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003663 setTransactionFlags(eTransactionNeeded);
3664 return;
3665 }
3666
chaviw273171b2018-12-26 11:46:30 -08003667 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003668}
3669
3670void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003671 const Vector<DisplayState>& displays, uint32_t flags,
3672 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003673 uint32_t transactionFlags = 0;
3674
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003675 if (flags & eAnimation) {
3676 // For window updates that are part of an animation we must wait for
3677 // previous animation "frames" to be handled.
3678 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003679 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003680 if (CC_UNLIKELY(err != NO_ERROR)) {
3681 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003682 // caller after a few seconds.
3683 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3684 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003685 mAnimTransactionPending = false;
3686 break;
3687 }
3688 }
3689 }
3690
chaviwca27f252018-02-06 16:46:39 -08003691 for (const DisplayState& display : displays) {
3692 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003693 }
3694
Marissa Walle2ffb422018-10-12 11:33:52 -07003695 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003696 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003697 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003698 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003699 // If the state doesn't require a traversal and there are callbacks, send them now
3700 if (!(clientStateFlags & eTraversalNeeded)) {
3701 mTransactionCompletedThread.sendCallbacks();
3702 }
3703 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003704
chaviw273171b2018-12-26 11:46:30 -08003705 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3706
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003707 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3708 // anyway. This can be used as a flush mechanism for previous async transactions.
3709 // Empty animation transaction can be used to simulate back-pressure, so also force a
3710 // transaction for empty animation transactions.
3711 if (transactionFlags == 0 &&
3712 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003713 transactionFlags = eTransactionNeeded;
3714 }
3715
Mathias Agopian386aa982011-11-07 21:58:03 -08003716 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003717 if (mInterceptor->isEnabled()) {
3718 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003719 }
Irvel468051e2016-06-13 16:44:44 -07003720
Mathias Agopian386aa982011-11-07 21:58:03 -08003721 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003722 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3723 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003724 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003725
3726 // if this is a synchronous transaction, wait for it to take effect
3727 // before returning.
3728 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003729 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003730 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003731 if (flags & eAnimation) {
3732 mAnimTransactionPending = true;
3733 }
3734 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003735 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3736 if (CC_UNLIKELY(err != NO_ERROR)) {
3737 // just in case something goes wrong in SF, return to the
3738 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003739 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3740 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003741 break;
3742 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003744 }
3745}
3746
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003747uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3748 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3749 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003750
Mathias Agopiane57f2922012-08-09 16:29:12 -07003751 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003752 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3753
3754 const uint32_t what = s.what;
3755 if (what & DisplayState::eSurfaceChanged) {
3756 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3757 state.surface = s.surface;
3758 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003759 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003760 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003761 if (what & DisplayState::eLayerStackChanged) {
3762 if (state.layerStack != s.layerStack) {
3763 state.layerStack = s.layerStack;
3764 flags |= eDisplayTransactionNeeded;
3765 }
3766 }
3767 if (what & DisplayState::eDisplayProjectionChanged) {
3768 if (state.orientation != s.orientation) {
3769 state.orientation = s.orientation;
3770 flags |= eDisplayTransactionNeeded;
3771 }
3772 if (state.frame != s.frame) {
3773 state.frame = s.frame;
3774 flags |= eDisplayTransactionNeeded;
3775 }
3776 if (state.viewport != s.viewport) {
3777 state.viewport = s.viewport;
3778 flags |= eDisplayTransactionNeeded;
3779 }
3780 }
3781 if (what & DisplayState::eDisplaySizeChanged) {
3782 if (state.width != s.width) {
3783 state.width = s.width;
3784 flags |= eDisplayTransactionNeeded;
3785 }
3786 if (state.height != s.height) {
3787 state.height = s.height;
3788 flags |= eDisplayTransactionNeeded;
3789 }
3790 }
3791
Mathias Agopiane57f2922012-08-09 16:29:12 -07003792 return flags;
3793}
3794
Robert Carrd4ae7f32018-06-07 16:10:57 -07003795bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3796 IPCThreadState* ipc = IPCThreadState::self();
3797 const int pid = ipc->getCallingPid();
3798 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003799 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003800 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003801 return false;
3802 }
3803 return true;
3804}
3805
chaviwca27f252018-02-06 16:46:39 -08003806uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3807 const layer_state_t& s = composerState.state;
3808 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3809
Mathias Agopian13127d82013-03-05 17:47:11 -08003810 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003811 if (layer == nullptr) {
3812 return 0;
3813 }
3814
chaviw8b3871a2017-11-01 17:41:01 -07003815 uint32_t flags = 0;
3816
Garfield Tan8a3083e2018-12-03 13:21:07 -08003817 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003818 bool geometryAppliesWithResize =
3819 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003820
3821 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3822 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003823 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003824 layer->pushPendingState();
3825 }
3826
chaviw8b3871a2017-11-01 17:41:01 -07003827 if (what & layer_state_t::ePositionChanged) {
3828 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3829 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003830 }
chaviw8b3871a2017-11-01 17:41:01 -07003831 }
3832 if (what & layer_state_t::eLayerChanged) {
3833 // NOTE: index needs to be calculated before we update the state
3834 const auto& p = layer->getParent();
3835 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003836 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003837 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003838 mCurrentState.layersSortedByZ.removeAt(idx);
3839 mCurrentState.layersSortedByZ.add(layer);
3840 // we need traversal (state changed)
3841 // AND transaction (list changed)
3842 flags |= eTransactionNeeded|eTraversalNeeded;
3843 }
chaviw8b3871a2017-11-01 17:41:01 -07003844 } else {
3845 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003846 flags |= eTransactionNeeded|eTraversalNeeded;
3847 }
3848 }
chaviw8b3871a2017-11-01 17:41:01 -07003849 }
3850 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003851 // NOTE: index needs to be calculated before we update the state
3852 const auto& p = layer->getParent();
3853 if (p == nullptr) {
3854 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3855 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3856 mCurrentState.layersSortedByZ.removeAt(idx);
3857 mCurrentState.layersSortedByZ.add(layer);
3858 // we need traversal (state changed)
3859 // AND transaction (list changed)
3860 flags |= eTransactionNeeded|eTraversalNeeded;
3861 }
3862 } else {
3863 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3864 flags |= eTransactionNeeded|eTraversalNeeded;
3865 }
chaviw8b3871a2017-11-01 17:41:01 -07003866 }
3867 }
3868 if (what & layer_state_t::eSizeChanged) {
3869 if (layer->setSize(s.w, s.h)) {
3870 flags |= eTraversalNeeded;
3871 }
3872 }
3873 if (what & layer_state_t::eAlphaChanged) {
3874 if (layer->setAlpha(s.alpha))
3875 flags |= eTraversalNeeded;
3876 }
3877 if (what & layer_state_t::eColorChanged) {
3878 if (layer->setColor(s.color))
3879 flags |= eTraversalNeeded;
3880 }
Peiyong Lind3788632018-09-18 16:01:31 -07003881 if (what & layer_state_t::eColorTransformChanged) {
3882 if (layer->setColorTransform(s.colorTransform)) {
3883 flags |= eTraversalNeeded;
3884 }
3885 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003886 if (what & layer_state_t::eBackgroundColorChanged) {
3887 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3888 flags |= eTraversalNeeded;
3889 }
3890 }
chaviw8b3871a2017-11-01 17:41:01 -07003891 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003892 // TODO: b/109894387
3893 //
3894 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3895 // rotation. To see the problem observe that if we have a square parent, and a child
3896 // of the same size, then we rotate the child 45 degrees around it's center, the child
3897 // must now be cropped to a non rectangular 8 sided region.
3898 //
3899 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3900 // private API, and the WindowManager only uses rotation in one case, which is on a top
3901 // level layer in which cropping is not an issue.
3902 //
3903 // However given that abuse of rotation matrices could lead to surfaces extending outside
3904 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3905 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3906 // transformations.
3907 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003908 flags |= eTraversalNeeded;
3909 }
3910 if (what & layer_state_t::eTransparentRegionChanged) {
3911 if (layer->setTransparentRegionHint(s.transparentRegion))
3912 flags |= eTraversalNeeded;
3913 }
3914 if (what & layer_state_t::eFlagsChanged) {
3915 if (layer->setFlags(s.flags, s.mask))
3916 flags |= eTraversalNeeded;
3917 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003918 if (what & layer_state_t::eCropChanged_legacy) {
3919 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003920 flags |= eTraversalNeeded;
3921 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003922 if (what & layer_state_t::eCornerRadiusChanged) {
3923 if (layer->setCornerRadius(s.cornerRadius))
3924 flags |= eTraversalNeeded;
3925 }
chaviw8b3871a2017-11-01 17:41:01 -07003926 if (what & layer_state_t::eLayerStackChanged) {
3927 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3928 // We only allow setting layer stacks for top level layers,
3929 // everything else inherits layer stack from its parent.
3930 if (layer->hasParent()) {
3931 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3932 layer->getName().string());
3933 } else if (idx < 0) {
3934 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3935 "that also does not appear in the top level layer list. Something"
3936 " has gone wrong.", layer->getName().string());
3937 } else if (layer->setLayerStack(s.layerStack)) {
3938 mCurrentState.layersSortedByZ.removeAt(idx);
3939 mCurrentState.layersSortedByZ.add(layer);
3940 // we need traversal (state changed)
3941 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003942 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003943 }
3944 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003945 if (what & layer_state_t::eDeferTransaction_legacy) {
3946 if (s.barrierHandle_legacy != nullptr) {
3947 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3948 } else if (s.barrierGbp_legacy != nullptr) {
3949 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003950 if (authenticateSurfaceTextureLocked(gbp)) {
3951 const auto& otherLayer =
3952 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003953 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003954 } else {
3955 ALOGE("Attempt to defer transaction to to an"
3956 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003957 }
3958 }
chaviw8b3871a2017-11-01 17:41:01 -07003959 // We don't trigger a traversal here because if no other state is
3960 // changed, we don't want this to cause any more work
3961 }
3962 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003963 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003965 if (!hadParent) {
3966 mCurrentState.layersSortedByZ.remove(layer);
3967 }
chaviw8b3871a2017-11-01 17:41:01 -07003968 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 }
3971 if (what & layer_state_t::eReparentChildren) {
3972 if (layer->reparentChildren(s.reparentHandle)) {
3973 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003974 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003975 }
chaviw8b3871a2017-11-01 17:41:01 -07003976 if (what & layer_state_t::eDetachChildren) {
3977 layer->detachChildren();
3978 }
3979 if (what & layer_state_t::eOverrideScalingModeChanged) {
3980 layer->setOverrideScalingMode(s.overrideScalingMode);
3981 // We don't trigger a traversal here because if no other state is
3982 // changed, we don't want this to cause any more work
3983 }
Marissa Wall61c58622018-07-18 10:12:20 -07003984 if (what & layer_state_t::eTransformChanged) {
3985 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3988 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3989 flags |= eTraversalNeeded;
3990 }
3991 if (what & layer_state_t::eCropChanged) {
3992 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3993 }
Marissa Wall861616d2018-10-22 12:52:23 -07003994 if (what & layer_state_t::eFrameChanged) {
3995 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3996 }
Marissa Wall61c58622018-07-18 10:12:20 -07003997 if (what & layer_state_t::eAcquireFenceChanged) {
3998 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eDataspaceChanged) {
4001 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eHdrMetadataChanged) {
4004 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4005 }
4006 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4007 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eApiChanged) {
4010 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4011 }
4012 if (what & layer_state_t::eSidebandStreamChanged) {
4013 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4014 }
Robert Carr720e5062018-07-30 17:45:14 -07004015 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004016 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4017 layer->setInputInfo(s.inputInfo);
4018 flags |= eTraversalNeeded;
4019 } else {
4020 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4021 }
Robert Carr720e5062018-07-30 17:45:14 -07004022 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004023 if (what & layer_state_t::eMetadataChanged) {
4024 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4025 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004026 std::vector<sp<CallbackHandle>> callbackHandles;
4027 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4028 mTransactionCompletedThread.run();
4029 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4030 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4031 }
4032 }
Marissa Wall73411622019-01-25 10:45:41 -08004033
4034 if (what & layer_state_t::eBufferChanged) {
4035 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4036 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4037 s.buffer);
4038 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004039 if (what & layer_state_t::eCachedBufferChanged) {
4040 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004041 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4042 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004043 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4044 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004045 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4046 // Do not put anything that updates layer state or modifies flags after
4047 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004048 return flags;
4049}
4050
chaviw273171b2018-12-26 11:46:30 -08004051uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4052 uint32_t flags = 0;
4053 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4054 flags |= eTraversalNeeded;
4055 }
4056
4057 mInputWindowCommands.merge(inputWindowCommands);
4058 return flags;
4059}
4060
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004061status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4062 uint32_t h, PixelFormat format, uint32_t flags,
4063 LayerMetadata metadata, sp<IBinder>* handle,
4064 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004065 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004066 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004067 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004068 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004069 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004070
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004071 status_t result = NO_ERROR;
4072
4073 sp<Layer> layer;
4074
Cody Northropbc755282017-03-31 12:00:08 -06004075 String8 uniqueName = getUniqueLayerName(name);
4076
Mathias Agopian3165cc22012-08-08 19:42:09 -07004077 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004078 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004079 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4080 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004083 case ISurfaceComposerClient::eFXSurfaceBufferState:
4084 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4085 break;
chaviw13fdc492017-06-27 12:40:18 -07004086 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004087 // check if buffer size is set for color layer.
4088 if (w > 0 || h > 0) {
4089 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4090 int(w), int(h));
4091 return BAD_VALUE;
4092 }
4093
chaviw13fdc492017-06-27 12:40:18 -07004094 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004095 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004096 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004097 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004098 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004099 // check if buffer size is set for container layer.
4100 if (w > 0 || h > 0) {
4101 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4102 int(w), int(h));
4103 return BAD_VALUE;
4104 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004105 result = createContainerLayer(client,
4106 uniqueName, w, h, flags,
4107 handle, &layer);
4108 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004109 default:
4110 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111 break;
4112 }
4113
Dan Stoza7d89d062015-04-30 13:29:25 -07004114 if (result != NO_ERROR) {
4115 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004117
Chia-I Wuab0c3192017-08-01 11:29:00 -07004118 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4119 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004120 if (metadata.has(METADATA_WINDOW_TYPE)) {
4121 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4122 if (windowType == 441731) {
4123 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4124 layer->setPrimaryDisplayOnly();
4125 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004126 }
4127
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004128 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004129
Robert Carrb89ea9d2018-12-10 13:01:14 -08004130 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4131 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4132 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004133 if (result != NO_ERROR) {
4134 return result;
4135 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004136 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004137
4138 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004139 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140}
4141
Cody Northropbc755282017-03-31 12:00:08 -06004142String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4143{
4144 bool matchFound = true;
4145 uint32_t dupeCounter = 0;
4146
4147 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4148 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4149
Dan Stoza436ccf32018-06-21 12:10:12 -07004150 // Grab the state lock since we're accessing mCurrentState
4151 Mutex::Autolock lock(mStateLock);
4152
Cody Northropbc755282017-03-31 12:00:08 -06004153 // Loop over layers until we're sure there is no matching name
4154 while (matchFound) {
4155 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004156 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004157 if (layer->getName() == uniqueName) {
4158 matchFound = true;
4159 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4160 }
4161 });
4162 }
4163
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004164 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4165 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004166
4167 return uniqueName;
4168}
4169
Marissa Wallfd668622018-05-10 10:21:13 -07004170status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4171 uint32_t w, uint32_t h, uint32_t flags,
4172 PixelFormat& format, sp<IBinder>* handle,
4173 sp<IGraphicBufferProducer>* gbp,
4174 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004176 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004177 case PIXEL_FORMAT_TRANSPARENT:
4178 case PIXEL_FORMAT_TRANSLUCENT:
4179 format = PIXEL_FORMAT_RGBA_8888;
4180 break;
4181 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004182 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 break;
4184 }
4185
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004186 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004187 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004188 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004189 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004190 *handle = layer->getHandle();
4191 *gbp = layer->getProducer();
4192 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004194
Marissa Wallfd668622018-05-10 10:21:13 -07004195 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004196 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197}
4198
Marissa Wall61c58622018-07-18 10:12:20 -07004199status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4200 uint32_t w, uint32_t h, uint32_t flags,
4201 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004202 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004203 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004204 *handle = layer->getHandle();
4205 *outLayer = layer;
4206
4207 return NO_ERROR;
4208}
4209
chaviw13fdc492017-06-27 12:40:18 -07004210status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004211 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004212 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004213{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004214 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004215 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004216 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004217}
4218
Robert Carr6b3f6c52018-08-13 13:05:17 -07004219status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4220 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4221 sp<IBinder>* handle, sp<Layer>* outLayer)
4222{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004223 *outLayer =
4224 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004225 *handle = (*outLayer)->getHandle();
4226 return NO_ERROR;
4227}
4228
4229
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004230void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004231 mLayersPendingRemoval.add(layer);
4232 mLayersRemoved = true;
4233 setTransactionFlags(eTransactionNeeded);
4234}
4235
Robert Carr695d5282018-12-18 15:27:58 -08004236void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004237{
Robert Carr2e102c92018-10-23 12:11:15 -07004238 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004239 // If a layer has a parent, we allow it to out-live it's handle
4240 // with the idea that the parent holds a reference and will eventually
4241 // be cleaned up. However no one cleans up the top-level so we do so
4242 // here.
4243 if (layer->getParent() == nullptr) {
4244 mCurrentState.layersSortedByZ.remove(layer);
4245 }
4246 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004247 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004248}
4249
Mathias Agopianb60314a2012-04-10 22:09:54 -07004250// ---------------------------------------------------------------------------
4251
Andy McFadden13a082e2012-08-24 10:16:42 -07004252void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004253 const auto display = getDefaultDisplayDeviceLocked();
4254 if (!display) return;
4255
4256 const sp<IBinder> token = display->getDisplayToken().promote();
4257 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004258
Jesse Hall01e29052013-02-19 16:13:35 -08004259 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004260 Vector<ComposerState> state;
4261 Vector<DisplayState> displays;
4262 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004263 d.what = DisplayState::eDisplayProjectionChanged |
4264 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004265 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004266 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004267 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004268 d.frame.makeInvalid();
4269 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004270 d.width = 0;
4271 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004272 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004273 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004274
Dominik Laskowskie9774092018-12-11 10:04:24 -08004275 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004276
Dominik Laskowski83b88212018-12-11 13:34:06 -08004277 const nsecs_t vsyncPeriod = getVsyncPeriod();
4278 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004279
Brian Andersond0010582017-03-07 13:20:31 -08004280 // Use phase of 0 since phase is not known.
4281 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004282 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004283 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004284}
4285
4286void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004287 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004288 postMessageAsync(
4289 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004290}
4291
Dominik Laskowskie9774092018-12-11 10:04:24 -08004292void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 if (display->isVirtual()) {
4294 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004295 return;
4296 }
4297
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 const auto displayId = display->getId();
4299 LOG_ALWAYS_FATAL_IF(!displayId);
4300
Dominik Laskowski34157762018-10-31 13:07:19 -07004301 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302
4303 int currentMode = display->getPowerMode();
4304 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004305 return;
4306 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004307
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308 display->setPowerMode(mode);
4309
Lloyd Pique4dccc412018-01-22 17:21:36 -08004310 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004311 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004312 }
4313
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004314 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004315 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004316 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004318 if (mUseScheduler) {
4319 mScheduler->onScreenAcquired(mAppConnectionHandle);
4320 } else {
4321 mEventThread->onScreenAcquired();
4322 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004323 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004324 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004325
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004326 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004327 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004328 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004329
4330 struct sched_param param = {0};
4331 param.sched_priority = 1;
4332 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4333 ALOGW("Couldn't set SCHED_FIFO on display on");
4334 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004335 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004336 // Turn off the display
4337 struct sched_param param = {0};
4338 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4339 ALOGW("Couldn't set SCHED_OTHER on display off");
4340 }
4341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004342 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004343 if (mUseScheduler) {
4344 mScheduler->disableHardwareVsync(true);
4345 } else {
4346 disableHardwareVsync(true); // also cancels any in-progress resync
4347 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004348 if (mUseScheduler) {
4349 mScheduler->onScreenReleased(mAppConnectionHandle);
4350 } else {
4351 mEventThread->onScreenReleased();
4352 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004353 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004354
Dominik Laskowski075d3172018-05-24 15:50:06 -07004355 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004356 mVisibleRegionsDirty = true;
4357 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004358 } else if (mode == HWC_POWER_MODE_DOZE ||
4359 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004360 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004361 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004363 if (mUseScheduler) {
4364 mScheduler->onScreenAcquired(mAppConnectionHandle);
4365 } else {
4366 mEventThread->onScreenAcquired();
4367 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004368 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004369 }
4370 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4371 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004372 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004373 if (mUseScheduler) {
4374 mScheduler->disableHardwareVsync(true);
4375 } else {
4376 disableHardwareVsync(true); // also cancels any in-progress resync
4377 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004378 if (mUseScheduler) {
4379 mScheduler->onScreenReleased(mAppConnectionHandle);
4380 } else {
4381 mEventThread->onScreenReleased();
4382 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004383 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004384 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004385 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004386 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004387 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004388 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004389
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004390 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004391 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004392 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004393 // Update refresh rate stats.
4394 mRefreshRateStats->setPowerMode(mode);
4395 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004396 }
4397
Dominik Laskowski34157762018-10-31 13:07:19 -07004398 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004399}
4400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004401void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004402 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004403 const auto display = getDisplayDevice(displayToken);
4404 if (!display) {
4405 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4406 displayToken.get());
4407 } else if (display->isVirtual()) {
4408 ALOGW("Attempt to set power mode %d for virtual display", mode);
4409 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004410 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004411 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004412 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004413}
4414
4415// ---------------------------------------------------------------------------
4416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4418 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004420
Mathias Agopianbd115332013-04-18 16:41:04 -07004421 IPCThreadState* ipc = IPCThreadState::self();
4422 const int pid = ipc->getCallingPid();
4423 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004424
Mathias Agopianbd115332013-04-18 16:41:04 -07004425 if ((uid != AID_SHELL) &&
4426 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4428 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004429 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004430 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004431 // (this would indicate SF is stuck, but we want to be able to
4432 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004433 status_t err = mStateLock.timedLock(s2ns(1));
4434 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004435 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 StringAppendF(&result,
4437 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4438 "(no locks held)\n",
4439 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004440 }
4441
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004443
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444 static const std::unordered_map<std::string, Dumper> dumpers = {
4445 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4446 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4447 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4448 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4449 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4450 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4451 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4452 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4453 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4454 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4455 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4456 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4457 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004458 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4460 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004461
Dominik Laskowskic2867142019-01-21 11:33:38 -08004462 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004463
Dominik Laskowskic2867142019-01-21 11:33:38 -08004464 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4465 (it->second)(args, asProto, result);
4466 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004467 if (asProto) {
4468 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4469 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4470 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004472 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004473 }
4474
Mathias Agopian9795c422009-08-26 16:36:26 -07004475 if (locked) {
4476 mStateLock.unlock();
4477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 return NO_ERROR;
4481}
4482
Dominik Laskowskic2867142019-01-21 11:33:38 -08004483void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 mCurrentState.traverseInZOrder(
4485 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004486}
4487
Dominik Laskowskic2867142019-01-21 11:33:38 -08004488void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004489 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004490
Dominik Laskowskic2867142019-01-21 11:33:38 -08004491 if (args.size() > 1) {
4492 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004493 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004494 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004495 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004496 }
Robert Carr2047fae2016-11-28 14:09:09 -08004497 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004498 } else {
4499 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500 }
4501}
4502
Dominik Laskowskic2867142019-01-21 11:33:38 -08004503void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004504 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004505 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004506 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004507 }
Robert Carr2047fae2016-11-28 14:09:09 -08004508 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004509
Svetoslavd85084b2014-03-20 10:28:31 -07004510 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004511}
4512
Dominik Laskowskic2867142019-01-21 11:33:38 -08004513void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4514 mTimeStats->parseArgs(asProto, args, result);
4515}
4516
Jamie Gennis6547ff42013-07-16 20:12:42 -07004517// This should only be called from the main thread. Otherwise it would need
4518// the lock and should use mCurrentState rather than mDrawingState.
4519void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004520 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004521 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004522 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004523
4524 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4525}
4526
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004528 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004529
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004530 if (isLayerTripleBufferingDisabled())
4531 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004532
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4534 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4535 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4536 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4537 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4538 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004539 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004540}
4541
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004542void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004543 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004544 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004545 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004546 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004547
4548 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4549
4550 if (mUseScheduler) {
4551 mScheduler->dump(mAppConnectionHandle, result);
4552 } else {
4553 mEventThread->dump(result);
4554 }
4555}
4556
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4558 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004559 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4560 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004561 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004562 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004564 }
David Sodman4a36e932017-11-07 14:29:47 -08004565 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004566 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004567 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4569 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004570}
4571
Dan Stozae77c7662016-05-13 11:37:28 -07004572void SurfaceFlinger::recordBufferingStats(const char* layerName,
4573 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004574 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4575 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004576 for (const auto& segment : history) {
4577 if (!segment.usedThirdBuffer) {
4578 stats.twoBufferTime += segment.totalTime;
4579 }
4580 if (segment.occupancyAverage < 1.0f) {
4581 stats.doubleBufferedTime += segment.totalTime;
4582 } else if (segment.occupancyAverage < 2.0f) {
4583 stats.tripleBufferedTime += segment.totalTime;
4584 }
4585 ++stats.numSegments;
4586 stats.totalTime += segment.totalTime;
4587 }
4588}
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4591 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004592
4593 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4594 const size_t count = currentLayers.size();
4595 for (size_t i=0 ; i<count ; i++) {
4596 currentLayers[i]->dumpFrameEvents(result);
4597 }
4598}
4599
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004601 result.append("Buffering stats:\n");
4602 result.append(" [Layer name] <Active time> <Two buffer> "
4603 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004604 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004605 typedef std::tuple<std::string, float, float, float> BufferTuple;
4606 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004607 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004608 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004609 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004610 if (stats.numSegments == 0) {
4611 continue;
4612 }
4613 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4614 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4615 stats.totalTime;
4616 float doubleBufferRatio = static_cast<float>(
4617 stats.doubleBufferedTime) / stats.totalTime;
4618 float tripleBufferRatio = static_cast<float>(
4619 stats.tripleBufferedTime) / stats.totalTime;
4620 sorted.insert({activeTime, {name, twoBufferRatio,
4621 doubleBufferRatio, tripleBufferRatio}});
4622 }
4623 for (const auto& sortedPair : sorted) {
4624 float activeTime = sortedPair.first;
4625 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4627 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004628 }
4629 result.append("\n");
4630}
4631
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004633 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004634 const auto displayId = display->getId();
4635 if (!displayId) {
4636 continue;
4637 }
4638 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004639 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 continue;
4641 }
4642
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result,
4644 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4645 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004646 uint8_t port;
4647 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004648 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649 result.append("no identification data\n");
4650 continue;
4651 }
4652
4653 if (!isEdid(data)) {
4654 result.append("unknown identification data: ");
4655 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004657 }
4658 result.append("\n");
4659 continue;
4660 }
4661
4662 const auto edid = parseEdid(data);
4663 if (!edid) {
4664 result.append("invalid EDID: ");
4665 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004667 }
4668 result.append("\n");
4669 continue;
4670 }
4671
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004673 result.append(edid->displayName.data(), edid->displayName.length());
4674 result.append("\"\n");
4675 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004676}
4677
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4679 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4680 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4681 StringAppendF(&result, "DisplayColorSetting: %s\n",
4682 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004683
4684 // TODO: print out if wide-color mode is active or not
4685
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004686 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004687 const auto displayId = display->getId();
4688 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004689 continue;
4690 }
4691
Yiwei Zhang5434a782018-12-05 18:06:32 -08004692 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004693 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004694 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004696 }
4697
Lloyd Pique32cbe282018-10-19 13:09:22 -07004698 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, " Current color mode: %s (%d)\n",
4700 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004701 }
4702 result.append("\n");
4703}
4704
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004706 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004707 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4708 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004709 continue;
4710 }
4711
Dominik Laskowski05275f12018-11-01 15:03:24 -07004712 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004713 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4714 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004715 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004716 compositionInfo.dump(result, nullptr);
4717 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004718 }
4719 }
David Sodman7e4ae112018-02-09 15:02:28 -08004720}
4721
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004722LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004723 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004724 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4725 const State& state = useDrawing ? mDrawingState : mCurrentState;
4726 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004727 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004728 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004729 });
4730
4731 return layersProto;
4732}
4733
Lloyd Pique32cbe282018-10-19 13:09:22 -07004734LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004735 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004736
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004737 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004738 resolution->set_w(displayDevice.getWidth());
4739 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004740
Lloyd Pique32cbe282018-10-19 13:09:22 -07004741 auto display = displayDevice.getCompositionDisplay();
4742 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004743
Lloyd Pique32cbe282018-10-19 13:09:22 -07004744 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4745 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4746 layersProto.set_global_transform(displayState.orientation);
4747
4748 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004749 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004750 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004751 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004752 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004753 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004754 }
4755 });
4756
4757 return layersProto;
4758}
4759
Dominik Laskowskic2867142019-01-21 11:33:38 -08004760void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4761 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004762 Colorizer colorizer(colorize);
4763
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004764 // figure out if we're stuck somewhere
4765 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004766 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004767 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4768
4769 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004770 * Dump library configuration.
4771 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004772
4773 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004774 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004776 appendSfConfigString(result);
4777 appendUiConfigString(result);
4778 appendGuiConfigString(result);
4779 result.append("\n");
4780
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004781 result.append("\nDisplay identification data:\n");
4782 dumpDisplayIdentificationData(result);
4783
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004784 result.append("\nWide-Color information:\n");
4785 dumpWideColorInfo(result);
4786
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004788 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004790 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004791 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004792
Andy McFadden41d67d72014-04-25 16:58:34 -07004793 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004794 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004795 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004796 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004797 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004798
Dan Stozab90cf072015-03-05 11:05:59 -08004799 dumpStaticScreenStats(result);
4800 result.append("\n");
4801
Yiwei Zhang5434a782018-12-05 18:06:32 -08004802 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004803
Dan Stozae77c7662016-05-13 11:37:28 -07004804 dumpBufferingStats(result);
4805
Andy McFadden4803b742012-09-24 19:07:20 -07004806 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004807 * Dump the visible layer list
4808 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4811 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4812 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004813 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004814
Chia-I Wu2f884132018-09-13 15:17:58 -07004815 {
4816 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4817 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004819 result.append("\n");
4820 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004821
David Sodman7e4ae112018-02-09 15:02:28 -08004822 result.append("\nFrame-Composition information:\n");
4823 dumpFrameCompositionInfo(result);
4824 result.append("\n");
4825
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004826 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004827 * Dump Display state
4828 */
4829
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004830 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004832 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004833 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004834 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004835 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004836 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004837
4838 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839 * Dump SurfaceFlinger global state
4840 */
4841
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004842 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004843 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004844 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004846 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
Dominik Laskowski075d3172018-05-24 15:50:06 -07004848 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004849 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4850 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004851 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4852 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004853 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004854 StringAppendF(&result,
4855 " transaction-flags : %08x\n"
4856 " gpu_to_cpu_unsupported : %d\n",
4857 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004858
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004859 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004860 displayId && getHwComposer().isConnected(*displayId)) {
4861 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004862 StringAppendF(&result,
4863 " refresh-rate : %f fps\n"
4864 " x-dpi : %f\n"
4865 " y-dpi : %f\n",
4866 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4867 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004868 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004869
Yiwei Zhang5434a782018-12-05 18:06:32 -08004870 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004871
Dan Stozae22aec72016-08-01 13:20:59 -07004872 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004873 * Tracing state
4874 */
4875 mTracing.dump(result);
4876 result.append("\n");
4877
4878 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004879 * HWC layer minidump
4880 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004881 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004882 const auto displayId = display->getId();
4883 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004884 continue;
4885 }
4886
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004888 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004889 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004890 result.append("\n");
4891 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892
4893 /*
4894 * Dump HWComposer state
4895 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004896 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004897 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004898 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004899 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004900 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004901 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004902
4903 /*
4904 * Dump gralloc state
4905 */
4906 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4907 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004908
4909 /*
4910 * Dump VrFlinger state if in use.
4911 */
4912 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4913 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004914 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004915 result.append("\n");
4916 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004917
4918 /**
4919 * Scheduler dump state.
4920 */
4921 if (mUseScheduler) {
4922 result.append("\nScheduler state:\n");
4923 result.append(mScheduler->doDump() + "\n");
4924 result.append(mRefreshRateStats->doDump() + "\n");
4925 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004926}
4927
Dominik Laskowski075d3172018-05-24 15:50:06 -07004928const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004929 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004930 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004931 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004932 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004933 }
4934 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004935
Dominik Laskowski34157762018-10-31 13:07:19 -07004936 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004937 static const Vector<sp<Layer>> empty;
4938 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004939}
4940
Chia-I Wu28f320b2018-05-03 11:02:56 -07004941void SurfaceFlinger::updateColorMatrixLocked() {
4942 mat4 colorMatrix;
4943 if (mGlobalSaturationFactor != 1.0f) {
4944 // Rec.709 luma coefficients
4945 float3 luminance{0.213f, 0.715f, 0.072f};
4946 luminance *= 1.0f - mGlobalSaturationFactor;
4947 mat4 saturationMatrix = mat4(
4948 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4949 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4950 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4951 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4952 );
4953 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4954 } else {
4955 colorMatrix = mClientColorMatrix * mDaltonizer();
4956 }
4957
4958 if (mCurrentState.colorMatrix != colorMatrix) {
4959 mCurrentState.colorMatrix = colorMatrix;
4960 mCurrentState.colorMatrixChanged = true;
4961 setTransactionFlags(eTransactionNeeded);
4962 }
4963}
4964
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004965status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966#pragma clang diagnostic push
4967#pragma clang diagnostic error "-Wswitch-enum"
4968 switch (static_cast<ISurfaceComposerTag>(code)) {
4969 // These methods should at minimum make sure that the client requested
4970 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004971 case BOOT_FINISHED:
4972 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004973 case CREATE_DISPLAY:
4974 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004975 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 case GET_ACTIVE_COLOR_MODE:
4977 case GET_ANIMATION_FRAME_STATS:
4978 case GET_HDR_CAPABILITIES:
4979 case SET_ACTIVE_CONFIG:
4980 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004981 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004982 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004983 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004984 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4985 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004986 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4987 IPCThreadState* ipc = IPCThreadState::self();
4988 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4989 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004990 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004991 }
Robert Carr1db73f62016-12-21 12:58:51 -08004992 return OK;
4993 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004995 IPCThreadState* ipc = IPCThreadState::self();
4996 const int pid = ipc->getCallingPid();
4997 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4999 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005000 return PERMISSION_DENIED;
5001 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 // Used by apps to hook Choreographer to SurfaceFlinger.
5005 case CREATE_DISPLAY_EVENT_CONNECTION:
5006 // The following calls are currently used by clients that do not
5007 // request necessary permissions. However, they do not expose any secret
5008 // information, so it is OK to pass them.
5009 case AUTHENTICATE_SURFACE:
5010 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005011 case GET_PHYSICAL_DISPLAY_IDS:
5012 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005014 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005015 case GET_DISPLAY_CONFIGS:
5016 case GET_DISPLAY_STATS:
5017 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5018 // Calling setTransactionState is safe, because you need to have been
5019 // granted a reference to Client* and Handle* to do anything with it.
5020 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005021 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005022 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005023 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005024 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005025 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005026 return OK;
5027 }
5028 case CAPTURE_LAYERS:
5029 case CAPTURE_SCREEN: {
5030 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005031 IPCThreadState* ipc = IPCThreadState::self();
5032 const int pid = ipc->getCallingPid();
5033 const int uid = ipc->getCallingUid();
5034 if ((uid != AID_GRAPHICS) &&
5035 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5036 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5037 return PERMISSION_DENIED;
5038 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005039 return OK;
5040 }
5041 // The following codes are deprecated and should never be allowed to access SF.
5042 case CONNECT_DISPLAY_UNUSED:
5043 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5044 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5045 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048
5049 // These codes are used for the IBinder protocol to either interrogate the recipient
5050 // side of the transaction for its canonical interface descriptor or to dump its state.
5051 // We let them pass by default.
5052 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5053 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5054 code == IBinder::SYSPROPS_TRANSACTION) {
5055 return OK;
5056 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005057 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005058 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005059 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005060 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5061 return OK;
5062 }
5063 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5064 return PERMISSION_DENIED;
5065#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005066}
5067
Ana Krulec13be8ad2018-08-21 02:43:56 +00005068status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5069 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005070 status_t credentialCheck = CheckTransactCodeCredentials(code);
5071 if (credentialCheck != OK) {
5072 return credentialCheck;
5073 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5076 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005077 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005078 IPCThreadState* ipc = IPCThreadState::self();
5079 const int uid = ipc->getCallingUid();
5080 if (CC_UNLIKELY(uid != AID_SYSTEM
5081 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005082 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005083 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005084 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005085 return PERMISSION_DENIED;
5086 }
5087 int n;
5088 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005089 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005090 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 return NO_ERROR;
5092 case 1002: // SHOW_UPDATES
5093 n = data.readInt32();
5094 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005095 invalidateHwcGeometry();
5096 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005098 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005099 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005100 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005102 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005103 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005104 setTransactionFlags(
5105 eTransactionNeeded|
5106 eDisplayTransactionNeeded|
5107 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005108 return NO_ERROR;
5109 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005110 case 1006:{ // send empty update
5111 signalRefresh();
5112 return NO_ERROR;
5113 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005114 case 1008: // toggle use of hw composer
5115 n = data.readInt32();
5116 mDebugDisableHWC = n ? 1 : 0;
5117 invalidateHwcGeometry();
5118 repaintEverything();
5119 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005120 case 1009: // toggle use of transform hint
5121 n = data.readInt32();
5122 mDebugDisableTransformHint = n ? 1 : 0;
5123 invalidateHwcGeometry();
5124 repaintEverything();
5125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005127 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005128 reply->writeInt32(0);
5129 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005130 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005131 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 return NO_ERROR;
5133 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005134 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005135 if (!display) {
5136 return NAME_NOT_FOUND;
5137 }
5138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005139 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005140 return NO_ERROR;
5141 }
5142 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005143 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005144 // daltonize
5145 n = data.readInt32();
5146 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005147 case 1:
5148 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5149 break;
5150 case 2:
5151 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5152 break;
5153 case 3:
5154 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5155 break;
5156 default:
5157 mDaltonizer.setType(ColorBlindnessType::None);
5158 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005159 }
5160 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005161 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005162 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005163 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005164 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005165
5166 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005167 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005168 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005169 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005170 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 // apply a color matrix
5172 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005174 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005175 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005176 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005177 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005178 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005179 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005180 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005181 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005183
5184 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5185 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005186 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005187 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5188 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5189 }
5190
Chia-I Wu28f320b2018-05-03 11:02:56 -07005191 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005192 return NO_ERROR;
5193 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005194 // This is an experimental interface
5195 // Needs to be shifted to proper binder interface when we productize
5196 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005197 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005198 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005199 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005200 return NO_ERROR;
5201 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005202 case 1017: {
5203 n = data.readInt32();
5204 mForceFullDamage = static_cast<bool>(n);
5205 return NO_ERROR;
5206 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005207 case 1018: { // Modify Choreographer's phase offset
5208 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005209 if (mUseScheduler) {
5210 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5211 } else {
5212 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5213 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005214 return NO_ERROR;
5215 }
5216 case 1019: { // Modify SurfaceFlinger's phase offset
5217 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005218 if (mUseScheduler) {
5219 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5220 } else {
5221 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5222 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005223 return NO_ERROR;
5224 }
Irvel468051e2016-06-13 16:44:44 -07005225 case 1020: { // Layer updates interceptor
5226 n = data.readInt32();
5227 if (n) {
5228 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005229 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005230 }
5231 else{
5232 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005233 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005234 }
5235 return NO_ERROR;
5236 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005237 case 1021: { // Disable HWC virtual displays
5238 n = data.readInt32();
5239 mUseHwcVirtualDisplays = !n;
5240 return NO_ERROR;
5241 }
Romain Guy0147a172017-06-01 13:53:56 -07005242 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005243 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005244 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005245
Chia-I Wu28f320b2018-05-03 11:02:56 -07005246 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005247 return NO_ERROR;
5248 }
Romain Guy54f154a2017-10-24 21:40:32 +01005249 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005250 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005251 invalidateHwcGeometry();
5252 repaintEverything();
5253 return NO_ERROR;
5254 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005255 // Deprecate, use 1030 to check whether the device is color managed.
5256 case 1024: {
5257 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005258 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005259 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005260 n = data.readInt32();
5261 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005262 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005263 mTracing.enable();
5264 doTracing("tracing.enable");
5265 reply->writeInt32(NO_ERROR);
5266 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005267 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005268 status_t err = mTracing.disable();
5269 reply->writeInt32(err);
5270 }
5271 return NO_ERROR;
5272 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005273 case 1026: { // Get layer tracing status
5274 reply->writeBool(mTracing.isEnabled());
5275 return NO_ERROR;
5276 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005277 // Is a DisplayColorSetting supported?
5278 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005279 const auto display = getDefaultDisplayDevice();
5280 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005281 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005282 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005283
5284 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5285 switch (setting) {
5286 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005287 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005288 break;
5289 case DisplayColorSetting::UNMANAGED:
5290 reply->writeBool(true);
5291 break;
5292 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005293 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005294 break;
5295 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005296 reply->writeBool(
5297 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005298 break;
5299 }
5300 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005301 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005302 // Is VrFlinger active?
5303 case 1028: {
5304 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005305 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005306 return NO_ERROR;
5307 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005308 // Is device color managed?
5309 case 1030: {
5310 reply->writeBool(useColorManagement);
5311 return NO_ERROR;
5312 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005313 // Override default composition data space
5314 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5315 // && adb shell stop zygote && adb shell start zygote
5316 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5317 // adb shell stop zygote && adb shell start zygote
5318 case 1031: {
5319 Mutex::Autolock _l(mStateLock);
5320 n = data.readInt32();
5321 if (n) {
5322 n = data.readInt32();
5323 if (n) {
5324 Dataspace dataspace = static_cast<Dataspace>(n);
5325 if (!validateCompositionDataspace(dataspace)) {
5326 return BAD_VALUE;
5327 }
5328 mDefaultCompositionDataspace = dataspace;
5329 }
5330 n = data.readInt32();
5331 if (n) {
5332 Dataspace dataspace = static_cast<Dataspace>(n);
5333 if (!validateCompositionDataspace(dataspace)) {
5334 return BAD_VALUE;
5335 }
5336 mWideColorGamutCompositionDataspace = dataspace;
5337 }
5338 } else {
5339 // restore composition data space.
5340 mDefaultCompositionDataspace = defaultCompositionDataspace;
5341 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5342 }
5343 return NO_ERROR;
5344 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005345 }
5346 }
5347 return err;
5348}
5349
Steven Thomas6d8110b2017-08-31 18:24:21 -07005350void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005351 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005352 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005353}
5354
Ana Krulec7d1d6832018-12-27 11:10:09 -08005355void SurfaceFlinger::repaintEverythingForHWC() {
5356 mRepaintEverything = true;
5357 mEventQueue->invalidateForHWC();
5358}
5359
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5361class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005362public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005363 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5364 ~WindowDisconnector() {
5365 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005366 }
5367
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005368private:
5369 ANativeWindow* mWindow;
5370 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005371};
5372
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005373status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005374 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5375 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005376 uint32_t reqWidth, uint32_t reqHeight,
5377 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005378 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005379 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005380
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005382
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005383 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5384
Chia-I Wu20261cb2018-08-23 12:55:44 -07005385 sp<DisplayDevice> display;
5386 {
5387 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005388
Chia-I Wu20261cb2018-08-23 12:55:44 -07005389 display = getDisplayDeviceLocked(displayToken);
5390 if (!display) return BAD_VALUE;
5391
Chia-I Wucb023152018-08-28 12:57:23 -07005392 // set the requested width/height to the logical display viewport size
5393 // by default
5394 if (reqWidth == 0 || reqHeight == 0) {
5395 reqWidth = uint32_t(display->getViewport().width());
5396 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005397 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005398 }
5399
Peiyong Lin0e003c92018-09-17 11:09:51 -07005400 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5401 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005402
5403 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005404 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005405 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5406 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005407}
5408
5409status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005410 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5411 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005412 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005413 ATRACE_CALL();
5414
5415 class LayerRenderArea : public RenderArea {
5416 public:
Robert Carr578038f2018-03-09 12:25:24 -08005417 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005418 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5419 bool childrenOnly)
5420 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005421 mLayer(layer),
5422 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005423 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005424 mFlinger(flinger),
5425 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005426 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005427 Rect getBounds() const override {
5428 const Layer::State& layerState(mLayer->getDrawingState());
5429 return mLayer->getBufferSize(layerState);
5430 }
Marissa Wall61c58622018-07-18 10:12:20 -07005431 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005432 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005433 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005434 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005435 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005436 }
chaviwa76b2712017-09-20 12:02:26 -07005437 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005438 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005439 Rect getSourceCrop() const override {
5440 if (mCrop.isEmpty()) {
5441 return getBounds();
5442 } else {
5443 return mCrop;
5444 }
5445 }
Robert Carr578038f2018-03-09 12:25:24 -08005446 class ReparentForDrawing {
5447 public:
5448 const sp<Layer>& oldParent;
5449 const sp<Layer>& newParent;
5450
5451 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5452 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005453 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005454 }
Robert Carr15eae092018-03-23 13:43:53 -07005455 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005456 };
5457
5458 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005459 const Rect sourceCrop = getSourceCrop();
5460 // no need to check rotation because there is none
5461 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5462 sourceCrop.height() != getReqHeight();
5463
Robert Carr578038f2018-03-09 12:25:24 -08005464 if (!mChildrenOnly) {
5465 mTransform = mLayer->getTransform().inverse();
5466 drawLayers();
5467 } else {
5468 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005469 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005470 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5471 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005472
5473 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5474 drawLayers();
5475 }
5476 }
chaviwa76b2712017-09-20 12:02:26 -07005477
chaviwa76b2712017-09-20 12:02:26 -07005478 private:
chaviw7206d492017-11-10 16:16:12 -08005479 const sp<Layer> mLayer;
5480 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005481
5482 // In the "childrenOnly" case we reparent the children to a screenshot
5483 // layer which has no properties set and which does not draw.
5484 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005485 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005486 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005487
5488 SurfaceFlinger* mFlinger;
5489 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005490 };
5491
5492 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5493 auto parent = layerHandle->owner.promote();
5494
Robert Carr2e102c92018-10-23 12:11:15 -07005495 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005496 ALOGE("captureLayers called with a removed parent");
5497 return NAME_NOT_FOUND;
5498 }
5499
Robert Carr578038f2018-03-09 12:25:24 -08005500 const int uid = IPCThreadState::self()->getCallingUid();
5501 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005502 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005503 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5504 return PERMISSION_DENIED;
5505 }
5506
chaviw7206d492017-11-10 16:16:12 -08005507 Rect crop(sourceCrop);
5508 if (sourceCrop.width() <= 0) {
5509 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005510 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005511 }
5512
5513 if (sourceCrop.height() <= 0) {
5514 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005515 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005516 }
5517
5518 int32_t reqWidth = crop.width() * frameScale;
5519 int32_t reqHeight = crop.height() * frameScale;
5520
Chia-I Wu20261cb2018-08-23 12:55:44 -07005521 // really small crop or frameScale
5522 if (reqWidth <= 0) {
5523 reqWidth = 1;
5524 }
5525 if (reqHeight <= 0) {
5526 reqHeight = 1;
5527 }
5528
Peiyong Lin0e003c92018-09-17 11:09:51 -07005529 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005530
Robert Carr578038f2018-03-09 12:25:24 -08005531 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005532 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5533 if (!layer->isVisible()) {
5534 return;
Robert Carr578038f2018-03-09 12:25:24 -08005535 } else if (childrenOnly && layer == parent.get()) {
5536 return;
chaviwa76b2712017-09-20 12:02:26 -07005537 }
5538 visitor(layer);
5539 });
5540 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005541 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005542}
5543
5544status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5545 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005546 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005547 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005548 bool useIdentityTransform) {
5549 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005550
Peiyong Lin0e003c92018-09-17 11:09:51 -07005551 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005552 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5553 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005554 *outBuffer =
5555 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5556 static_cast<android_pixel_format>(reqPixelFormat), 1,
5557 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005558
5559 // This mutex protects syncFd and captureResult for communication of the return values from the
5560 // main thread back to this Binder thread
5561 std::mutex captureMutex;
5562 std::condition_variable captureCondition;
5563 std::unique_lock<std::mutex> captureLock(captureMutex);
5564 int syncFd = -1;
5565 std::optional<status_t> captureResult;
5566
Robert Carr03480e22018-01-04 16:02:06 -08005567 const int uid = IPCThreadState::self()->getCallingUid();
5568 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5569
Dominik Laskowski8c001672018-05-30 16:52:06 -07005570 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005571 // If there is a refresh pending, bug out early and tell the binder thread to try again
5572 // after the refresh.
5573 if (mRefreshPending) {
5574 ATRACE_NAME("Skipping screenshot for now");
5575 std::unique_lock<std::mutex> captureLock(captureMutex);
5576 captureResult = std::make_optional<status_t>(EAGAIN);
5577 captureCondition.notify_one();
5578 return;
5579 }
5580
5581 status_t result = NO_ERROR;
5582 int fd = -1;
5583 {
5584 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005585 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005586 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5587 useIdentityTransform, forSystem, &fd);
5588 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005589 }
5590
5591 {
5592 std::unique_lock<std::mutex> captureLock(captureMutex);
5593 syncFd = fd;
5594 captureResult = std::make_optional<status_t>(result);
5595 captureCondition.notify_one();
5596 }
5597 });
5598
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005599 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005601 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005602 while (*captureResult == EAGAIN) {
5603 captureResult.reset();
5604 result = postMessageAsync(message);
5605 if (result != NO_ERROR) {
5606 return result;
5607 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005608 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 }
5610 result = *captureResult;
5611 }
5612
5613 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005614 sync_wait(syncFd, -1);
5615 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005616 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005617
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005618 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005619}
5620
chaviwa76b2712017-09-20 12:02:26 -07005621void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005622 TraverseLayersFunction traverseLayers,
Alec Mouri79108df2019-02-04 19:33:44 +00005623 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005624 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005625
Alec Mouri79108df2019-02-04 19:33:44 +00005626 auto& engine(getRenderEngine());
5627
chaviwa76b2712017-09-20 12:02:26 -07005628 const auto reqWidth = renderArea.getReqWidth();
5629 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005630 const auto sourceCrop = renderArea.getSourceCrop();
5631 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005632
Alec Mouri79108df2019-02-04 19:33:44 +00005633 engine.setOutputDataSpace(renderArea.getReqDataSpace());
5634 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005635
Alec Mouri79108df2019-02-04 19:33:44 +00005636 // make sure to clear all GL error flags
5637 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005638
Alec Mouri79108df2019-02-04 19:33:44 +00005639 // set-up our viewport
5640 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
5641 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005642
chaviw50da5042018-04-09 13:49:37 -07005643 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Alec Mouri79108df2019-02-04 19:33:44 +00005644 // redraw the screen entirely...
5645 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005646
chaviwa76b2712017-09-20 12:02:26 -07005647 traverseLayers([&](Layer* layer) {
Alec Mouri79108df2019-02-04 19:33:44 +00005648 engine.setColorTransform(layer->getColorTransform());
5649 layer->draw(renderArea, useIdentityTransform);
5650 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005651 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005652}
5653
chaviwa76b2712017-09-20 12:02:26 -07005654status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5655 TraverseLayersFunction traverseLayers,
5656 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005657 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005658 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005659 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005660 ATRACE_CALL();
5661
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005662 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005663
5664 traverseLayers([&](Layer* layer) {
5665 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5666 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005667
Robert Carr03480e22018-01-04 16:02:06 -08005668 // We allow the system server to take screenshots of secure layers for
5669 // use in situations like the Screen-rotation animation and place
5670 // the impetus on WindowManager to not persist them.
5671 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005672 ALOGW("FB is protected: PERMISSION_DENIED");
5673 return PERMISSION_DENIED;
5674 }
Alec Mouri79108df2019-02-04 19:33:44 +00005675 auto& engine(getRenderEngine());
5676
5677 // this binds the given EGLImage as a framebuffer for the
5678 // duration of this scope.
5679 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
5680 if (bufferBond.getStatus() != NO_ERROR) {
5681 ALOGE("got ANWB binding error while taking screenshot");
5682 return INVALID_OPERATION;
5683 }
5684
5685 // this will in fact render into our dequeued buffer
5686 // via an FBO, which means we didn't have to create
5687 // an EGLSurface and therefore we're not
5688 // dependent on the context's EGLConfig.
5689 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
5690
5691 base::unique_fd syncFd = engine.flush();
5692 if (syncFd < 0) {
5693 engine.finish();
5694 }
5695 *outSyncFd = syncFd.release();
5696
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005697 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005698}
5699
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005700// ---------------------------------------------------------------------------
5701
Dan Stoza412903f2017-04-27 13:42:17 -07005702void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5703 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005704}
5705
Dan Stoza412903f2017-04-27 13:42:17 -07005706void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5707 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005708}
5709
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005710void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005711 const LayerVector::Visitor& visitor) {
5712 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005713 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005714 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005715 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005716 continue;
5717 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005718 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005719 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005720 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005721 return;
5722 }
chaviwa76b2712017-09-20 12:02:26 -07005723 if (!layer->isVisible()) {
5724 return;
5725 }
5726 visitor(layer);
5727 });
5728 }
5729}
5730
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005731}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005732
Lloyd Pique074e8122018-07-26 12:57:23 -07005733
Mathias Agopian3f844832013-08-07 21:24:32 -07005734#if defined(__gl_h_)
5735#error "don't include gl/gl.h in this file"
5736#endif
5737
5738#if defined(__gl2_h_)
5739#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005740#endif