blob: 753b5ca175c6a0eded3b4559b05a66ae89a3d939 [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
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 std::optional<DisplayId> displayId;
497
498 if (id == HWC_DISPLAY_PRIMARY) {
499 displayId = getInternalDisplayId();
500 } else if (id == HWC_DISPLAY_EXTERNAL) {
501 displayId = getExternalDisplayId();
502 }
503
504 if (!displayId) {
505 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800506 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508
509 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
Ady Abraham37965d42018-11-01 13:43:32 -0700512status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
513 if (!outGetColorManagement) {
514 return BAD_VALUE;
515 }
516 *outGetColorManagement = useColorManagement;
517 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700518}
519
Lloyd Pique441d5042018-10-18 16:49:51 -0700520HWComposer& SurfaceFlinger::getHwComposer() const {
521 return mCompositionEngine->getHwComposer();
522}
523
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700524renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
525 return mCompositionEngine->getRenderEngine();
526}
527
Lloyd Pique70d91362018-10-18 16:02:55 -0700528compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
529 return *mCompositionEngine.get();
530}
531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532void SurfaceFlinger::bootFinished()
533{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
541 // wait patiently for the window manager death
542 const String16 name("window");
543 sp<IBinder> window(defaultServiceManager()->getService(name));
544 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700545 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 postMessageAsync(new LambdaMessage([this] {
569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
571 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572}
573
Dan Stoza436ccf32018-06-21 12:10:12 -0700574uint32_t SurfaceFlinger::getNewTexture() {
575 {
576 std::lock_guard lock(mTexturePoolMutex);
577 if (!mTexturePool.empty()) {
578 uint32_t name = mTexturePool.back();
579 mTexturePool.pop_back();
580 ATRACE_INT("TexturePoolSize", mTexturePool.size());
581 return name;
582 }
583
584 // The pool was too small, so increase it for the future
585 ++mTexturePoolSize;
586 }
587
588 // The pool was empty, so we need to get a new texture name directly using a
589 // blocking call to the main thread
590 uint32_t name = 0;
591 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
592 return name;
593}
594
Mathias Agopian3f844832013-08-07 21:24:32 -0700595void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700596 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700597}
598
Wei Wangf9b05ee2017-07-19 20:59:39 -0700599// Do not call property_set on main thread which will be blocked by init
600// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700602 ALOGI( "SurfaceFlinger's main thread ready to run. "
603 "Initializing graphics H/W...");
604
Ana Krulec757f63a2019-01-25 10:46:18 -0800605 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608
Dominik Laskowski83b88212018-12-11 13:34:06 -0800609 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800616 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
617 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
618 mPhaseOffsets->setRefreshRateType(
619 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700620
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800623 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700624 impl::EventThread::InterceptVSyncsCallback());
625 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800626 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mInterceptor->saveVSyncEvent(timestamp);
629 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800630
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700632 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
633 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 } else {
635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800637 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mEventThread =
639 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 impl::EventThread::InterceptVSyncsCallback(),
641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800644 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700645
646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 [this](nsecs_t timestamp) {
649 mInterceptor->saveVSyncEvent(timestamp);
650 },
651 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800652 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
654 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700657 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700658 renderEngineFeature |= (useColorManagement ?
659 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700660 renderEngineFeature |= (useContextPriority ?
661 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700662
663 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700665 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700670 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
671 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
694 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 .value_or(0),
697 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (!mVrFlinger) {
699 ALOGE("Failed to start vrflinger");
700 }
701 }
702
Lloyd Pique90c115d2018-09-18 21:39:42 -0700703 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700705
Mathias Agopian92a979a2012-08-02 18:32:23 -0700706 // initialize our drawing state
707 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700708
Andy McFadden13a082e2012-08-24 10:16:42 -0700709 // set initial conditions (e.g. unblank default device)
710 initializeDisplays();
711
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700712 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700713
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700715
716 const bool presentFenceReliable =
717 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
718 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719
720 if (mStartPropertySetThread->Start() != NO_ERROR) {
721 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723
Ana Krulec7d1d6832018-12-27 11:10:09 -0800724 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800725 mScheduler->setExpiredIdleTimerCallback([this]() {
726 mPhaseOffsets->setRefreshRateType(
727 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
728 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
729 mVsyncModulator.setPhaseOffsets(early, gl, late);
730 setRefreshRateTo(60.f /* fps */);
731 });
732 mScheduler->setResetIdleTimerCallback([this]() {
733 mPhaseOffsets->setRefreshRateType(
734 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
735 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
736 mVsyncModulator.setPhaseOffsets(early, gl, late);
737 setRefreshRateTo(90.f /* fps */);
738 });
Alec Mourifb571ea2019-01-24 18:42:10 -0800739 mRefreshRateStats =
740 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
741 *display->getId()),
742 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 }
744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700746}
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 Mutex::Autolock _l(mStateLock);
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751 char value[PROPERTY_VALUE_MAX];
752
753 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100757
758 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700759 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 const auto displayId = getPhysicalDisplayId(displayToken);
822 if (!displayId) {
823 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Steven Thomas6d8110b2017-08-31 18:24:21 -0700845 ConditionalLock _l(mStateLock,
846 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800895 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800909 info.presentationDeadline =
910 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowski075d3172018-05-24 15:50:06 -0700915 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulece588e312018-09-18 12:32:24 -0700931 if (mUseScheduler) {
932 mScheduler->getDisplayStatInfo(stats);
933 } else {
934 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
935 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
936 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return NO_ERROR;
938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
941 const auto display = getDisplayDevice(displayToken);
942 if (!display) {
943 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800944 return BAD_VALUE;
945 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
951 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800952 postMessageAsync(new LambdaMessage(
953 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 return NO_ERROR;
955}
956
957status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
958 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800959 postMessageSync(new LambdaMessage(
960 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 return NO_ERROR;
962}
963
964void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
965 Vector<DisplayInfo> configs;
966 getDisplayConfigs(displayToken, &configs);
967 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
968 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
969 return;
970 }
971
972 const auto display = getDisplayDevice(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
975 displayToken.get());
976 return;
977 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800979 ALOGW("Attempt to set active config %d for virtual display", mode);
980 return;
981 }
982 int currentDisplayPowerMode = display->getPowerMode();
983 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
984 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 return;
986 }
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 return;
992 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800993 if (mUseScheduler) {
994 mRefreshRateStats->setConfigMode(mode);
995 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700996
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997 const auto displayId = display->getId();
998 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Ana Krulec7d1d6832018-12-27 11:10:09 -08001003 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001004 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001005}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1008 Vector<ColorMode>* outColorModes) {
1009 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001010 return BAD_VALUE;
1011 }
1012
Dominik Laskowski075d3172018-05-24 15:50:06 -07001013 const auto displayId = getPhysicalDisplayId(displayToken);
1014 if (!displayId) {
1015 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001016 }
1017
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001019 {
1020 ConditionalLock _l(mStateLock,
1021 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001022 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 }
Michael Wright28f24d02016-07-12 13:30:53 -07001024 outColorModes->clear();
1025 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1026
1027 return NO_ERROR;
1028}
1029
Daniel Solomon42d04562019-01-20 21:03:19 -08001030status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1031 ui::DisplayPrimaries &primaries) {
1032 if (!displayToken) {
1033 return BAD_VALUE;
1034 }
1035
1036 // Currently we only support this API for a single internal display.
1037 if (getInternalDisplayToken() != displayToken) {
1038 return BAD_VALUE;
1039 }
1040
1041 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1042 return NO_ERROR;
1043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1046 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001047 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001048 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001049 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001050}
1051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001053 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054 Vector<ColorMode> modes;
1055 getDisplayColorModes(displayToken, &modes);
1056 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1057 if (mode < ColorMode::NATIVE || !exists) {
1058 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1059 decodeColorMode(mode).c_str(), mode, displayToken.get());
1060 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001061 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 const auto display = getDisplayDevice(displayToken);
1063 if (!display) {
1064 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 } else if (display->isVirtual()) {
1067 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1068 decodeColorMode(mode).c_str(), mode);
1069 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001070 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1071 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072 }
1073 }));
1074
Michael Wright28f24d02016-07-12 13:30:53 -07001075 return NO_ERROR;
1076}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001077
Svetoslavd85084b2014-03-20 10:28:31 -07001078status_t SurfaceFlinger::clearAnimationFrameStats() {
1079 Mutex::Autolock _l(mStateLock);
1080 mAnimFrameTracker.clearStats();
1081 return NO_ERROR;
1082}
1083
1084status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1085 Mutex::Autolock _l(mStateLock);
1086 mAnimFrameTracker.getStats(outStats);
1087 return NO_ERROR;
1088}
1089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1091 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001092 Mutex::Autolock _l(mStateLock);
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDeviceLocked(displayToken);
1095 if (!display) {
1096 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001097 return BAD_VALUE;
1098 }
1099
Peiyong Linfb069302018-04-25 14:34:31 -07001100 // At this point the DisplayDeivce should already be set up,
1101 // meaning the luminance information is already queried from
1102 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001104 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1105 capabilities.getDesiredMaxLuminance(),
1106 capabilities.getDesiredMaxAverageLuminance(),
1107 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001108
1109 return NO_ERROR;
1110}
1111
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001112status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1113 ui::PixelFormat* outFormat,
1114 ui::Dataspace* outDataspace,
1115 uint8_t* outComponentMask) const {
1116 if (!outFormat || !outDataspace || !outComponentMask) {
1117 return BAD_VALUE;
1118 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001119 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001120 if (!display || !display->getId()) {
1121 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1122 return BAD_VALUE;
1123 }
1124 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1125 outDataspace, outComponentMask);
1126}
1127
Kevin DuBois74e53772018-11-19 10:52:38 -08001128status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1129 bool enable, uint8_t componentMask,
1130 uint64_t maxFrames) const {
1131 const auto display = getDisplayDevice(displayToken);
1132 if (!display || !display->getId()) {
1133 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1134 return BAD_VALUE;
1135 }
1136
1137 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1138 componentMask, maxFrames);
1139}
1140
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001141status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1142 uint64_t maxFrames, uint64_t timestamp,
1143 DisplayedFrameStats* outStats) const {
1144 const auto display = getDisplayDevice(displayToken);
1145 if (!display || !display->getId()) {
1146 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1147 return BAD_VALUE;
1148 }
1149
1150 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1151 outStats);
1152}
1153
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001154status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1155 if (!outSupported) {
1156 return BAD_VALUE;
1157 }
1158 *outSupported = getRenderEngine().supportsProtectedContent();
1159 return NO_ERROR;
1160}
1161
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001162status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1163 bool* outIsWideColorDisplay) const {
1164 if (!displayToken || !outIsWideColorDisplay) {
1165 return BAD_VALUE;
1166 }
1167 Mutex::Autolock _l(mStateLock);
1168 const auto display = getDisplayDeviceLocked(displayToken);
1169 if (!display) {
1170 return BAD_VALUE;
1171 }
1172 *outIsWideColorDisplay = display->hasWideColorGamut();
1173 return NO_ERROR;
1174}
1175
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001177 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 if (mInjectVSyncs == enable) {
1181 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183
Dominik Laskowski83b88212018-12-11 13:34:06 -08001184 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001185
Ana Krulec98b5b242018-08-10 15:03:23 -07001186 // TODO(akrulec): Part of the Injector should be refactored, so that it
1187 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 if (enable) {
1189 ALOGV("VSync Injections enabled");
1190 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001191 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001192 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001193 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001194 impl::EventThread::InterceptVSyncsCallback(),
1195 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001197 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198 } else {
1199 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001200 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001201 }
1202
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001203 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001204 }));
1205
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001206 return NO_ERROR;
1207}
1208
1209status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001210 Mutex::Autolock _l(mStateLock);
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212 if (!mInjectVSyncs) {
1213 ALOGE("VSync Injections not enabled");
1214 return BAD_VALUE;
1215 }
1216 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1217 ALOGV("Injecting VSync inside SurfaceFlinger");
1218 mVSyncInjector->onInjectSyncEvent(when);
1219 }
1220 return NO_ERROR;
1221}
1222
Lloyd Pique755e3192018-01-31 16:46:15 -08001223status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1224 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001225 // Try to acquire a lock for 1s, fail gracefully
1226 const status_t err = mStateLock.timedLock(s2ns(1));
1227 const bool locked = (err == NO_ERROR);
1228 if (!locked) {
1229 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1230 return TIMED_OUT;
1231 }
1232
1233 outLayers->clear();
1234 mCurrentState.traverseInZOrder([&](Layer* layer) {
1235 outLayers->push_back(layer->getLayerDebugInfo());
1236 });
1237
1238 mStateLock.unlock();
1239 return NO_ERROR;
1240}
1241
Peiyong Linc6780972018-10-28 15:24:08 -07001242status_t SurfaceFlinger::getCompositionPreference(
1243 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1244 Dataspace* outWideColorGamutDataspace,
1245 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001246 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001247 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001248 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001249 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001250 return NO_ERROR;
1251}
1252
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001253// ----------------------------------------------------------------------------
1254
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001255sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1256 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001257 auto resyncCallback = makeResyncCallback([this] {
1258 Mutex::Autolock lock(mStateLock);
1259 return getVsyncPeriod();
1260 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261
Ana Krulec98b5b242018-08-10 15:03:23 -07001262 if (mUseScheduler) {
1263 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001264 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001265 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001266 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001267 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001268 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001269 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001271 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001272 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001273 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001274 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001275}
1276
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001277// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278
1279void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001280 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001281}
1282
1283void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001284 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001285}
1286
1287void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001288 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289}
1290
1291void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001292 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001293 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001294}
1295
1296status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001297 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001298 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001299}
1300
1301status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001302 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001303 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001304 if (res == NO_ERROR) {
1305 msg->wait();
1306 }
1307 return res;
1308}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001309
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001310void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001311 do {
1312 waitForEvent();
1313 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001314}
1315
Dominik Laskowski83b88212018-12-11 13:34:06 -08001316nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1317 const auto displayId = getInternalDisplayId();
1318 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1319 return 0;
1320 }
1321
1322 const auto config = getHwComposer().getActiveConfig(*displayId);
1323 return config ? config->getVsyncPeriod() : 0;
1324}
1325
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326void SurfaceFlinger::enableHardwareVsync() {
1327 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001329 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001332 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333}
1334
Dominik Laskowski83b88212018-12-11 13:34:06 -08001335void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 Mutex::Autolock _l(mHWVsyncLock);
1337
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338 if (makeAvailable) {
1339 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001340 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1341 if (mUseScheduler) {
1342 mScheduler->makeHWSyncAvailable(true);
1343 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001344 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001345 // Hardware vsync is not currently available, so abort the resync
1346 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001347 return;
1348 }
1349
Dominik Laskowski83b88212018-12-11 13:34:06 -08001350 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001351 return;
1352 }
1353
Ana Krulece588e312018-09-18 12:32:24 -07001354 if (mUseScheduler) {
1355 mScheduler->setVsyncPeriod(period);
1356 } else {
1357 mPrimaryDispSync->reset();
1358 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359
Ana Krulece588e312018-09-18 12:32:24 -07001360 if (!mPrimaryHWVsyncEnabled) {
1361 mPrimaryDispSync->beginResync();
1362 mEventControlThread->setVsyncEnabled(true);
1363 mPrimaryHWVsyncEnabled = true;
1364 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001365 }
1366}
1367
Jesse Hall948fe0c2013-10-14 12:56:09 -07001368void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 Mutex::Autolock _l(mHWVsyncLock);
1370 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001371 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001372 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 mPrimaryHWVsyncEnabled = false;
1374 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001375 if (makeUnavailable) {
1376 mHWVsyncAvailable = false;
1377 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001378}
1379
Dominik Laskowski83b88212018-12-11 13:34:06 -08001380void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001381 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001382
Dan Stoza57164302017-05-08 14:03:54 -07001383 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001384 const nsecs_t last = lastResyncTime.exchange(now);
1385
1386 if (now - last > kIgnoreDelay) {
1387 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001388 }
1389}
1390
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001391void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1392 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001393 ATRACE_NAME("SF onVsync");
1394
Steven Thomas3cfac282017-02-06 12:29:30 -08001395 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001397 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 return;
1399 }
1400
Dominik Laskowski075d3172018-05-24 15:50:06 -07001401 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001402 return;
1403 }
1404
Dominik Laskowski075d3172018-05-24 15:50:06 -07001405 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001406 // For now, we don't do anything with external display vsyncs.
1407 return;
1408 }
1409
Ana Krulece588e312018-09-18 12:32:24 -07001410 if (mUseScheduler) {
1411 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001412 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001413 bool needsHwVsync = false;
1414 { // Scope for the lock
1415 Mutex::Autolock _l(mHWVsyncLock);
1416 if (mPrimaryHWVsyncEnabled) {
1417 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1418 }
1419 }
1420
1421 if (needsHwVsync) {
1422 enableHardwareVsync();
1423 } else {
1424 disableHardwareVsync(false);
1425 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001426 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001427}
1428
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001430 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1431 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001432}
1433
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434void SurfaceFlinger::setRefreshRateTo(float newFps) {
1435 const auto displayId = getInternalDisplayId();
1436 if (!displayId || mBootStage != BootStage::FINISHED) {
1437 return;
1438 }
1439 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1440 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1441 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1442 // refresh cycle.
1443
1444 // Don't do any updating if the current fps is the same as the new one.
1445 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1446 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1447 if (currentVsyncPeriod == 0) {
1448 return;
1449 }
1450 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1451 // floating numbers.
1452 const float currentFps = 1e9 / currentVsyncPeriod;
1453 if (std::abs(currentFps - newFps) <= 1) {
1454 return;
1455 }
1456
1457 auto configs = getHwComposer().getConfigs(*displayId);
1458 for (int i = 0; i < configs.size(); i++) {
1459 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1460 if (vsyncPeriod == 0) {
1461 continue;
1462 }
1463 const float fps = 1e9 / vsyncPeriod;
1464 // TODO(b/113612090): There should be a better way at determining which config
1465 // has the right refresh rate.
1466 if (std::abs(fps - newFps) <= 1) {
1467 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1468 if (!display) return;
1469 // This is posted in async function to avoid deadlock when getDisplayDevice
1470 // requires mStateLock.
1471 setActiveConfigAsync(display, i);
1472 ATRACE_INT("FPS", newFps);
1473 }
1474 }
1475}
1476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001478 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001479 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001480 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481
Lloyd Piqueba04e622017-12-14 17:11:26 -08001482 // Ignore events that do not have the right sequenceId.
1483 if (sequenceId != getBE().mComposerSequenceId) {
1484 return;
1485 }
1486
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 // Only lock if we're not on the main thread. This function is normally
1488 // called on a hwbinder thread, but for the primary display it's called on
1489 // the main thread with the state lock already held, so don't attempt to
1490 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001491 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001494
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001495 if (std::this_thread::get_id() == mMainThreadId) {
1496 // Process all pending hot plug events immediately if we are on the main thread.
1497 processDisplayHotplugEventsLocked();
1498 }
1499
Lloyd Piqueba04e622017-12-14 17:11:26 -08001500 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001501}
1502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001504 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001505 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001507 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001509}
1510
Dominik Laskowski075d3172018-05-24 15:50:06 -07001511void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001512 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001513 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001514 if (const auto displayId = getInternalDisplayId()) {
1515 getHwComposer().setVsyncEnabled(*displayId,
1516 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1517 }
Mathias Agopian86303202012-07-24 22:46:10 -07001518}
1519
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001521void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001522 if (mUseScheduler) {
1523 mScheduler->disableHardwareVsync(true);
1524 } else {
1525 disableHardwareVsync(true);
1526 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527 // Clear the drawing state so that the logic inside of
1528 // handleTransactionLocked will fire. It will determine the delta between
1529 // mCurrentState and mDrawingState and re-apply all changes when we make the
1530 // transition.
1531 mDrawingState.displays.clear();
1532 mDisplays.clear();
1533}
1534
Steven Thomas050b2c82017-03-06 11:45:16 -08001535void SurfaceFlinger::updateVrFlinger() {
1536 if (!mVrFlinger)
1537 return;
1538 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001539 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001540 return;
1541 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 ALOGE("Vr flinger is only supported for remote hardware composer"
1545 " service connections. Ignoring request to transition to vr"
1546 " flinger.");
1547 mVrFlingerRequestsDisplay = false;
1548 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001549 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001550
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001552
Steven Thomas0123ac62018-07-12 11:32:34 -07001553 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001554 LOG_ALWAYS_FATAL_IF(!display);
1555 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001556 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1557 // called below. Clear the reference now so we don't accidentally use it
1558 // later.
1559 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001560
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001566 // Delete the current instance before creating the new one
1567 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1568 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1569 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1570 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001571
Lloyd Pique441d5042018-10-18 16:49:51 -07001572 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001573 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001574
1575 if (vrFlingerRequestsDisplay) {
1576 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001577 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001578
1579 mVisibleRegionsDirty = true;
1580 invalidateHwcGeometry();
1581
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001582 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001583 display = getDefaultDisplayDeviceLocked();
1584 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001585 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001586
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001588 const nsecs_t vsyncPeriod = getVsyncPeriod();
1589 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001590
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001591 // The present fences returned from vr_hwc are not an accurate
1592 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001593 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001594 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1595 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001596 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001597 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001598 !hasSyncFramework);
1599 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001600
Steven Thomasb02664d2017-07-26 18:48:28 -07001601 // Use phase of 0 since phase is not known.
1602 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001603 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001604 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001605
Dominik Laskowski83b88212018-12-11 13:34:06 -08001606 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001607
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001608 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001610}
1611
Mathias Agopian4fec8732012-06-29 14:12:52 -07001612void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001613 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001614 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001615 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001616 if (mUseScheduler) {
1617 // This call is made each time SF wakes up and creates a new frame.
1618 mScheduler->incrementFrameCounter();
1619 }
Dan Stoza50182882016-07-08 12:02:20 -07001620 bool frameMissed = !mHadClientComposition &&
1621 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 (mPreviousPresentFence->getSignalTime() ==
1623 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001624 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001625 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001626 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001627 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001628 if (mPropagateBackpressure) {
1629 signalLayerUpdate();
1630 break;
1631 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001632 }
Dan Stoza50182882016-07-08 12:02:20 -07001633
Steven Thomas050b2c82017-03-06 11:45:16 -08001634 // Now that we're going to make it to the handleMessageTransaction()
1635 // call below it's safe to call updateVrFlinger(), which will
1636 // potentially trigger a display handoff.
1637 updateVrFlinger();
1638
Dan Stoza6b9454d2014-11-07 16:00:59 -08001639 bool refreshNeeded = handleMessageTransaction();
1640 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001641
1642 updateCursorAsync();
1643 updateInputFlinger();
1644
Dan Stoza58784442014-12-02 16:58:17 -08001645 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001646 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001647 // Signal a refresh if a transaction modified the window state,
1648 // a new buffer was latched, or if HWC has requested a full
1649 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001650 signalRefresh();
1651 }
1652 break;
1653 }
1654 case MessageQueue::REFRESH: {
1655 handleMessageRefresh();
1656 break;
1657 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001658 }
1659}
1660
Dan Stoza6b9454d2014-11-07 16:00:59 -08001661bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001662 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001663
1664 // Apply any ready transactions in the queues if there are still transactions that have not been
1665 // applied, wake up during the next vsync period and check again
1666 bool transactionNeeded = false;
1667 if (!flushTransactionQueues()) {
1668 transactionNeeded = true;
1669 }
1670
Mathias Agopian4fec8732012-06-29 14:12:52 -07001671 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001672 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001674
1675 if (transactionNeeded) {
1676 setTransactionFlags(eTransactionNeeded);
1677 }
1678
1679 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001680}
1681
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001684
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001685 mRefreshPending = false;
1686
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001687 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001688 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001689 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001690 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 for (const auto& [token, display] : mDisplays) {
1692 beginFrame(display);
1693 prepareFrame(display);
1694 doDebugFlashRegions(display, repaintEverything);
1695 doComposition(display, repaintEverything);
1696 }
1697
Adrian Roos1e1a1282017-11-01 19:05:31 +01001698 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001699 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700
1701 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001702 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001703
Dan Stozabfbffeb2016-07-21 14:49:33 -07001704 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001705 for (const auto& [token, displayDevice] : mDisplays) {
1706 auto display = displayDevice->getCompositionDisplay();
1707 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001708 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001709 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001710 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711
Alec Mouri86770e52018-09-24 22:40:58 +00001712 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001713 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001714 if (mHadClientComposition) {
1715 base::unique_fd flushFence(getRenderEngine().flush());
1716 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1717 getBE().flushFence = new Fence(std::move(flushFence));
1718 } else {
1719 // Cleanup for hygiene.
1720 getBE().flushFence = Fence::NO_FENCE;
1721 }
1722 }
1723
Jorim Jaggi90535212018-05-23 23:44:06 +02001724 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001725
David Sodman7e4ae112018-02-09 15:02:28 -08001726 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001727 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001728 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001729 compositionInfo.hwc.hwcLayer = nullptr;
1730 }
David Sodmanba340492018-08-05 21:51:33 -07001731 }
David Sodman7e4ae112018-02-09 15:02:28 -08001732
1733 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001734}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001735
David Sodmanfa9b2af2017-12-24 13:28:59 -08001736
1737bool SurfaceFlinger::handleMessageInvalidate() {
1738 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001739 bool refreshNeeded = handlePageFlip();
1740
1741 for (auto& layer : mLayersPendingRefresh) {
1742 Region visibleReg;
1743 visibleReg.set(layer->computeScreenBounds());
1744 invalidateLayerStack(layer, visibleReg);
1745 }
1746 mLayersPendingRefresh.clear();
1747 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001748}
1749
David Sodman79bba0e2018-08-05 18:07:49 -07001750void SurfaceFlinger::calculateWorkingSet() {
1751 ATRACE_CALL();
1752 ALOGV(__FUNCTION__);
1753
David Sodman79bba0e2018-08-05 18:07:49 -07001754 // build the h/w work list
1755 if (CC_UNLIKELY(mGeometryInvalid)) {
1756 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001757 for (const auto& [token, displayDevice] : mDisplays) {
1758 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001759 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760 if (!displayId) {
1761 continue;
1762 }
David Sodman79bba0e2018-08-05 18:07:49 -07001763
Lloyd Pique32cbe282018-10-19 13:09:22 -07001764 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001765 for (size_t i = 0; i < currentLayers.size(); i++) {
1766 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001767
Dominik Laskowski075d3172018-05-24 15:50:06 -07001768 if (!layer->hasHwcLayer(*displayId)) {
1769 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1770 layer->forceClientComposition(*displayId);
1771 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001772 }
1773 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774
Lloyd Pique32cbe282018-10-19 13:09:22 -07001775 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 if (mDebugDisableHWC || mDebugRegion) {
1777 layer->forceClientComposition(*displayId);
1778 }
David Sodman79bba0e2018-08-05 18:07:49 -07001779 }
1780 }
1781 }
1782
1783 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001784 for (const auto& [token, displayDevice] : mDisplays) {
1785 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001786 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001787 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001788 continue;
1789 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001790 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001791
1792 if (mDrawingState.colorMatrixChanged) {
1793 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001794 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001796 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001798 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1799 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001800 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001802 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1803 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001804 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 }
1807
Peiyong Lind3788632018-09-18 16:01:31 -07001808 // TODO(b/111562338) remove when composer 2.3 is shipped.
1809 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001810 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001811 }
1812
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001813 if (layer->getRoundedCornerState().radius > 0.0f) {
1814 layer->forceClientComposition(*displayId);
1815 }
1816
Dominik Laskowski075d3172018-05-24 15:50:06 -07001817 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001818 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001819 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 continue;
1821 }
1822
Lloyd Pique32cbe282018-10-19 13:09:22 -07001823 const auto& displayState = display->getState();
1824 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1825 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001826 }
1827
Peiyong Lin13effd12018-07-24 17:01:47 -07001828 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001829 ColorMode colorMode;
1830 Dataspace dataSpace;
1831 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001832 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001834 }
1835 }
1836
1837 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001838
1839 for (const auto& [token, display] : mDisplays) {
1840 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001841 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001842 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001843
1844 if (displayId) {
1845 if (!layer->setHwcLayer(*displayId)) {
1846 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1847 }
1848 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001849 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850
Dominik Laskowski05275f12018-11-01 15:03:24 -07001851 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001852 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1853 }
1854 }
David Sodman79bba0e2018-08-05 18:07:49 -07001855}
1856
Lloyd Pique32cbe282018-10-19 13:09:22 -07001857void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1858 bool repaintEverything) {
1859 auto display = displayDevice->getCompositionDisplay();
1860 const auto& displayState = display->getState();
1861
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862 // is debugging enabled
1863 if (CC_LIKELY(!mDebugRegion))
1864 return;
1865
Lloyd Pique32cbe282018-10-19 13:09:22 -07001866 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001867 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00001868 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001869 if (!dirtyRegion.isEmpty()) {
1870 // redraw the whole screen
Alec Mouri79108df2019-02-04 19:33:44 +00001871 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872
Alec Mouri79108df2019-02-04 19:33:44 +00001873 // and draw the dirty region
1874 auto& engine(getRenderEngine());
1875 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
1876
1877 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 }
1879 }
1880
Lloyd Pique32cbe282018-10-19 13:09:22 -07001881 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882
1883 if (mDebugRegion > 1) {
1884 usleep(mDebugRegion * 1000);
1885 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001886
Lloyd Pique32cbe282018-10-19 13:09:22 -07001887 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888}
1889
Adrian Roos1e1a1282017-11-01 19:05:31 +01001890void SurfaceFlinger::doTracing(const char* where) {
1891 ATRACE_CALL();
1892 ATRACE_NAME(where);
1893 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001894 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001895 }
1896}
1897
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001898void SurfaceFlinger::logLayerStats() {
1899 ATRACE_CALL();
1900 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001901 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001902 if (display->isPrimary()) {
1903 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001904 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001905 }
1906 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001907
1908 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001909 }
1910}
1911
David Sodman2b406362017-12-15 13:33:47 -08001912void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 ATRACE_CALL();
1915 ALOGV("preComposition");
1916
David Sodman2b406362017-12-15 13:33:47 -08001917 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1918
Mathias Agopiancd60f992012-08-16 16:28:27 -07001919 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001920 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001921 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001922 needExtraInvalidate = true;
1923 }
Robert Carr2047fae2016-11-28 14:09:09 -08001924 });
1925
Mathias Agopiancd60f992012-08-16 16:28:27 -07001926 if (needExtraInvalidate) {
1927 signalLayerUpdate();
1928 }
1929}
1930
Ana Krulece588e312018-09-18 12:32:24 -07001931void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1932 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001933 // Update queue of past composite+present times and determine the
1934 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001935 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001937 while (!getBE().mCompositePresentTimes.empty()) {
1938 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 // Cached values should have been updated before calling this method,
1940 // which helps avoid duplicate syscalls.
1941 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1942 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1943 break;
1944 }
1945 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 }
1948
1949 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001950 while (getBE().mCompositePresentTimes.size() > 16) {
1951 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952 }
1953
Ana Krulece588e312018-09-18 12:32:24 -07001954 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001955}
1956
Ana Krulece588e312018-09-18 12:32:24 -07001957void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1958 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959 // Integer division and modulo round toward 0 not -inf, so we need to
1960 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001961 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1962 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1963 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964
Ana Krulec757f63a2019-01-25 10:46:18 -08001965 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001966 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001967 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001968 }
1969
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // Snap the latency to a value that removes scheduling jitter from the
1971 // composition and present times, which often have >1ms of jitter.
1972 // Reducing jitter is important if an app attempts to extrapolate
1973 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001974 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001976 nsecs_t bias = stats.vsyncPeriod / 2;
1977 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1978 nsecs_t snappedCompositeToPresentLatency =
1979 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980
David Sodman99974d22017-11-28 12:04:33 -08001981 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001982 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1983 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001984 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985}
1986
Ady Abraham8164d482019-01-11 14:47:59 -08001987// debug patch for b/119477596 - add stack guards to catch stack
1988// corruptions and disable clang optimizations.
1989// The code below is temporary and planned to be removed once stack
1990// corruptions are found.
1991#pragma clang optimize off
1992class StackGuard {
1993public:
1994 StackGuard(const char* name, const char* func, int line) {
1995 guarders.reserve(MIN_CAPACITY);
1996 guarders.push_back({this, name, func, line});
1997 validate();
1998 }
1999 ~StackGuard() {
2000 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2001 if (i->guard == this) {
2002 guarders.erase(i);
2003 break;
2004 }
2005 }
2006 }
2007
2008 static void validate() {
2009 for (const auto& guard : guarders) {
2010 if (guard.guard->cookie != COOKIE_VALUE) {
2011 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2012 CallStack stack(LOG_TAG);
2013 abort();
2014 }
2015 }
2016 }
2017
2018private:
2019 uint64_t cookie = COOKIE_VALUE;
2020 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2021 static constexpr size_t MIN_CAPACITY = 16;
2022
2023 struct GuarderElement {
2024 StackGuard* guard;
2025 const char* name;
2026 const char* func;
2027 int line;
2028 };
2029
2030 static std::vector<GuarderElement> guarders;
2031};
2032std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2033
2034#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2035
2036#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002037void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002038{
Ady Abraham8164d482019-01-11 14:47:59 -08002039 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ATRACE_CALL();
2041 ALOGV("postComposition");
2042
Brian Anderson3546a3f2016-07-14 11:51:14 -07002043 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002044 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002045 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002046 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002047 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002048 }
Ady Abraham8164d482019-01-11 14:47:59 -08002049 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002050
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002051 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002052 const auto displayDevice = getDefaultDisplayDeviceLocked();
2053 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002054
David Sodman73beded2017-11-15 11:56:06 -08002055 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002057 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2058
Lloyd Pique32cbe282018-10-19 13:09:22 -07002059 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002060 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002061 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2062 ->getRenderSurface()
2063 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002064 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065 } else {
2066 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2067 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068
Ady Abraham8164d482019-01-11 14:47:59 -08002069 ASSERT_ON_STACK_GUARD();
2070
David Sodman73beded2017-11-15 11:56:06 -08002071 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002072 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2073 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002074 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002075 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002076 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002077
Ana Krulece588e312018-09-18 12:32:24 -07002078 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002079 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002080 if (mUseScheduler) {
2081 mScheduler->getDisplayStatInfo(&stats);
2082 } else {
2083 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2084 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2085 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002086
Ady Abraham8164d482019-01-11 14:47:59 -08002087 ASSERT_ON_STACK_GUARD();
2088
David Sodman2b406362017-12-15 13:33:47 -08002089 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002090 // when we started doing work for this frame, but that should be okay
2091 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002092 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002093 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002094 DEFINE_STACK_GUARD(compositorTiming);
2095
Brian Andersond0010582017-03-07 13:20:31 -08002096 {
David Sodman99974d22017-11-28 12:04:33 -08002097 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002098 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002099 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002100
2101 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002102 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002103
Robert Carr2047fae2016-11-28 14:09:09 -08002104 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002105 bool frameLatched =
2106 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2107 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002108 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002109 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002110 recordBufferingStats(layer->getName().string(),
2111 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002112 }
Ady Abraham8164d482019-01-11 14:47:59 -08002113 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002114 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002115
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002116 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002117 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002118 if (mUseScheduler) {
2119 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002121 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002122 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2123 enableHardwareVsync();
2124 } else {
2125 disableHardwareVsync(false);
2126 }
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002128 }
2129 }
2130
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002131 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002132 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2133 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002134 if (mUseScheduler) {
2135 mScheduler->enableHardwareVsync();
2136 } else {
2137 enableHardwareVsync();
2138 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002139 }
2140 }
2141
Ady Abraham8164d482019-01-11 14:47:59 -08002142 ASSERT_ON_STACK_GUARD();
2143
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002144 if (mAnimCompositionPending) {
2145 mAnimCompositionPending = false;
2146
Brian Anderson4e606e32017-03-16 15:34:57 -07002147 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002148 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002149 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002150
2151 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002152 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002153 // The HWC doesn't support present fences, so use the refresh
2154 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 const nsecs_t presentTime =
2156 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002157 DEFINE_STACK_GUARD(presentTime);
2158
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002159 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002160 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 }
2162 mAnimFrameTracker.advanceFrame();
2163 }
Dan Stozab90cf072015-03-05 11:05:59 -08002164
Ady Abraham8164d482019-01-11 14:47:59 -08002165 ASSERT_ON_STACK_GUARD();
2166
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002167 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002168 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002169 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002170 }
2171
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
2173
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002174 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002175
Ady Abraham8164d482019-01-11 14:47:59 -08002176 ASSERT_ON_STACK_GUARD();
2177
Lloyd Pique32cbe282018-10-19 13:09:22 -07002178 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2179 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002180 return;
2181 }
2182
2183 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002184 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002185 if (mHasPoweredOff) {
2186 mHasPoweredOff = false;
2187 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002188 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002189 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002190 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002191 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002192 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2193 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002194 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002195 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002196 }
David Sodman4a36e932017-11-07 14:29:47 -08002197 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002198
2199 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002200 }
David Sodman4a36e932017-11-07 14:29:47 -08002201 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002202 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002203
2204 {
2205 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002206 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002207 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002208 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002209 if (refillCount > 0) {
2210 const size_t offset = mTexturePool.size();
2211 mTexturePool.resize(mTexturePoolSize);
2212 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2213 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2214 }
Ady Abraham8164d482019-01-11 14:47:59 -08002215 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002216 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002217
Marissa Wallfda30bb2018-10-12 11:34:28 -07002218 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002219 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002220
2221 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002222}
Ady Abraham8164d482019-01-11 14:47:59 -08002223#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002224
2225void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 ATRACE_CALL();
2227 ALOGV("rebuildLayerStacks");
2228
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002229 // We need to clear these out now as these may be holding on to a
2230 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2231 // also holds a reference. When the set of visible layers is recomputed,
2232 // some layers may be destroyed if the only thing keeping them alive was
2233 // that list of visible layers associated with each display. The layer
2234 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2235 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2236 for (const auto& [token, display] : mDisplays) {
2237 getBE().mCompositionInfo[token].clear();
2238 }
2239
Mathias Agopiancd60f992012-08-16 16:28:27 -07002240 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002241 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002242 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002243 mVisibleRegionsDirty = false;
2244 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002245
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002246 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002247 const auto& displayDevice = pair.second;
2248 auto display = displayDevice->getCompositionDisplay();
2249 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002250 Region opaqueRegion;
2251 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002252 compositionengine::Output::OutputLayers layersSortedByZ;
2253 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002254 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const ui::Transform& tr = displayState.transform;
2256 const Rect bounds = displayState.bounds;
2257 if (displayState.isEnabled) {
2258 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002259
Jeff Sharkey76488112017-02-27 14:15:18 -07002260 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002261 auto compositionLayer = layer->getCompositionLayer();
2262 if (compositionLayer == nullptr) {
2263 return;
2264 }
2265
Chia-I Wu83806892017-11-16 10:50:20 -08002266 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002267 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002268 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2269 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2270
Lloyd Piqueef36b002019-01-23 17:52:04 -08002271 if (display->belongsInOutput(layer->getLayerStack(),
2272 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002273 Region drawRegion(tr.transform(
2274 layer->visibleNonTransparentRegion));
2275 drawRegion.andSelf(bounds);
2276 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002277 layersSortedByZ.emplace_back(
2278 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2279 layerFE));
2280
2281 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002282 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002283 // Clear out the HWC layer if this layer was
2284 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002286 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002287 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002288 // WM changes display->layerStack upon sleep/awake.
2289 // Here we make sure we delete the HWC layers even if
2290 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002291 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002292 }
2293
2294 // If a layer is not going to get a release fence because
2295 // it is invisible, but it is also going to release its
2296 // old buffer, add it to the list of layers needing
2297 // fences.
2298 if (hwcLayerDestroyed) {
2299 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2300 mLayersWithQueuedFrames.cend(), layer);
2301 if (found != mLayersWithQueuedFrames.cend()) {
2302 layersNeedingFences.add(layer);
2303 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002304 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002305 });
2306 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002307
2308 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2309
2310 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002311 displayDevice->setLayersNeedingFences(layersNeedingFences);
2312
2313 Region undefinedRegion{bounds};
2314 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2315
2316 display->editState().undefinedRegion = undefinedRegion;
2317 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002318 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002319 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002320}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002321
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002324// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002326// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327// The returned HDR data space is one of
2328// - Dataspace::UNKNOWN
2329// - Dataspace::BT2020_HLG
2330// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2332 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002333 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334 *outHdrDataSpace = Dataspace::UNKNOWN;
2335
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002337 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 case Dataspace::V0_SCRGB:
2339 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002340 case Dataspace::BT2020:
2341 case Dataspace::BT2020_ITU:
2342 case Dataspace::BT2020_LINEAR:
2343 case Dataspace::DISPLAY_BT2020:
2344 bestDataSpace = Dataspace::DISPLAY_BT2020;
2345 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002347 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002348 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002349 case Dataspace::BT2020_PQ:
2350 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002352 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002353 case Dataspace::BT2020_HLG:
2354 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002355 // When there's mixed PQ content and HLG content, we set the HDR
2356 // data space to be BT2020_PQ and convert HLG to PQ.
2357 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2358 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002359 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360 break;
2361 default:
2362 break;
2363 }
Romain Guy54f154a2017-10-24 21:40:32 +01002364 }
2365
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002367}
2368
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002369// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2371 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002372 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2373 *outMode = ColorMode::NATIVE;
2374 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002375 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002377 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002378
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002382 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2383
Peiyong Lindfde5112018-06-05 10:58:41 -07002384 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002385 const bool isHdr =
2386 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002387 if (isHdr) {
2388 bestDataSpace = hdrDataSpace;
2389 }
2390
Chia-I Wu0d711262018-05-21 15:19:35 -07002391 RenderIntent intent;
2392 switch (mDisplayColorSetting) {
2393 case DisplayColorSetting::MANAGED:
2394 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002395 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002396 break;
2397 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002398 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002399 break;
2400 default: // vendor display color setting
2401 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2402 break;
2403 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002404
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002405 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002406}
2407
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2409 auto display = displayDevice->getCompositionDisplay();
2410 const auto& displayState = display->getState();
2411
Alec Mouri79108df2019-02-04 19:33:44 +00002412 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2414 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002415
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 // If nothing has changed (!dirty), don't recompose.
2417 // If something changed, but we don't currently have any visible layers,
2418 // and didn't when we last did a composition, then skip it this time.
2419 // The second rule does two things:
2420 // - When all layers are removed from a display, we'll emit one black
2421 // frame, then nothing more until we get new layers.
2422 // - When a display is created with a private layer stack, we won't
2423 // emit any black frames until a layer is added to the layer stack.
2424 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002425
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 const char flagPrefix[] = {'-', '+'};
2427 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2429 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2430 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2431 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002432
Lloyd Pique31cb2942018-10-19 17:23:03 -07002433 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002434
David Sodmanfa9b2af2017-12-24 13:28:59 -08002435 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002437 }
2438}
2439
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2441 auto display = displayDevice->getCompositionDisplay();
2442 const auto& displayState = display->getState();
2443
2444 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445 return;
David Sodman2b406362017-12-15 13:33:47 -08002446 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447
Lloyd Pique31cb2942018-10-19 17:23:03 -07002448 status_t result = display->getRenderSurface()->prepareFrame(
2449 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002452}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002453
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002455 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 ALOGV("doComposition");
2457
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 auto display = displayDevice->getCompositionDisplay();
2459 const auto& displayState = display->getState();
2460
2461 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002462 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00002463 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002464
David Sodmanfa9b2af2017-12-24 13:28:59 -08002465 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002467
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002469 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002470 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002472}
2473
David Sodmanfa9b2af2017-12-24 13:28:59 -08002474void SurfaceFlinger::postFrame()
2475{
2476 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002477 const auto display = getDefaultDisplayDeviceLocked();
2478 if (display && getHwComposer().isConnected(*display->getId())) {
2479 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002480 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2481 logFrameStats();
2482 }
2483 }
2484}
2485
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002487 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002489
Lloyd Pique32cbe282018-10-19 13:09:22 -07002490 auto display = displayDevice->getCompositionDisplay();
2491 const auto& displayState = display->getState();
2492 const auto displayId = display->getId();
2493
David Sodmanfa9b2af2017-12-24 13:28:59 -08002494 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002495
Lloyd Pique32cbe282018-10-19 13:09:22 -07002496 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 if (displayId) {
2498 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002499 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002500 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002501 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002502 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002503
Chia-I Wu7b549592017-11-15 09:14:57 -08002504 // The layer buffer from the previous frame (if any) is released
2505 // by HWC only when the release fence from this frame (if any) is
2506 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 if (displayId && layer->hasHwcLayer(*displayId)) {
2508 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2509 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002510 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002511
2512 // If the layer was client composited in the previous frame, we
2513 // need to merge with the previous client target acquire fence.
2514 // Since we do not track that, always merge with the current
2515 // client target acquire fence when it is available, even though
2516 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002517 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002518 releaseFence =
2519 Fence::merge("LayerRelease", releaseFence,
2520 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002521 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002522
David Sodman15094112018-10-11 09:39:37 -07002523 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002524 }
Chia-I Wu83806892017-11-16 10:50:20 -08002525
2526 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002528 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002529 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002531 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002533 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002534 }
2535 }
2536
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 if (displayId) {
2538 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002539 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541}
2542
Mathias Agopian87baae12012-07-31 12:38:26 -07002543void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544{
Mathias Agopian841cde52012-03-01 15:44:37 -08002545 ATRACE_CALL();
2546
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002547 // here we keep a copy of the drawing state (that is the state that's
2548 // going to be overwritten by handleTransactionLocked()) outside of
2549 // mStateLock so that the side-effects of the State assignment
2550 // don't happen with mStateLock held (which can cause deadlocks).
2551 State drawingState(mDrawingState);
2552
Mathias Agopianca4d3602011-05-19 15:38:14 -07002553 Mutex::Autolock _l(mStateLock);
2554 const nsecs_t now = systemTime();
2555 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556
Mathias Agopianca4d3602011-05-19 15:38:14 -07002557 // Here we're guaranteed that some transaction flags are set
2558 // so we can call handleTransactionLocked() unconditionally.
2559 // We call getTransactionFlags(), which will also clear the flags,
2560 // with mStateLock held to guarantee that mCurrentState won't change
2561 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002562
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002563 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002564 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002565 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002566
Mathias Agopianca4d3602011-05-19 15:38:14 -07002567 mLastTransactionTime = systemTime() - now;
2568 mDebugInTransaction = 0;
2569 invalidateHwcGeometry();
2570 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002571}
2572
Lloyd Piqueba04e622017-12-14 17:11:26 -08002573void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2574 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 const std::optional<DisplayIdentificationInfo> info =
2576 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002577
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002579 continue;
2580 }
2581
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002584 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 mPhysicalDisplayTokens[info->id] = new BBinder();
2586 DisplayDeviceState state;
2587 state.displayId = info->id;
2588 state.isSecure = true; // All physical displays are currently considered secure.
2589 state.displayName = info->name;
2590 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2591 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002592 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002593 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002594 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2597 if (index >= 0) {
2598 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2599 mInterceptor->saveDisplayDeletion(state.sequenceId);
2600 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002601 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603 }
2604
2605 processDisplayChangesLocked();
2606 }
2607
2608 mPendingHotplugEvents.clear();
2609}
2610
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002611void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2612 bool connected) {
2613 if (mUseScheduler) {
2614 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2615 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2616 } else {
2617 mEventThread->onHotplugReceived(displayType, connected);
2618 mSFEventThread->onHotplugReceived(displayType, connected);
2619 }
2620}
2621
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002624 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 const sp<IGraphicBufferProducer>& producer) {
2626 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002627 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 creationArgs.isSecure = state.isSecure;
2630 creationArgs.displaySurface = dispSurface;
2631 creationArgs.hasWideColorGamut = false;
2632 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002633
Dominik Laskowski075d3172018-05-24 15:50:06 -07002634 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2635 creationArgs.isPrimary = isInternalDisplay;
2636
2637 if (useColorManagement && displayId) {
2638 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002640 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002641 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002643
Dominik Laskowski7e045462018-05-30 13:02:02 -07002644 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 }
tangrobin6753a022018-08-10 10:58:54 +08002648 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 if (displayId) {
2651 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002652 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002653 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002654 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655
Lloyd Pique90c115d2018-09-18 21:39:42 -07002656 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002658 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660 // Make sure that composition can never be stalled by a virtual display
2661 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002662 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002663 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2665 }
2666
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 creationArgs.displayInstallOrientation =
2668 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002669
Lloyd Pique99d3da52018-01-22 17:48:03 -08002670 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002671 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672
Lloyd Pique90c115d2018-09-18 21:39:42 -07002673 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674
2675 if (maxFrameBufferAcquiredBuffers >= 3) {
2676 nativeWindowSurface->preallocateBuffers();
2677 }
2678
2679 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002680 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002681 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002682 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002683 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002685 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2686 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002687 if (!state.isVirtual()) {
2688 LOG_ALWAYS_FATAL_IF(!displayId);
2689 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002690 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002691
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 display->setLayerStack(state.layerStack);
2693 display->setProjection(state.orientation, state.viewport, state.frame);
2694 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002695
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002697}
2698
Lloyd Pique347200f2017-12-14 17:00:15 -08002699void SurfaceFlinger::processDisplayChangesLocked() {
2700 // here we take advantage of Vector's copy-on-write semantics to
2701 // improve performance by skipping the transaction entirely when
2702 // know that the lists are identical
2703 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2704 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2705 if (!curr.isIdenticalTo(draw)) {
2706 mVisibleRegionsDirty = true;
2707 const size_t cc = curr.size();
2708 size_t dc = draw.size();
2709
2710 // find the displays that were removed
2711 // (ie: in drawing state but not in current state)
2712 // also handle displays that changed
2713 // (ie: displays that are in both lists)
2714 for (size_t i = 0; i < dc;) {
2715 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2716 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 // Save display IDs before disconnecting.
2718 const auto internalDisplayId = getInternalDisplayId();
2719 const auto externalDisplayId = getExternalDisplayId();
2720
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002723 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002726 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002728 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002729 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 } else {
2732 // this display is in both lists. see if something changed.
2733 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2736 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2737 if (state_binder != draw_binder) {
2738 // changing the surface is like destroying and
2739 // recreating the DisplayDevice, so we just remove it
2740 // from the drawing state, so that it get re-added
2741 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002742 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002743 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002745 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 mDrawingState.displays.removeItemsAt(i);
2747 dc--;
2748 // at this point we must loop to the next item
2749 continue;
2750 }
2751
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002752 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002753 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 }
2756 if ((state.orientation != draw[i].orientation) ||
2757 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 }
2760 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 }
2763 }
2764 }
2765 ++i;
2766 }
2767
2768 // find displays that were added
2769 // (ie: in current state but not in drawing state)
2770 for (size_t i = 0; i < cc; i++) {
2771 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2772 const DisplayDeviceState& state(curr[i]);
2773
Lloyd Pique542307f2018-10-19 13:24:08 -07002774 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 sp<IGraphicBufferProducer> producer;
2776 sp<IGraphicBufferProducer> bqProducer;
2777 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002778 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002779
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002781 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002782 // Virtual displays without a surface are dormant:
2783 // they have external state (layer stack, projection,
2784 // etc.) but no internal state (i.e. a DisplayDevice).
2785 if (state.surface != nullptr) {
2786 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002787 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 int width = 0;
2789 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2790 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2791 int height = 0;
2792 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2793 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2794 int intFormat = 0;
2795 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2796 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002797 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002798
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799 displayId =
2800 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 }
2802
2803 // TODO: Plumb requested format back up to consumer
2804
2805 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002806 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 bqProducer, bqConsumer,
2808 state.displayName);
2809
2810 dispSurface = vds;
2811 producer = vds;
2812 }
2813 } else {
2814 ALOGE_IF(state.surface != nullptr,
2815 "adding a supported display, but rendering "
2816 "surface is provided (%p), ignoring it",
2817 state.surface.get());
2818
Dominik Laskowski075d3172018-05-24 15:50:06 -07002819 displayId = state.displayId;
2820 LOG_ALWAYS_FATAL_IF(!displayId);
2821 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 producer = bqProducer;
2823 }
2824
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002825 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002826 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002827 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002828 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002830 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002831 LOG_ALWAYS_FATAL_IF(!displayId);
2832
2833 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002834 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002835 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002836 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002837 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 }
2839 }
2840 }
2841 }
2842 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002843
2844 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002845}
2846
Mathias Agopian87baae12012-07-31 12:38:26 -07002847void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002848{
Dan Stoza7dde5992015-05-22 09:51:44 -07002849 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002850 mCurrentState.traverseInZOrder([](Layer* layer) {
2851 layer->notifyAvailableFrames();
2852 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 /*
2855 * Traversal of the children
2856 * (perform the transaction for each of them if needed)
2857 */
2858
Mathias Agopian3559b072012-08-15 13:46:03 -07002859 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002860 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002862 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863
2864 const uint32_t flags = layer->doTransaction(0);
2865 if (flags & Layer::eVisibleRegion)
2866 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002867
2868 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002869 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002870 }
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 }
2873
2874 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002875 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 */
2877
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002879 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002880 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002881 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002883 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002884 // The transform hint might have changed for some layers
2885 // (either because a display has changed, or because a layer
2886 // as changed).
2887 //
2888 // Walk through all the layers in currentLayers,
2889 // and update their transform hint.
2890 //
2891 // If a layer is visible only on a single display, then that
2892 // display is used to calculate the hint, otherwise we use the
2893 // default display.
2894 //
2895 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2896 // the hint is set before we acquire a buffer from the surface texture.
2897 //
2898 // NOTE: layer transactions have taken place already, so we use their
2899 // drawing state. However, SurfaceFlinger's own transaction has not
2900 // happened yet, so we must use the current state layer list
2901 // (soon to become the drawing state list).
2902 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002904 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002905 bool first = true;
2906 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002907 // NOTE: we rely on the fact that layers are sorted by
2908 // layerStack first (so we don't have to traverse the list
2909 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002911 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002912 currentlayerStack = layerStack;
2913 // figure out if this layerstack is mirrored
2914 // (more than one display) if so, pick the default display,
2915 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 hintDisplay = nullptr;
2917 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002918 if (display->getCompositionDisplay()
2919 ->belongsInOutput(layer->getLayerStack(),
2920 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002921 if (hintDisplay) {
2922 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002923 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002924 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002926 }
2927 }
2928 }
2929 }
Chet Haase91d25932013-04-11 15:24:55 -07002930
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002931 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002932 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2933 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002934
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002935 // could be null when this layer is using a layerStack
2936 // that is not visible on any display. Also can occur at
2937 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002938 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002939 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002940
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002941 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002942 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002943 if (hintDisplay) {
2944 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002945 }
Robert Carr2047fae2016-11-28 14:09:09 -08002946
2947 first = false;
2948 });
Mathias Agopian84300952012-11-21 16:02:13 -08002949 }
2950
2951
Mathias Agopian3559b072012-08-15 13:46:03 -07002952 /*
2953 * Perform our own transaction if needed
2954 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955
2956 if (mLayersAdded) {
2957 mLayersAdded = false;
2958 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002959 mVisibleRegionsDirty = true;
2960 }
2961
2962 // some layers might have been removed, so
2963 // we need to update the regions they're exposing.
2964 if (mLayersRemoved) {
2965 mLayersRemoved = false;
2966 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002967 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002969 // this layer is not visible anymore
2970 // TODO: we could traverse the tree from front to back and
2971 // compute the actual visible region
2972 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002973 Region visibleReg;
2974 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002975 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002976 }
Robert Carr2047fae2016-11-28 14:09:09 -08002977 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 }
2979
2980 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002981}
2982
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002983void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002984 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002985 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002986 return;
2987 }
2988
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002989 if (mVisibleRegionsDirty || mInputInfoChanged) {
2990 mInputInfoChanged = false;
2991 updateInputWindowInfo();
2992 }
2993
2994 executeInputWindowCommands();
2995}
2996
2997void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002998 Vector<InputWindowInfo> inputHandles;
2999
3000 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3001 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003002 // When calculating the screen bounds we ignore the transparent region since it may
3003 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003004 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003005 }
3006 });
3007 mInputFlinger->setInputWindows(inputHandles);
3008}
3009
chaviwfbe5d9c2018-12-26 12:23:37 -08003010void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003011 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3012 if (transferTouchFocusCommand.fromToken != nullptr &&
3013 transferTouchFocusCommand.toToken != nullptr &&
3014 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3015 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3016 transferTouchFocusCommand.toToken);
3017 }
3018 }
3019
3020 mInputWindowCommands.clear();
3021}
3022
Riley Andrews03414a12014-07-01 14:22:59 -07003023void SurfaceFlinger::updateCursorAsync()
3024{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003025 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003026 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003027 continue;
3028 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3031 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003032 }
3033 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003034}
3035
chaviw61626f22018-11-15 16:26:27 -08003036void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3037 if (layer->hasReadyFrame()) {
3038 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3039 if (layer->shouldPresentNow(expectedPresentTime)) {
3040 bool ignored = false;
3041 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3042 }
3043 }
3044 layer->releasePendingBuffer(systemTime());
3045}
3046
Mathias Agopian4fec8732012-06-29 14:12:52 -07003047void SurfaceFlinger::commitTransaction()
3048{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003049 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003050 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003051 for (const auto& l : mLayersPendingRemoval) {
3052 recordBufferingStats(l->getName().string(),
3053 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003054
3055 // We need to release the HWC layers when the Layer is removed
3056 // from the current state otherwise the HWC layer just continues
3057 // showing at its last configured state until we eventually
3058 // abandon the buffer queue.
3059 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003060 l->destroyHwcLayersForAllDisplays();
3061 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003062 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003063 }
3064 mLayersPendingRemoval.clear();
3065 }
3066
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003067 // If this transaction is part of a window animation then the next frame
3068 // we composite should be considered an animation as well.
3069 mAnimCompositionPending = mAnimTransactionPending;
3070
Mathias Agopian4fec8732012-06-29 14:12:52 -07003071 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003072 // clear the "changed" flags in current state
3073 mCurrentState.colorMatrixChanged = false;
3074
Robert Carr1f0a16a2016-10-24 16:27:39 -07003075 mDrawingState.traverseInZOrder([](Layer* layer) {
3076 layer->commitChildList();
3077 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003078 mTransactionPending = false;
3079 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003080 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081}
3082
Lloyd Pique32cbe282018-10-19 13:09:22 -07003083void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003084 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003085 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003086 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003087
Lloyd Pique32cbe282018-10-19 13:09:22 -07003088 auto display = displayDevice->getCompositionDisplay();
3089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 Region aboveOpaqueLayers;
3091 Region aboveCoveredLayers;
3092 Region dirty;
3093
Mathias Agopian87baae12012-07-31 12:38:26 -07003094 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095
Robert Carr2047fae2016-11-28 14:09:09 -08003096 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003097 // start with the whole surface at its current location
3098 const Layer::State& s(layer->getDrawingState());
3099
Jesse Hall01e29052013-02-19 16:13:35 -08003100 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003101 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003102 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003103 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003104
Mathias Agopianab028732010-03-16 16:41:46 -07003105 /*
3106 * opaqueRegion: area of a surface that is fully opaque.
3107 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003109
3110 /*
3111 * visibleRegion: area of a surface that is visible on screen
3112 * and not fully transparent. This is essentially the layer's
3113 * footprint minus the opaque regions above it.
3114 * Areas covered by a translucent surface are considered visible.
3115 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003117
3118 /*
3119 * coveredRegion: area of a surface that is covered by all
3120 * visible regions above it (which includes the translucent areas).
3121 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003123
Jesse Halla8026d22012-09-25 13:25:04 -07003124 /*
3125 * transparentRegion: area of a surface that is hinted to be completely
3126 * transparent. This is only used to tell when the layer has no visible
3127 * non-transparent regions and can be removed from the layer list. It
3128 * does not affect the visibleRegion of this layer or any layers
3129 * beneath it. The hint may not be correct if apps don't respect the
3130 * SurfaceView restrictions (which, sadly, some don't).
3131 */
3132 Region transparentRegion;
3133
Mathias Agopianab028732010-03-16 16:41:46 -07003134
3135 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003136 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003137 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003141 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003142 if (!visibleRegion.isEmpty()) {
3143 // Remove the transparent area from the visible region
3144 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003145 if (tr.preserveRects()) {
3146 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003147 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003148 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003149 // transformation too complex, can't do the
3150 // transparent region optimization.
3151 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003152 }
Mathias Agopianab028732010-03-16 16:41:46 -07003153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154
Mathias Agopianab028732010-03-16 16:41:46 -07003155 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003156 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003157 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003158 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003159 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003160 // the opaque region is the layer's footprint
3161 opaqueRegion = visibleRegion;
3162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 }
3164 }
3165
Robert Carre5f4f692018-01-12 13:12:28 -08003166 if (visibleRegion.isEmpty()) {
3167 layer->clearVisibilityRegions();
3168 return;
3169 }
3170
Mathias Agopianab028732010-03-16 16:41:46 -07003171 // Clip the covered region to the visible region
3172 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3173
3174 // Update aboveCoveredLayers for next (lower) layer
3175 aboveCoveredLayers.orSelf(visibleRegion);
3176
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 // subtract the opaque region covered by the layers above us
3178 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179
3180 // compute this layer's dirty region
3181 if (layer->contentDirty) {
3182 // we need to invalidate the whole region
3183 dirty = visibleRegion;
3184 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003185 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 layer->contentDirty = false;
3187 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003188 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003189 * the exposed region consists of two components:
3190 * 1) what's VISIBLE now and was COVERED before
3191 * 2) what's EXPOSED now less what was EXPOSED before
3192 *
3193 * note that (1) is conservative, we start with the whole
3194 * visible region but only keep what used to be covered by
3195 * something -- which mean it may have been exposed.
3196 *
3197 * (2) handles areas that were not covered by anything but got
3198 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003199 */
Mathias Agopianab028732010-03-16 16:41:46 -07003200 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003201 const Region oldVisibleRegion = layer->visibleRegion;
3202 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003203 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3204 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 }
3206 dirty.subtractSelf(aboveOpaqueLayers);
3207
3208 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003209 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210
Mathias Agopianab028732010-03-16 16:41:46 -07003211 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003213
Jesse Halla8026d22012-09-25 13:25:04 -07003214 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215 layer->setVisibleRegion(visibleRegion);
3216 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003217 layer->setVisibleNonTransparentRegion(
3218 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003219 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220
Mathias Agopian87baae12012-07-31 12:38:26 -07003221 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222}
3223
Chia-I Wuab0c3192017-08-01 11:29:00 -07003224void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003225 for (const auto& [token, displayDevice] : mDisplays) {
3226 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003227 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003228 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003229 }
3230 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003231}
3232
Daniel Solomon42d04562019-01-20 21:03:19 -08003233void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3234 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3235 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3236 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3237 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3238 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3239 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3240 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3241 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3242 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3243 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3244 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3245 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3246}
3247
Dan Stoza6b9454d2014-11-07 16:00:59 -08003248bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003250 ALOGV("handlePageFlip");
3251
Brian Andersond6927fb2016-07-23 23:37:30 -07003252 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253
Mathias Agopian4fec8732012-06-29 14:12:52 -07003254 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003256 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003257
3258 // Store the set of layers that need updates. This set must not change as
3259 // buffers are being latched, as this could result in a deadlock.
3260 // Example: Two producers share the same command stream and:
3261 // 1.) Layer 0 is latched
3262 // 2.) Layer 0 gets a new frame
3263 // 2.) Layer 1 gets a new frame
3264 // 3.) Layer 1 is latched.
3265 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3266 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003267 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003268 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003269 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003270 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3271 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003272 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003273 } else {
3274 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003275 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003276 } else {
3277 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003278 }
Robert Carr2047fae2016-11-28 14:09:09 -08003279 });
3280
Lloyd Piquef2c79392018-12-20 16:23:33 -08003281 if (!mLayersWithQueuedFrames.empty()) {
3282 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3283 // writes to Layer current state. See also b/119481871
3284 Mutex::Autolock lock(mStateLock);
3285
3286 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003287 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3288 mLayersPendingRefresh.push_back(layer);
3289 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003290 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003291 if (layer->isBufferLatched()) {
3292 newDataLatched = true;
3293 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003294 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003295 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003296
Alec Mouri86770e52018-09-24 22:40:58 +00003297 // Clear the renderengine fence here...
3298 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3299 // clear instead of sp::clear.
3300 getBE().flushFence = Fence::NO_FENCE;
3301
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003302 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003303
3304 // If we will need to wake up at some time in the future to deal with a
3305 // queued frame that shouldn't be displayed during this vsync period, wake
3306 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003307 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003308 signalLayerUpdate();
3309 }
3310
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003311 // enter boot animation on first buffer latch
3312 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3313 ALOGI("Enter boot animation");
3314 mBootStage = BootStage::BOOTANIMATION;
3315 }
3316
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003318 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319}
3320
Mathias Agopianad456f92011-01-13 17:53:01 -08003321void SurfaceFlinger::invalidateHwcGeometry()
3322{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003324}
3325
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003327 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003328 auto display = displayDevice->getCompositionDisplay();
3329
Dan Stoza71433162014-02-04 16:22:36 -08003330 // We only need to actually compose the display if:
3331 // 1) It is being handled by hardware composer, which may need this to
3332 // keep its virtual display state machine in sync, or
3333 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003334 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003336 return;
3337 }
3338
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 ALOGV("doDisplayComposition");
Alec Mouri79108df2019-02-04 19:33:44 +00003340 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003341
3342 // swap buffers (presentation)
Alec Mouri79108df2019-02-04 19:33:44 +00003343 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344}
3345
Alec Mouri79108df2019-02-04 19:33:44 +00003346bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003347 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003348
Lloyd Pique32cbe282018-10-19 13:09:22 -07003349 auto display = displayDevice->getCompositionDisplay();
3350 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003351 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003352
3353 const Region bounds(displayState.bounds);
3354 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003355 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003356 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003357
Peiyong Lind3788632018-09-18 16:01:31 -07003358 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003359 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003360
Alec Mouri79108df2019-02-04 19:33:44 +00003361 // Framebuffer will live in this scope for GPU composition.
3362 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 if (hasClientComposition) {
3365 ALOGV("hasClientComposition");
3366
Alec Mouri79108df2019-02-04 19:33:44 +00003367 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003368
3369 if (buf == nullptr) {
3370 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3371 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003373 return false;
3374 }
3375
Alec Mouri79108df2019-02-04 19:33:44 +00003376 // Bind the framebuffer in this scope.
3377 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3378 buf->getNativeBuffer());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379
Alec Mouri79108df2019-02-04 19:33:44 +00003380 if (fbo->getStatus() != NO_ERROR) {
3381 ALOGW("Binding buffer for display [%s] failed with status: %d",
3382 displayDevice->getDisplayName().c_str(), fbo->getStatus());
3383 return false;
3384 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003385
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003386 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003387 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003388 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003389 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003390 }
Alec Mouri79108df2019-02-04 19:33:44 +00003391 getRenderEngine().setOutputDataSpace(outputDataspace);
3392 getRenderEngine().setDisplayMaxLuminance(
3393 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003394
Lloyd Pique441d5042018-10-18 16:49:51 -07003395 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003396 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003397 getHwComposer()
3398 .hasDisplayCapability(displayId,
3399 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003400
Peiyong Lind3788632018-09-18 16:01:31 -07003401 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003402 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3403 if (applyColorMatrix) {
Alec Mouri79108df2019-02-04 19:33:44 +00003404 colorMatrix = mDrawingState.colorMatrix;
3405 }
3406
3407 display->getRenderSurface()->setViewportAndProjection();
3408
3409 // Never touch the framebuffer if we don't have any framebuffer layers
3410 if (hasDeviceComposition) {
3411 // when using overlays, we assume a fully transparent framebuffer
3412 // NOTE: we could reduce how much we need to clear, for instance
3413 // remove where there are opaque FB layers. however, on some
3414 // GPUs doing a "clean slate" clear might be more efficient.
3415 // We'll revisit later if needed.
3416 getRenderEngine().clearWithColor(0, 0, 0, 0);
3417 } else {
3418 // we start with the whole screen area and remove the scissor part
3419 // we're left with the letterbox region
3420 // (common case is that letterbox ends-up being empty)
3421 const Region letterbox = bounds.subtract(displayState.scissor);
3422
3423 // compute the area to clear
3424 const Region region = displayState.undefinedRegion.merge(letterbox);
3425
3426 // screen is already cleared here
3427 if (!region.isEmpty()) {
3428 // can happen with SurfaceView
3429 drawWormhole(region);
3430 }
3431 }
3432
3433 const Rect& bounds = displayState.bounds;
3434 const Rect& scissor = displayState.scissor;
3435 if (scissor != bounds) {
3436 // scissor doesn't match the screen's dimensions, so we
3437 // need to clear everything outside of it and enable
3438 // the GL scissor so we don't draw anything where we shouldn't
3439
3440 // enable scissor for this frame
3441 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003442 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003443 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003444
Mathias Agopian85d751c2012-08-29 16:59:24 -07003445 /*
3446 * and then, render the layers targeted at the framebuffer
3447 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003448
Dan Stoza9e56aa02015-11-02 13:00:03 -08003449 ALOGV("Rendering client layers");
Alec Mouri79108df2019-02-04 19:33:44 +00003450 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003452 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri79108df2019-02-04 19:33:44 +00003453 const Region clip(bounds.intersect(displayTransform.transform(layer->visibleRegion)));
David Sodmanc1498e62018-09-12 14:36:26 -07003454 ALOGV("Layer: %s", layer->getName().string());
3455 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003457 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003458 case HWC2::Composition::Cursor:
3459 case HWC2::Composition::Device:
3460 case HWC2::Composition::Sideband:
3461 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003462 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003463 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003464 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003465 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003466 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003467 // never clear the very first layer since we're
3468 // guaranteed the FB is already cleared
Alec Mouri79108df2019-02-04 19:33:44 +00003469 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003470 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003471 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003472 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003473 case HWC2::Composition::Client: {
Alec Mouri79108df2019-02-04 19:33:44 +00003474 if (layer->hasColorTransform()) {
3475 mat4 tmpMatrix;
3476 if (applyColorMatrix) {
3477 tmpMatrix = mDrawingState.colorMatrix;
3478 }
3479 tmpMatrix *= layer->getColorTransform();
3480 getRenderEngine().setColorTransform(tmpMatrix);
3481 } else {
3482 getRenderEngine().setColorTransform(colorMatrix);
Peiyong Lind3788632018-09-18 16:01:31 -07003483 }
Alec Mouri79108df2019-02-04 19:33:44 +00003484 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003485 break;
3486 }
3487 default:
3488 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003489 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003490 } else {
3491 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003492 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003493 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003494 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003495
Alec Mouri79108df2019-02-04 19:33:44 +00003496 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003497 if (hasClientComposition) {
Alec Mouri79108df2019-02-04 19:33:44 +00003498 getRenderEngine().setColorTransform(mat4());
3499 getRenderEngine().disableScissor();
3500 display->getRenderSurface()->finishBuffer();
3501 // Clear out error flags here so that we don't wait until next
3502 // composition to log.
3503 getRenderEngine().checkErrors();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003504 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003505 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506}
3507
Chia-I Wu28e3a252018-09-07 12:05:02 -07003508void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003509 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003510 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511}
3512
Dan Stoza7d89d062015-04-30 13:29:25 -07003513status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003514 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003515 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003516 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003517 const sp<Layer>& parent,
3518 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003519{
Dan Stoza7d89d062015-04-30 13:29:25 -07003520 // add this layer to the current state list
3521 {
3522 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003523 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003524 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3525 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003526 return NO_MEMORY;
3527 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003528 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003529 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003530 } else if (parent == nullptr) {
3531 lbc->onRemovedFromCurrentState();
3532 } else if (parent->isRemovedFromCurrentState()) {
3533 parent->addChild(lbc);
3534 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003535 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003536 parent->addChild(lbc);
3537 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003538
Yiwei Zhang243b3782018-05-15 17:40:04 -07003539 if (gbc != nullptr) {
3540 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3541 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3542 mMaxGraphicBufferProducerListSize,
3543 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3544 mGraphicBufferProducerList.size(),
3545 mMaxGraphicBufferProducerListSize, mNumLayers);
3546 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003547 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003548 }
3549
Mathias Agopian96f08192010-06-02 23:28:45 -07003550 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003551 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003552
Dan Stoza7d89d062015-04-30 13:29:25 -07003553 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003554}
3555
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003556uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003557 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003558}
3559
Mathias Agopian3f844832013-08-07 21:24:32 -07003560uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003561 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562}
3563
Mathias Agopian3f844832013-08-07 21:24:32 -07003564uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003565 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003566}
3567
3568uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003569 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003570 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003571 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003573 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 }
3575 return old;
3576}
3577
Marissa Wall713b63f2018-10-17 15:42:43 -07003578bool SurfaceFlinger::flushTransactionQueues() {
3579 Mutex::Autolock _l(mStateLock);
3580 auto it = mTransactionQueues.begin();
3581 while (it != mTransactionQueues.end()) {
3582 auto& [applyToken, transactionQueue] = *it;
3583
3584 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003585 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3586 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003587 break;
3588 }
chaviw273171b2018-12-26 11:46:30 -08003589 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003590 transactionQueue.pop();
3591 }
3592
3593 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3594 }
3595 return mTransactionQueues.empty();
3596}
3597
chaviwca27f252018-02-06 16:46:39 -08003598bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3599 for (const ComposerState& state : states) {
3600 // Here we need to check that the interface we're given is indeed
3601 // one of our own. A malicious client could give us a nullptr
3602 // IInterface, or one of its own or even one of our own but a
3603 // different type. All these situations would cause us to crash.
3604 if (state.client == nullptr) {
3605 return true;
3606 }
3607
3608 sp<IBinder> binder = IInterface::asBinder(state.client);
3609 if (binder == nullptr) {
3610 return true;
3611 }
3612
3613 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3614 return true;
3615 }
3616 }
3617 return false;
3618}
3619
Marissa Wall17b4e452018-12-26 16:32:34 -08003620bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3621 const Vector<ComposerState>& states) {
3622 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3623 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3624 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3625 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3626 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3627 return false;
3628 }
3629
Marissa Wall713b63f2018-10-17 15:42:43 -07003630 for (const ComposerState& state : states) {
3631 const layer_state_t& s = state.state;
3632 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3633 continue;
3634 }
3635 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003636 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003637 }
3638 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003639 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003640}
3641
3642void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3643 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003644 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003645 const InputWindowCommands& inputWindowCommands,
3646 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003647 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003648 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003649
chaviwca27f252018-02-06 16:46:39 -08003650 if (containsAnyInvalidClientState(states)) {
3651 return;
3652 }
3653
Marissa Wall713b63f2018-10-17 15:42:43 -07003654 // If its TransactionQueue already has a pending TransactionState or if it is pending
3655 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003656 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3657 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003658 setTransactionFlags(eTransactionNeeded);
3659 return;
3660 }
3661
chaviw273171b2018-12-26 11:46:30 -08003662 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003663}
3664
3665void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003666 const Vector<DisplayState>& displays, uint32_t flags,
3667 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003668 uint32_t transactionFlags = 0;
3669
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003670 if (flags & eAnimation) {
3671 // For window updates that are part of an animation we must wait for
3672 // previous animation "frames" to be handled.
3673 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003674 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003675 if (CC_UNLIKELY(err != NO_ERROR)) {
3676 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003677 // caller after a few seconds.
3678 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3679 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003680 mAnimTransactionPending = false;
3681 break;
3682 }
3683 }
3684 }
3685
chaviwca27f252018-02-06 16:46:39 -08003686 for (const DisplayState& display : displays) {
3687 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003688 }
3689
Marissa Walle2ffb422018-10-12 11:33:52 -07003690 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003691 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003692 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003693 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003694 // If the state doesn't require a traversal and there are callbacks, send them now
3695 if (!(clientStateFlags & eTraversalNeeded)) {
3696 mTransactionCompletedThread.sendCallbacks();
3697 }
3698 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003699
chaviw273171b2018-12-26 11:46:30 -08003700 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3701
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003702 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3703 // anyway. This can be used as a flush mechanism for previous async transactions.
3704 // Empty animation transaction can be used to simulate back-pressure, so also force a
3705 // transaction for empty animation transactions.
3706 if (transactionFlags == 0 &&
3707 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003708 transactionFlags = eTransactionNeeded;
3709 }
3710
Mathias Agopian386aa982011-11-07 21:58:03 -08003711 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003712 if (mInterceptor->isEnabled()) {
3713 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003714 }
Irvel468051e2016-06-13 16:44:44 -07003715
Mathias Agopian386aa982011-11-07 21:58:03 -08003716 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003717 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3718 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003719 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003720
3721 // if this is a synchronous transaction, wait for it to take effect
3722 // before returning.
3723 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003724 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003725 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003726 if (flags & eAnimation) {
3727 mAnimTransactionPending = true;
3728 }
3729 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003730 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3731 if (CC_UNLIKELY(err != NO_ERROR)) {
3732 // just in case something goes wrong in SF, return to the
3733 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003734 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3735 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003736 break;
3737 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 }
3740}
3741
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003742uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3743 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3744 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003745
Mathias Agopiane57f2922012-08-09 16:29:12 -07003746 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003747 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3748
3749 const uint32_t what = s.what;
3750 if (what & DisplayState::eSurfaceChanged) {
3751 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3752 state.surface = s.surface;
3753 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003754 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003755 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003756 if (what & DisplayState::eLayerStackChanged) {
3757 if (state.layerStack != s.layerStack) {
3758 state.layerStack = s.layerStack;
3759 flags |= eDisplayTransactionNeeded;
3760 }
3761 }
3762 if (what & DisplayState::eDisplayProjectionChanged) {
3763 if (state.orientation != s.orientation) {
3764 state.orientation = s.orientation;
3765 flags |= eDisplayTransactionNeeded;
3766 }
3767 if (state.frame != s.frame) {
3768 state.frame = s.frame;
3769 flags |= eDisplayTransactionNeeded;
3770 }
3771 if (state.viewport != s.viewport) {
3772 state.viewport = s.viewport;
3773 flags |= eDisplayTransactionNeeded;
3774 }
3775 }
3776 if (what & DisplayState::eDisplaySizeChanged) {
3777 if (state.width != s.width) {
3778 state.width = s.width;
3779 flags |= eDisplayTransactionNeeded;
3780 }
3781 if (state.height != s.height) {
3782 state.height = s.height;
3783 flags |= eDisplayTransactionNeeded;
3784 }
3785 }
3786
Mathias Agopiane57f2922012-08-09 16:29:12 -07003787 return flags;
3788}
3789
Robert Carrd4ae7f32018-06-07 16:10:57 -07003790bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3791 IPCThreadState* ipc = IPCThreadState::self();
3792 const int pid = ipc->getCallingPid();
3793 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003794 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003795 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003796 return false;
3797 }
3798 return true;
3799}
3800
chaviwca27f252018-02-06 16:46:39 -08003801uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3802 const layer_state_t& s = composerState.state;
3803 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3804
Mathias Agopian13127d82013-03-05 17:47:11 -08003805 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003806 if (layer == nullptr) {
3807 return 0;
3808 }
3809
chaviw8b3871a2017-11-01 17:41:01 -07003810 uint32_t flags = 0;
3811
Garfield Tan8a3083e2018-12-03 13:21:07 -08003812 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003813 bool geometryAppliesWithResize =
3814 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003815
3816 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3817 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003818 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003819 layer->pushPendingState();
3820 }
3821
chaviw8b3871a2017-11-01 17:41:01 -07003822 if (what & layer_state_t::ePositionChanged) {
3823 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3824 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003825 }
chaviw8b3871a2017-11-01 17:41:01 -07003826 }
3827 if (what & layer_state_t::eLayerChanged) {
3828 // NOTE: index needs to be calculated before we update the state
3829 const auto& p = layer->getParent();
3830 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003831 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003832 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003833 mCurrentState.layersSortedByZ.removeAt(idx);
3834 mCurrentState.layersSortedByZ.add(layer);
3835 // we need traversal (state changed)
3836 // AND transaction (list changed)
3837 flags |= eTransactionNeeded|eTraversalNeeded;
3838 }
chaviw8b3871a2017-11-01 17:41:01 -07003839 } else {
3840 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003841 flags |= eTransactionNeeded|eTraversalNeeded;
3842 }
3843 }
chaviw8b3871a2017-11-01 17:41:01 -07003844 }
3845 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003846 // NOTE: index needs to be calculated before we update the state
3847 const auto& p = layer->getParent();
3848 if (p == nullptr) {
3849 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3850 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3851 mCurrentState.layersSortedByZ.removeAt(idx);
3852 mCurrentState.layersSortedByZ.add(layer);
3853 // we need traversal (state changed)
3854 // AND transaction (list changed)
3855 flags |= eTransactionNeeded|eTraversalNeeded;
3856 }
3857 } else {
3858 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3859 flags |= eTransactionNeeded|eTraversalNeeded;
3860 }
chaviw8b3871a2017-11-01 17:41:01 -07003861 }
3862 }
3863 if (what & layer_state_t::eSizeChanged) {
3864 if (layer->setSize(s.w, s.h)) {
3865 flags |= eTraversalNeeded;
3866 }
3867 }
3868 if (what & layer_state_t::eAlphaChanged) {
3869 if (layer->setAlpha(s.alpha))
3870 flags |= eTraversalNeeded;
3871 }
3872 if (what & layer_state_t::eColorChanged) {
3873 if (layer->setColor(s.color))
3874 flags |= eTraversalNeeded;
3875 }
Peiyong Lind3788632018-09-18 16:01:31 -07003876 if (what & layer_state_t::eColorTransformChanged) {
3877 if (layer->setColorTransform(s.colorTransform)) {
3878 flags |= eTraversalNeeded;
3879 }
3880 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003881 if (what & layer_state_t::eBackgroundColorChanged) {
3882 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3883 flags |= eTraversalNeeded;
3884 }
3885 }
chaviw8b3871a2017-11-01 17:41:01 -07003886 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003887 // TODO: b/109894387
3888 //
3889 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3890 // rotation. To see the problem observe that if we have a square parent, and a child
3891 // of the same size, then we rotate the child 45 degrees around it's center, the child
3892 // must now be cropped to a non rectangular 8 sided region.
3893 //
3894 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3895 // private API, and the WindowManager only uses rotation in one case, which is on a top
3896 // level layer in which cropping is not an issue.
3897 //
3898 // However given that abuse of rotation matrices could lead to surfaces extending outside
3899 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3900 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3901 // transformations.
3902 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003903 flags |= eTraversalNeeded;
3904 }
3905 if (what & layer_state_t::eTransparentRegionChanged) {
3906 if (layer->setTransparentRegionHint(s.transparentRegion))
3907 flags |= eTraversalNeeded;
3908 }
3909 if (what & layer_state_t::eFlagsChanged) {
3910 if (layer->setFlags(s.flags, s.mask))
3911 flags |= eTraversalNeeded;
3912 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003913 if (what & layer_state_t::eCropChanged_legacy) {
3914 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003915 flags |= eTraversalNeeded;
3916 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003917 if (what & layer_state_t::eCornerRadiusChanged) {
3918 if (layer->setCornerRadius(s.cornerRadius))
3919 flags |= eTraversalNeeded;
3920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 if (what & layer_state_t::eLayerStackChanged) {
3922 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3923 // We only allow setting layer stacks for top level layers,
3924 // everything else inherits layer stack from its parent.
3925 if (layer->hasParent()) {
3926 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3927 layer->getName().string());
3928 } else if (idx < 0) {
3929 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3930 "that also does not appear in the top level layer list. Something"
3931 " has gone wrong.", layer->getName().string());
3932 } else if (layer->setLayerStack(s.layerStack)) {
3933 mCurrentState.layersSortedByZ.removeAt(idx);
3934 mCurrentState.layersSortedByZ.add(layer);
3935 // we need traversal (state changed)
3936 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003937 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003938 }
3939 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003940 if (what & layer_state_t::eDeferTransaction_legacy) {
3941 if (s.barrierHandle_legacy != nullptr) {
3942 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3943 } else if (s.barrierGbp_legacy != nullptr) {
3944 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003945 if (authenticateSurfaceTextureLocked(gbp)) {
3946 const auto& otherLayer =
3947 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003948 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003949 } else {
3950 ALOGE("Attempt to defer transaction to to an"
3951 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003952 }
3953 }
chaviw8b3871a2017-11-01 17:41:01 -07003954 // We don't trigger a traversal here because if no other state is
3955 // changed, we don't want this to cause any more work
3956 }
3957 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003958 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003959 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003960 if (!hadParent) {
3961 mCurrentState.layersSortedByZ.remove(layer);
3962 }
chaviw8b3871a2017-11-01 17:41:01 -07003963 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003964 }
chaviw8b3871a2017-11-01 17:41:01 -07003965 }
3966 if (what & layer_state_t::eReparentChildren) {
3967 if (layer->reparentChildren(s.reparentHandle)) {
3968 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003969 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003970 }
chaviw8b3871a2017-11-01 17:41:01 -07003971 if (what & layer_state_t::eDetachChildren) {
3972 layer->detachChildren();
3973 }
3974 if (what & layer_state_t::eOverrideScalingModeChanged) {
3975 layer->setOverrideScalingMode(s.overrideScalingMode);
3976 // We don't trigger a traversal here because if no other state is
3977 // changed, we don't want this to cause any more work
3978 }
Marissa Wall61c58622018-07-18 10:12:20 -07003979 if (what & layer_state_t::eTransformChanged) {
3980 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3981 }
3982 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3983 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3984 flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eCropChanged) {
3987 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3988 }
Marissa Wall861616d2018-10-22 12:52:23 -07003989 if (what & layer_state_t::eFrameChanged) {
3990 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3991 }
Marissa Wall61c58622018-07-18 10:12:20 -07003992 if (what & layer_state_t::eAcquireFenceChanged) {
3993 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3994 }
3995 if (what & layer_state_t::eDataspaceChanged) {
3996 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3997 }
3998 if (what & layer_state_t::eHdrMetadataChanged) {
3999 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4000 }
4001 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4002 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4003 }
4004 if (what & layer_state_t::eApiChanged) {
4005 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4006 }
4007 if (what & layer_state_t::eSidebandStreamChanged) {
4008 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4009 }
Robert Carr720e5062018-07-30 17:45:14 -07004010 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004011 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4012 layer->setInputInfo(s.inputInfo);
4013 flags |= eTraversalNeeded;
4014 } else {
4015 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4016 }
Robert Carr720e5062018-07-30 17:45:14 -07004017 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004018 if (what & layer_state_t::eMetadataChanged) {
4019 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4020 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004021 std::vector<sp<CallbackHandle>> callbackHandles;
4022 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4023 mTransactionCompletedThread.run();
4024 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4025 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4026 }
4027 }
Marissa Wall73411622019-01-25 10:45:41 -08004028
4029 if (what & layer_state_t::eBufferChanged) {
4030 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4031 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4032 s.buffer);
4033 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004034 if (what & layer_state_t::eCachedBufferChanged) {
4035 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004036 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4037 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004038 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4039 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004040 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4041 // Do not put anything that updates layer state or modifies flags after
4042 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004043 return flags;
4044}
4045
chaviw273171b2018-12-26 11:46:30 -08004046uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4047 uint32_t flags = 0;
4048 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4049 flags |= eTraversalNeeded;
4050 }
4051
4052 mInputWindowCommands.merge(inputWindowCommands);
4053 return flags;
4054}
4055
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004056status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4057 uint32_t h, PixelFormat format, uint32_t flags,
4058 LayerMetadata metadata, sp<IBinder>* handle,
4059 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004060 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004061 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004062 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004063 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004064 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004065
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004066 status_t result = NO_ERROR;
4067
4068 sp<Layer> layer;
4069
Cody Northropbc755282017-03-31 12:00:08 -06004070 String8 uniqueName = getUniqueLayerName(name);
4071
Mathias Agopian3165cc22012-08-08 19:42:09 -07004072 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004073 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004074 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4075 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004078 case ISurfaceComposerClient::eFXSurfaceBufferState:
4079 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4080 break;
chaviw13fdc492017-06-27 12:40:18 -07004081 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004082 // check if buffer size is set for color layer.
4083 if (w > 0 || h > 0) {
4084 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4085 int(w), int(h));
4086 return BAD_VALUE;
4087 }
4088
chaviw13fdc492017-06-27 12:40:18 -07004089 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004090 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004091 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004092 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004093 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004094 // check if buffer size is set for container layer.
4095 if (w > 0 || h > 0) {
4096 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4097 int(w), int(h));
4098 return BAD_VALUE;
4099 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004100 result = createContainerLayer(client,
4101 uniqueName, w, h, flags,
4102 handle, &layer);
4103 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004104 default:
4105 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004106 break;
4107 }
4108
Dan Stoza7d89d062015-04-30 13:29:25 -07004109 if (result != NO_ERROR) {
4110 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004112
Chia-I Wuab0c3192017-08-01 11:29:00 -07004113 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4114 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004115 if (metadata.has(METADATA_WINDOW_TYPE)) {
4116 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4117 if (windowType == 441731) {
4118 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4119 layer->setPrimaryDisplayOnly();
4120 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004121 }
4122
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004123 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004124
Robert Carrb89ea9d2018-12-10 13:01:14 -08004125 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4126 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4127 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004128 if (result != NO_ERROR) {
4129 return result;
4130 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004131 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004132
4133 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135}
4136
Cody Northropbc755282017-03-31 12:00:08 -06004137String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4138{
4139 bool matchFound = true;
4140 uint32_t dupeCounter = 0;
4141
4142 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4143 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4144
Dan Stoza436ccf32018-06-21 12:10:12 -07004145 // Grab the state lock since we're accessing mCurrentState
4146 Mutex::Autolock lock(mStateLock);
4147
Cody Northropbc755282017-03-31 12:00:08 -06004148 // Loop over layers until we're sure there is no matching name
4149 while (matchFound) {
4150 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004151 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004152 if (layer->getName() == uniqueName) {
4153 matchFound = true;
4154 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4155 }
4156 });
4157 }
4158
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004159 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4160 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004161
4162 return uniqueName;
4163}
4164
Marissa Wallfd668622018-05-10 10:21:13 -07004165status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4166 uint32_t w, uint32_t h, uint32_t flags,
4167 PixelFormat& format, sp<IBinder>* handle,
4168 sp<IGraphicBufferProducer>* gbp,
4169 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004170 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004171 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004172 case PIXEL_FORMAT_TRANSPARENT:
4173 case PIXEL_FORMAT_TRANSLUCENT:
4174 format = PIXEL_FORMAT_RGBA_8888;
4175 break;
4176 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004177 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004178 break;
4179 }
4180
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004181 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004182 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004183 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004184 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004185 *handle = layer->getHandle();
4186 *gbp = layer->getProducer();
4187 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004189
Marissa Wallfd668622018-05-10 10:21:13 -07004190 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004191 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192}
4193
Marissa Wall61c58622018-07-18 10:12:20 -07004194status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4195 uint32_t w, uint32_t h, uint32_t flags,
4196 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004197 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004198 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004199 *handle = layer->getHandle();
4200 *outLayer = layer;
4201
4202 return NO_ERROR;
4203}
4204
chaviw13fdc492017-06-27 12:40:18 -07004205status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004206 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004207 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004209 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004210 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004211 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004212}
4213
Robert Carr6b3f6c52018-08-13 13:05:17 -07004214status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4215 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4216 sp<IBinder>* handle, sp<Layer>* outLayer)
4217{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004218 *outLayer =
4219 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004220 *handle = (*outLayer)->getHandle();
4221 return NO_ERROR;
4222}
4223
4224
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004225void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004226 mLayersPendingRemoval.add(layer);
4227 mLayersRemoved = true;
4228 setTransactionFlags(eTransactionNeeded);
4229}
4230
Robert Carr695d5282018-12-18 15:27:58 -08004231void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004232{
Robert Carr2e102c92018-10-23 12:11:15 -07004233 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004234 // If a layer has a parent, we allow it to out-live it's handle
4235 // with the idea that the parent holds a reference and will eventually
4236 // be cleaned up. However no one cleans up the top-level so we do so
4237 // here.
4238 if (layer->getParent() == nullptr) {
4239 mCurrentState.layersSortedByZ.remove(layer);
4240 }
4241 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004242 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004243}
4244
Mathias Agopianb60314a2012-04-10 22:09:54 -07004245// ---------------------------------------------------------------------------
4246
Andy McFadden13a082e2012-08-24 10:16:42 -07004247void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004248 const auto display = getDefaultDisplayDeviceLocked();
4249 if (!display) return;
4250
4251 const sp<IBinder> token = display->getDisplayToken().promote();
4252 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004253
Jesse Hall01e29052013-02-19 16:13:35 -08004254 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004255 Vector<ComposerState> state;
4256 Vector<DisplayState> displays;
4257 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004258 d.what = DisplayState::eDisplayProjectionChanged |
4259 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004261 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004262 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004263 d.frame.makeInvalid();
4264 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004265 d.width = 0;
4266 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004267 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004268 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004269
Dominik Laskowskie9774092018-12-11 10:04:24 -08004270 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004271
Dominik Laskowski83b88212018-12-11 13:34:06 -08004272 const nsecs_t vsyncPeriod = getVsyncPeriod();
4273 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004274
Brian Andersond0010582017-03-07 13:20:31 -08004275 // Use phase of 0 since phase is not known.
4276 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004277 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004278 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004279}
4280
4281void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004282 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004283 postMessageAsync(
4284 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004285}
4286
Dominik Laskowskie9774092018-12-11 10:04:24 -08004287void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 if (display->isVirtual()) {
4289 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004290 return;
4291 }
4292
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 const auto displayId = display->getId();
4294 LOG_ALWAYS_FATAL_IF(!displayId);
4295
Dominik Laskowski34157762018-10-31 13:07:19 -07004296 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297
4298 int currentMode = display->getPowerMode();
4299 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004300 return;
4301 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303 display->setPowerMode(mode);
4304
Lloyd Pique4dccc412018-01-22 17:21:36 -08004305 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004306 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004307 }
4308
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004309 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004310 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004313 if (mUseScheduler) {
4314 mScheduler->onScreenAcquired(mAppConnectionHandle);
4315 } else {
4316 mEventThread->onScreenAcquired();
4317 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004318 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004319 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004320
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004321 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004322 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004323 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004324
4325 struct sched_param param = {0};
4326 param.sched_priority = 1;
4327 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4328 ALOGW("Couldn't set SCHED_FIFO on display on");
4329 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004330 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004331 // Turn off the display
4332 struct sched_param param = {0};
4333 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4334 ALOGW("Couldn't set SCHED_OTHER on display off");
4335 }
4336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004337 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004338 if (mUseScheduler) {
4339 mScheduler->disableHardwareVsync(true);
4340 } else {
4341 disableHardwareVsync(true); // also cancels any in-progress resync
4342 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004343 if (mUseScheduler) {
4344 mScheduler->onScreenReleased(mAppConnectionHandle);
4345 } else {
4346 mEventThread->onScreenReleased();
4347 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004348 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004349
Dominik Laskowski075d3172018-05-24 15:50:06 -07004350 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004351 mVisibleRegionsDirty = true;
4352 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004353 } else if (mode == HWC_POWER_MODE_DOZE ||
4354 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004355 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004356 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004358 if (mUseScheduler) {
4359 mScheduler->onScreenAcquired(mAppConnectionHandle);
4360 } else {
4361 mEventThread->onScreenAcquired();
4362 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004363 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004364 }
4365 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4366 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004367 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004368 if (mUseScheduler) {
4369 mScheduler->disableHardwareVsync(true);
4370 } else {
4371 disableHardwareVsync(true); // also cancels any in-progress resync
4372 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004373 if (mUseScheduler) {
4374 mScheduler->onScreenReleased(mAppConnectionHandle);
4375 } else {
4376 mEventThread->onScreenReleased();
4377 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004378 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004379 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004380 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004381 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004382 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004383 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004385 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004386 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004387 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004388 // Update refresh rate stats.
4389 mRefreshRateStats->setPowerMode(mode);
4390 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004391 }
4392
Dominik Laskowski34157762018-10-31 13:07:19 -07004393 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004394}
4395
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004396void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004397 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004398 const auto display = getDisplayDevice(displayToken);
4399 if (!display) {
4400 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4401 displayToken.get());
4402 } else if (display->isVirtual()) {
4403 ALOGW("Attempt to set power mode %d for virtual display", mode);
4404 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004405 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004406 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004408}
4409
4410// ---------------------------------------------------------------------------
4411
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4413 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004415
Mathias Agopianbd115332013-04-18 16:41:04 -07004416 IPCThreadState* ipc = IPCThreadState::self();
4417 const int pid = ipc->getCallingPid();
4418 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004419
Mathias Agopianbd115332013-04-18 16:41:04 -07004420 if ((uid != AID_SHELL) &&
4421 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4423 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004425 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004426 // (this would indicate SF is stuck, but we want to be able to
4427 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004428 status_t err = mStateLock.timedLock(s2ns(1));
4429 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004430 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result,
4432 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4433 "(no locks held)\n",
4434 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004435 }
4436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004438
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439 static const std::unordered_map<std::string, Dumper> dumpers = {
4440 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4441 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4442 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4443 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4444 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4445 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4446 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4447 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4448 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4449 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4450 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4451 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4452 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004453 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004454 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4455 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004456
Dominik Laskowskic2867142019-01-21 11:33:38 -08004457 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004458
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4460 (it->second)(args, asProto, result);
4461 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004462 if (asProto) {
4463 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4464 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4465 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004466 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004467 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004468 }
4469
Mathias Agopian9795c422009-08-26 16:36:26 -07004470 if (locked) {
4471 mStateLock.unlock();
4472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 return NO_ERROR;
4476}
4477
Dominik Laskowskic2867142019-01-21 11:33:38 -08004478void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 mCurrentState.traverseInZOrder(
4480 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004481}
4482
Dominik Laskowskic2867142019-01-21 11:33:38 -08004483void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004484 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004485
Dominik Laskowskic2867142019-01-21 11:33:38 -08004486 if (args.size() > 1) {
4487 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004488 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004489 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004490 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004491 }
Robert Carr2047fae2016-11-28 14:09:09 -08004492 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004493 } else {
4494 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495 }
4496}
4497
Dominik Laskowskic2867142019-01-21 11:33:38 -08004498void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004499 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004500 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004501 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004502 }
Robert Carr2047fae2016-11-28 14:09:09 -08004503 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004504
Svetoslavd85084b2014-03-20 10:28:31 -07004505 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004506}
4507
Dominik Laskowskic2867142019-01-21 11:33:38 -08004508void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4509 mTimeStats->parseArgs(asProto, args, result);
4510}
4511
Jamie Gennis6547ff42013-07-16 20:12:42 -07004512// This should only be called from the main thread. Otherwise it would need
4513// the lock and should use mCurrentState rather than mDrawingState.
4514void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004515 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004516 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004517 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004518
4519 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4520}
4521
Yiwei Zhang5434a782018-12-05 18:06:32 -08004522void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004523 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004524
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004525 if (isLayerTripleBufferingDisabled())
4526 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004527
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4529 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4530 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4531 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4532 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4533 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004534 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004535}
4536
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004537void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004538 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004539 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004540 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004541 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004542
4543 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4544
4545 if (mUseScheduler) {
4546 mScheduler->dump(mAppConnectionHandle, result);
4547 } else {
4548 mEventThread->dump(result);
4549 }
4550}
4551
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4553 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004554 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4555 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004556 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004557 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004559 }
David Sodman4a36e932017-11-07 14:29:47 -08004560 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 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[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4564 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004565}
4566
Dan Stozae77c7662016-05-13 11:37:28 -07004567void SurfaceFlinger::recordBufferingStats(const char* layerName,
4568 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004569 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4570 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004571 for (const auto& segment : history) {
4572 if (!segment.usedThirdBuffer) {
4573 stats.twoBufferTime += segment.totalTime;
4574 }
4575 if (segment.occupancyAverage < 1.0f) {
4576 stats.doubleBufferedTime += segment.totalTime;
4577 } else if (segment.occupancyAverage < 2.0f) {
4578 stats.tripleBufferedTime += segment.totalTime;
4579 }
4580 ++stats.numSegments;
4581 stats.totalTime += segment.totalTime;
4582 }
4583}
4584
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4586 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004587
4588 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4589 const size_t count = currentLayers.size();
4590 for (size_t i=0 ; i<count ; i++) {
4591 currentLayers[i]->dumpFrameEvents(result);
4592 }
4593}
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004596 result.append("Buffering stats:\n");
4597 result.append(" [Layer name] <Active time> <Two buffer> "
4598 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004599 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004600 typedef std::tuple<std::string, float, float, float> BufferTuple;
4601 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004602 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004603 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004604 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004605 if (stats.numSegments == 0) {
4606 continue;
4607 }
4608 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4609 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4610 stats.totalTime;
4611 float doubleBufferRatio = static_cast<float>(
4612 stats.doubleBufferedTime) / stats.totalTime;
4613 float tripleBufferRatio = static_cast<float>(
4614 stats.tripleBufferedTime) / stats.totalTime;
4615 sorted.insert({activeTime, {name, twoBufferRatio,
4616 doubleBufferRatio, tripleBufferRatio}});
4617 }
4618 for (const auto& sortedPair : sorted) {
4619 float activeTime = sortedPair.first;
4620 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4622 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004623 }
4624 result.append("\n");
4625}
4626
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004628 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 const auto displayId = display->getId();
4630 if (!displayId) {
4631 continue;
4632 }
4633 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004634 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004635 continue;
4636 }
4637
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result,
4639 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4640 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004641 uint8_t port;
4642 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004643 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004644 result.append("no identification data\n");
4645 continue;
4646 }
4647
4648 if (!isEdid(data)) {
4649 result.append("unknown identification data: ");
4650 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652 }
4653 result.append("\n");
4654 continue;
4655 }
4656
4657 const auto edid = parseEdid(data);
4658 if (!edid) {
4659 result.append("invalid EDID: ");
4660 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004661 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004662 }
4663 result.append("\n");
4664 continue;
4665 }
4666
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004668 result.append(edid->displayName.data(), edid->displayName.length());
4669 result.append("\"\n");
4670 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004671}
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4674 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4675 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4676 StringAppendF(&result, "DisplayColorSetting: %s\n",
4677 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004678
4679 // TODO: print out if wide-color mode is active or not
4680
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004681 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004682 const auto displayId = display->getId();
4683 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 continue;
4685 }
4686
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004689 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004690 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004691 }
4692
Lloyd Pique32cbe282018-10-19 13:09:22 -07004693 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 StringAppendF(&result, " Current color mode: %s (%d)\n",
4695 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004696 }
4697 result.append("\n");
4698}
4699
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004701 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004702 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4703 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004704 continue;
4705 }
4706
Dominik Laskowski05275f12018-11-01 15:03:24 -07004707 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4709 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004710 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 compositionInfo.dump(result, nullptr);
4712 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004713 }
4714 }
David Sodman7e4ae112018-02-09 15:02:28 -08004715}
4716
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004717LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004718 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004719 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4720 const State& state = useDrawing ? mDrawingState : mCurrentState;
4721 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004722 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004723 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004724 });
4725
4726 return layersProto;
4727}
4728
Lloyd Pique32cbe282018-10-19 13:09:22 -07004729LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004730 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004731
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004732 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004733 resolution->set_w(displayDevice.getWidth());
4734 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004735
Lloyd Pique32cbe282018-10-19 13:09:22 -07004736 auto display = displayDevice.getCompositionDisplay();
4737 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004738
Lloyd Pique32cbe282018-10-19 13:09:22 -07004739 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4740 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4741 layersProto.set_global_transform(displayState.orientation);
4742
4743 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004744 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004745 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004746 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004747 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004748 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004749 }
4750 });
4751
4752 return layersProto;
4753}
4754
Dominik Laskowskic2867142019-01-21 11:33:38 -08004755void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4756 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004757 Colorizer colorizer(colorize);
4758
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759 // figure out if we're stuck somewhere
4760 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4763
4764 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004765 * Dump library configuration.
4766 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767
4768 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004769 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004771 appendSfConfigString(result);
4772 appendUiConfigString(result);
4773 appendGuiConfigString(result);
4774 result.append("\n");
4775
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004776 result.append("\nDisplay identification data:\n");
4777 dumpDisplayIdentificationData(result);
4778
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004779 result.append("\nWide-Color information:\n");
4780 dumpWideColorInfo(result);
4781
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004782 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004783 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004784 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004785 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004786 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004787
Andy McFadden41d67d72014-04-25 16:58:34 -07004788 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004789 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004790 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004791 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004792 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004793
Dan Stozab90cf072015-03-05 11:05:59 -08004794 dumpStaticScreenStats(result);
4795 result.append("\n");
4796
Yiwei Zhang5434a782018-12-05 18:06:32 -08004797 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004798
Dan Stozae77c7662016-05-13 11:37:28 -07004799 dumpBufferingStats(result);
4800
Andy McFadden4803b742012-09-24 19:07:20 -07004801 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802 * Dump the visible layer list
4803 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004804 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4806 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4807 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004808 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004809
Chia-I Wu2f884132018-09-13 15:17:58 -07004810 {
4811 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4812 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004813 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004814 result.append("\n");
4815 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816
David Sodman7e4ae112018-02-09 15:02:28 -08004817 result.append("\nFrame-Composition information:\n");
4818 dumpFrameCompositionInfo(result);
4819 result.append("\n");
4820
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004821 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004822 * Dump Display state
4823 */
4824
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004825 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004826 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004827 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004828 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004829 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004830 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004831 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004832
4833 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004834 * Dump SurfaceFlinger global state
4835 */
4836
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004837 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004838 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004840
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004841 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004842
Dominik Laskowski075d3172018-05-24 15:50:06 -07004843 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004844 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4845 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4847 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004848 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result,
4850 " transaction-flags : %08x\n"
4851 " gpu_to_cpu_unsupported : %d\n",
4852 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004853
Dominik Laskowski075d3172018-05-24 15:50:06 -07004854 if (const auto displayId = getInternalDisplayId();
4855 displayId && getHwComposer().isConnected(*displayId)) {
4856 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857 StringAppendF(&result,
4858 " refresh-rate : %f fps\n"
4859 " x-dpi : %f\n"
4860 " y-dpi : %f\n",
4861 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4862 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004863 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004864
Yiwei Zhang5434a782018-12-05 18:06:32 -08004865 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004866
Dan Stozae22aec72016-08-01 13:20:59 -07004867 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004868 * Tracing state
4869 */
4870 mTracing.dump(result);
4871 result.append("\n");
4872
4873 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004874 * HWC layer minidump
4875 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004876 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004877 const auto displayId = display->getId();
4878 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004879 continue;
4880 }
4881
Yiwei Zhang5434a782018-12-05 18:06:32 -08004882 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004883 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004884 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004885 result.append("\n");
4886 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887
4888 /*
4889 * Dump HWComposer state
4890 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004891 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004892 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004893 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004894 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004895 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004896 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004897
4898 /*
4899 * Dump gralloc state
4900 */
4901 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4902 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004903
4904 /*
4905 * Dump VrFlinger state if in use.
4906 */
4907 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4908 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004910 result.append("\n");
4911 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004912
4913 /**
4914 * Scheduler dump state.
4915 */
4916 if (mUseScheduler) {
4917 result.append("\nScheduler state:\n");
4918 result.append(mScheduler->doDump() + "\n");
4919 result.append(mRefreshRateStats->doDump() + "\n");
4920 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004921}
4922
Dominik Laskowski075d3172018-05-24 15:50:06 -07004923const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004924 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004925 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004926 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004927 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004928 }
4929 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004930
Dominik Laskowski34157762018-10-31 13:07:19 -07004931 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004932 static const Vector<sp<Layer>> empty;
4933 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004934}
4935
Chia-I Wu28f320b2018-05-03 11:02:56 -07004936void SurfaceFlinger::updateColorMatrixLocked() {
4937 mat4 colorMatrix;
4938 if (mGlobalSaturationFactor != 1.0f) {
4939 // Rec.709 luma coefficients
4940 float3 luminance{0.213f, 0.715f, 0.072f};
4941 luminance *= 1.0f - mGlobalSaturationFactor;
4942 mat4 saturationMatrix = mat4(
4943 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4944 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4945 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4946 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4947 );
4948 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4949 } else {
4950 colorMatrix = mClientColorMatrix * mDaltonizer();
4951 }
4952
4953 if (mCurrentState.colorMatrix != colorMatrix) {
4954 mCurrentState.colorMatrix = colorMatrix;
4955 mCurrentState.colorMatrixChanged = true;
4956 setTransactionFlags(eTransactionNeeded);
4957 }
4958}
4959
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004960status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004961#pragma clang diagnostic push
4962#pragma clang diagnostic error "-Wswitch-enum"
4963 switch (static_cast<ISurfaceComposerTag>(code)) {
4964 // These methods should at minimum make sure that the client requested
4965 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004966 case BOOT_FINISHED:
4967 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004968 case CREATE_DISPLAY:
4969 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004970 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971 case GET_ACTIVE_COLOR_MODE:
4972 case GET_ANIMATION_FRAME_STATS:
4973 case GET_HDR_CAPABILITIES:
4974 case SET_ACTIVE_CONFIG:
4975 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004976 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004977 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004978 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004979 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4980 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004981 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4982 IPCThreadState* ipc = IPCThreadState::self();
4983 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4984 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004985 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 }
Robert Carr1db73f62016-12-21 12:58:51 -08004987 return OK;
4988 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004989 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004990 IPCThreadState* ipc = IPCThreadState::self();
4991 const int pid = ipc->getCallingPid();
4992 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004993 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4994 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004995 return PERMISSION_DENIED;
4996 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004998 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004999 // Used by apps to hook Choreographer to SurfaceFlinger.
5000 case CREATE_DISPLAY_EVENT_CONNECTION:
5001 // The following calls are currently used by clients that do not
5002 // request necessary permissions. However, they do not expose any secret
5003 // information, so it is OK to pass them.
5004 case AUTHENTICATE_SURFACE:
5005 case GET_ACTIVE_CONFIG:
5006 case GET_BUILT_IN_DISPLAY:
5007 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005008 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005009 case GET_DISPLAY_CONFIGS:
5010 case GET_DISPLAY_STATS:
5011 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5012 // Calling setTransactionState is safe, because you need to have been
5013 // granted a reference to Client* and Handle* to do anything with it.
5014 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005015 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005016 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005017 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005018 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005019 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 return OK;
5021 }
5022 case CAPTURE_LAYERS:
5023 case CAPTURE_SCREEN: {
5024 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005025 IPCThreadState* ipc = IPCThreadState::self();
5026 const int pid = ipc->getCallingPid();
5027 const int uid = ipc->getCallingUid();
5028 if ((uid != AID_GRAPHICS) &&
5029 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5030 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5031 return PERMISSION_DENIED;
5032 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005033 return OK;
5034 }
5035 // The following codes are deprecated and should never be allowed to access SF.
5036 case CONNECT_DISPLAY_UNUSED:
5037 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5038 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5039 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005042
5043 // These codes are used for the IBinder protocol to either interrogate the recipient
5044 // side of the transaction for its canonical interface descriptor or to dump its state.
5045 // We let them pass by default.
5046 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5047 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5048 code == IBinder::SYSPROPS_TRANSACTION) {
5049 return OK;
5050 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005051 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005053 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5055 return OK;
5056 }
5057 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5058 return PERMISSION_DENIED;
5059#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005060}
5061
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5063 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005064 status_t credentialCheck = CheckTransactCodeCredentials(code);
5065 if (credentialCheck != OK) {
5066 return credentialCheck;
5067 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005068
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005069 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5070 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005071 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005072 IPCThreadState* ipc = IPCThreadState::self();
5073 const int uid = ipc->getCallingUid();
5074 if (CC_UNLIKELY(uid != AID_SYSTEM
5075 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005076 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005077 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005078 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 return PERMISSION_DENIED;
5080 }
5081 int n;
5082 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005083 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005084 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005085 return NO_ERROR;
5086 case 1002: // SHOW_UPDATES
5087 n = data.readInt32();
5088 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005089 invalidateHwcGeometry();
5090 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005092 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005093 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005094 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005096 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005097 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005098 setTransactionFlags(
5099 eTransactionNeeded|
5100 eDisplayTransactionNeeded|
5101 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005102 return NO_ERROR;
5103 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005104 case 1006:{ // send empty update
5105 signalRefresh();
5106 return NO_ERROR;
5107 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005108 case 1008: // toggle use of hw composer
5109 n = data.readInt32();
5110 mDebugDisableHWC = n ? 1 : 0;
5111 invalidateHwcGeometry();
5112 repaintEverything();
5113 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005114 case 1009: // toggle use of transform hint
5115 n = data.readInt32();
5116 mDebugDisableTransformHint = n ? 1 : 0;
5117 invalidateHwcGeometry();
5118 repaintEverything();
5119 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005121 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 reply->writeInt32(0);
5123 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005124 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005125 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 return NO_ERROR;
5127 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005128 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005129 if (!display) {
5130 return NAME_NOT_FOUND;
5131 }
5132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005133 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005134 return NO_ERROR;
5135 }
5136 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005137 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005138 // daltonize
5139 n = data.readInt32();
5140 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005141 case 1:
5142 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5143 break;
5144 case 2:
5145 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5146 break;
5147 case 3:
5148 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5149 break;
5150 default:
5151 mDaltonizer.setType(ColorBlindnessType::None);
5152 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005153 }
5154 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005155 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005156 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005157 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005158 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005159
5160 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005161 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005162 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005163 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005165 // apply a color matrix
5166 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005167 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005168 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005169 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005170 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005171 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005174 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005175 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005177
5178 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5179 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005181 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5182 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5183 }
5184
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005186 return NO_ERROR;
5187 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005188 // This is an experimental interface
5189 // Needs to be shifted to proper binder interface when we productize
5190 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005191 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005192 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005193 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005194 return NO_ERROR;
5195 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005196 case 1017: {
5197 n = data.readInt32();
5198 mForceFullDamage = static_cast<bool>(n);
5199 return NO_ERROR;
5200 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005201 case 1018: { // Modify Choreographer's phase offset
5202 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005203 if (mUseScheduler) {
5204 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5205 } else {
5206 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5207 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005208 return NO_ERROR;
5209 }
5210 case 1019: { // Modify SurfaceFlinger's phase offset
5211 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005212 if (mUseScheduler) {
5213 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5214 } else {
5215 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5216 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005217 return NO_ERROR;
5218 }
Irvel468051e2016-06-13 16:44:44 -07005219 case 1020: { // Layer updates interceptor
5220 n = data.readInt32();
5221 if (n) {
5222 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005223 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005224 }
5225 else{
5226 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005227 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005228 }
5229 return NO_ERROR;
5230 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005231 case 1021: { // Disable HWC virtual displays
5232 n = data.readInt32();
5233 mUseHwcVirtualDisplays = !n;
5234 return NO_ERROR;
5235 }
Romain Guy0147a172017-06-01 13:53:56 -07005236 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005238 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005239
Chia-I Wu28f320b2018-05-03 11:02:56 -07005240 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005241 return NO_ERROR;
5242 }
Romain Guy54f154a2017-10-24 21:40:32 +01005243 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005244 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005245 invalidateHwcGeometry();
5246 repaintEverything();
5247 return NO_ERROR;
5248 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005249 // Deprecate, use 1030 to check whether the device is color managed.
5250 case 1024: {
5251 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005252 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005253 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005254 n = data.readInt32();
5255 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005256 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005257 mTracing.enable();
5258 doTracing("tracing.enable");
5259 reply->writeInt32(NO_ERROR);
5260 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005261 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005262 status_t err = mTracing.disable();
5263 reply->writeInt32(err);
5264 }
5265 return NO_ERROR;
5266 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005267 case 1026: { // Get layer tracing status
5268 reply->writeBool(mTracing.isEnabled());
5269 return NO_ERROR;
5270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005271 // Is a DisplayColorSetting supported?
5272 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005273 const auto display = getDefaultDisplayDevice();
5274 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005275 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005276 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005277
5278 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5279 switch (setting) {
5280 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005281 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005282 break;
5283 case DisplayColorSetting::UNMANAGED:
5284 reply->writeBool(true);
5285 break;
5286 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005287 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005288 break;
5289 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005290 reply->writeBool(
5291 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005292 break;
5293 }
5294 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005295 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005296 // Is VrFlinger active?
5297 case 1028: {
5298 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005299 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005300 return NO_ERROR;
5301 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005302 // Is device color managed?
5303 case 1030: {
5304 reply->writeBool(useColorManagement);
5305 return NO_ERROR;
5306 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005307 // Override default composition data space
5308 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5309 // && adb shell stop zygote && adb shell start zygote
5310 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5311 // adb shell stop zygote && adb shell start zygote
5312 case 1031: {
5313 Mutex::Autolock _l(mStateLock);
5314 n = data.readInt32();
5315 if (n) {
5316 n = data.readInt32();
5317 if (n) {
5318 Dataspace dataspace = static_cast<Dataspace>(n);
5319 if (!validateCompositionDataspace(dataspace)) {
5320 return BAD_VALUE;
5321 }
5322 mDefaultCompositionDataspace = dataspace;
5323 }
5324 n = data.readInt32();
5325 if (n) {
5326 Dataspace dataspace = static_cast<Dataspace>(n);
5327 if (!validateCompositionDataspace(dataspace)) {
5328 return BAD_VALUE;
5329 }
5330 mWideColorGamutCompositionDataspace = dataspace;
5331 }
5332 } else {
5333 // restore composition data space.
5334 mDefaultCompositionDataspace = defaultCompositionDataspace;
5335 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5336 }
5337 return NO_ERROR;
5338 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005339 }
5340 }
5341 return err;
5342}
5343
Steven Thomas6d8110b2017-08-31 18:24:21 -07005344void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005345 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005346 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005347}
5348
Ana Krulec7d1d6832018-12-27 11:10:09 -08005349void SurfaceFlinger::repaintEverythingForHWC() {
5350 mRepaintEverything = true;
5351 mEventQueue->invalidateForHWC();
5352}
5353
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005354// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5355class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005356public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5358 ~WindowDisconnector() {
5359 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005360 }
5361
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362private:
5363 ANativeWindow* mWindow;
5364 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005365};
5366
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005367status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005368 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5369 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005370 uint32_t reqWidth, uint32_t reqHeight,
5371 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005372 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005373 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005375 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005376
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005377 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5378
Chia-I Wu20261cb2018-08-23 12:55:44 -07005379 sp<DisplayDevice> display;
5380 {
5381 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005382
Chia-I Wu20261cb2018-08-23 12:55:44 -07005383 display = getDisplayDeviceLocked(displayToken);
5384 if (!display) return BAD_VALUE;
5385
Chia-I Wucb023152018-08-28 12:57:23 -07005386 // set the requested width/height to the logical display viewport size
5387 // by default
5388 if (reqWidth == 0 || reqHeight == 0) {
5389 reqWidth = uint32_t(display->getViewport().width());
5390 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005391 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005392 }
5393
Peiyong Lin0e003c92018-09-17 11:09:51 -07005394 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5395 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005396
5397 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005398 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005399 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5400 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005401}
5402
5403status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5405 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005406 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005407 ATRACE_CALL();
5408
5409 class LayerRenderArea : public RenderArea {
5410 public:
Robert Carr578038f2018-03-09 12:25:24 -08005411 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005412 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5413 bool childrenOnly)
5414 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005415 mLayer(layer),
5416 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005417 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005418 mFlinger(flinger),
5419 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005420 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005421 Rect getBounds() const override {
5422 const Layer::State& layerState(mLayer->getDrawingState());
5423 return mLayer->getBufferSize(layerState);
5424 }
Marissa Wall61c58622018-07-18 10:12:20 -07005425 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005426 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005427 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005428 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005429 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005430 }
chaviwa76b2712017-09-20 12:02:26 -07005431 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005432 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005433 Rect getSourceCrop() const override {
5434 if (mCrop.isEmpty()) {
5435 return getBounds();
5436 } else {
5437 return mCrop;
5438 }
5439 }
Robert Carr578038f2018-03-09 12:25:24 -08005440 class ReparentForDrawing {
5441 public:
5442 const sp<Layer>& oldParent;
5443 const sp<Layer>& newParent;
5444
5445 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5446 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005447 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005448 }
Robert Carr15eae092018-03-23 13:43:53 -07005449 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005450 };
5451
5452 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005453 const Rect sourceCrop = getSourceCrop();
5454 // no need to check rotation because there is none
5455 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5456 sourceCrop.height() != getReqHeight();
5457
Robert Carr578038f2018-03-09 12:25:24 -08005458 if (!mChildrenOnly) {
5459 mTransform = mLayer->getTransform().inverse();
5460 drawLayers();
5461 } else {
5462 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005463 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005464 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5465 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005466
5467 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5468 drawLayers();
5469 }
5470 }
chaviwa76b2712017-09-20 12:02:26 -07005471
chaviwa76b2712017-09-20 12:02:26 -07005472 private:
chaviw7206d492017-11-10 16:16:12 -08005473 const sp<Layer> mLayer;
5474 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005475
5476 // In the "childrenOnly" case we reparent the children to a screenshot
5477 // layer which has no properties set and which does not draw.
5478 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005479 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005480 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005481
5482 SurfaceFlinger* mFlinger;
5483 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005484 };
5485
5486 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5487 auto parent = layerHandle->owner.promote();
5488
Robert Carr2e102c92018-10-23 12:11:15 -07005489 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005490 ALOGE("captureLayers called with a removed parent");
5491 return NAME_NOT_FOUND;
5492 }
5493
Robert Carr578038f2018-03-09 12:25:24 -08005494 const int uid = IPCThreadState::self()->getCallingUid();
5495 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005496 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005497 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5498 return PERMISSION_DENIED;
5499 }
5500
chaviw7206d492017-11-10 16:16:12 -08005501 Rect crop(sourceCrop);
5502 if (sourceCrop.width() <= 0) {
5503 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005504 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005505 }
5506
5507 if (sourceCrop.height() <= 0) {
5508 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005509 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005510 }
5511
5512 int32_t reqWidth = crop.width() * frameScale;
5513 int32_t reqHeight = crop.height() * frameScale;
5514
Chia-I Wu20261cb2018-08-23 12:55:44 -07005515 // really small crop or frameScale
5516 if (reqWidth <= 0) {
5517 reqWidth = 1;
5518 }
5519 if (reqHeight <= 0) {
5520 reqHeight = 1;
5521 }
5522
Peiyong Lin0e003c92018-09-17 11:09:51 -07005523 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005524
Robert Carr578038f2018-03-09 12:25:24 -08005525 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005526 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5527 if (!layer->isVisible()) {
5528 return;
Robert Carr578038f2018-03-09 12:25:24 -08005529 } else if (childrenOnly && layer == parent.get()) {
5530 return;
chaviwa76b2712017-09-20 12:02:26 -07005531 }
5532 visitor(layer);
5533 });
5534 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005535 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005536}
5537
5538status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5539 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005540 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005541 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005542 bool useIdentityTransform) {
5543 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005544
Peiyong Lin0e003c92018-09-17 11:09:51 -07005545 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005546 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5547 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005548 *outBuffer =
5549 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5550 static_cast<android_pixel_format>(reqPixelFormat), 1,
5551 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005552
5553 // This mutex protects syncFd and captureResult for communication of the return values from the
5554 // main thread back to this Binder thread
5555 std::mutex captureMutex;
5556 std::condition_variable captureCondition;
5557 std::unique_lock<std::mutex> captureLock(captureMutex);
5558 int syncFd = -1;
5559 std::optional<status_t> captureResult;
5560
Robert Carr03480e22018-01-04 16:02:06 -08005561 const int uid = IPCThreadState::self()->getCallingUid();
5562 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5563
Dominik Laskowski8c001672018-05-30 16:52:06 -07005564 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 // If there is a refresh pending, bug out early and tell the binder thread to try again
5566 // after the refresh.
5567 if (mRefreshPending) {
5568 ATRACE_NAME("Skipping screenshot for now");
5569 std::unique_lock<std::mutex> captureLock(captureMutex);
5570 captureResult = std::make_optional<status_t>(EAGAIN);
5571 captureCondition.notify_one();
5572 return;
5573 }
5574
5575 status_t result = NO_ERROR;
5576 int fd = -1;
5577 {
5578 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005580 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5581 useIdentityTransform, forSystem, &fd);
5582 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 }
5584
5585 {
5586 std::unique_lock<std::mutex> captureLock(captureMutex);
5587 syncFd = fd;
5588 captureResult = std::make_optional<status_t>(result);
5589 captureCondition.notify_one();
5590 }
5591 });
5592
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005593 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 while (*captureResult == EAGAIN) {
5597 captureResult.reset();
5598 result = postMessageAsync(message);
5599 if (result != NO_ERROR) {
5600 return result;
5601 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005602 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 }
5604 result = *captureResult;
5605 }
5606
5607 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005608 sync_wait(syncFd, -1);
5609 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005610 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005611
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005613}
5614
chaviwa76b2712017-09-20 12:02:26 -07005615void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005616 TraverseLayersFunction traverseLayers,
Alec Mouri79108df2019-02-04 19:33:44 +00005617 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005618 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005619
Alec Mouri79108df2019-02-04 19:33:44 +00005620 auto& engine(getRenderEngine());
5621
chaviwa76b2712017-09-20 12:02:26 -07005622 const auto reqWidth = renderArea.getReqWidth();
5623 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005624 const auto sourceCrop = renderArea.getSourceCrop();
5625 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005626
Alec Mouri79108df2019-02-04 19:33:44 +00005627 engine.setOutputDataSpace(renderArea.getReqDataSpace());
5628 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005629
Alec Mouri79108df2019-02-04 19:33:44 +00005630 // make sure to clear all GL error flags
5631 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005632
Alec Mouri79108df2019-02-04 19:33:44 +00005633 // set-up our viewport
5634 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
5635 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005636
chaviw50da5042018-04-09 13:49:37 -07005637 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Alec Mouri79108df2019-02-04 19:33:44 +00005638 // redraw the screen entirely...
5639 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005640
chaviwa76b2712017-09-20 12:02:26 -07005641 traverseLayers([&](Layer* layer) {
Alec Mouri79108df2019-02-04 19:33:44 +00005642 engine.setColorTransform(layer->getColorTransform());
5643 layer->draw(renderArea, useIdentityTransform);
5644 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005645 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005646}
5647
chaviwa76b2712017-09-20 12:02:26 -07005648status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5649 TraverseLayersFunction traverseLayers,
5650 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005651 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005652 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005653 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005654 ATRACE_CALL();
5655
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005656 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005657
5658 traverseLayers([&](Layer* layer) {
5659 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5660 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005661
Robert Carr03480e22018-01-04 16:02:06 -08005662 // We allow the system server to take screenshots of secure layers for
5663 // use in situations like the Screen-rotation animation and place
5664 // the impetus on WindowManager to not persist them.
5665 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005666 ALOGW("FB is protected: PERMISSION_DENIED");
5667 return PERMISSION_DENIED;
5668 }
Alec Mouri79108df2019-02-04 19:33:44 +00005669 auto& engine(getRenderEngine());
5670
5671 // this binds the given EGLImage as a framebuffer for the
5672 // duration of this scope.
5673 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
5674 if (bufferBond.getStatus() != NO_ERROR) {
5675 ALOGE("got ANWB binding error while taking screenshot");
5676 return INVALID_OPERATION;
5677 }
5678
5679 // this will in fact render into our dequeued buffer
5680 // via an FBO, which means we didn't have to create
5681 // an EGLSurface and therefore we're not
5682 // dependent on the context's EGLConfig.
5683 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
5684
5685 base::unique_fd syncFd = engine.flush();
5686 if (syncFd < 0) {
5687 engine.finish();
5688 }
5689 *outSyncFd = syncFd.release();
5690
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005692}
5693
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005694// ---------------------------------------------------------------------------
5695
Dan Stoza412903f2017-04-27 13:42:17 -07005696void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5697 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005698}
5699
Dan Stoza412903f2017-04-27 13:42:17 -07005700void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5701 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005702}
5703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005704void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005705 const LayerVector::Visitor& visitor) {
5706 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005707 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005708 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005709 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005710 continue;
5711 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005712 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005713 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005714 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005715 return;
5716 }
chaviwa76b2712017-09-20 12:02:26 -07005717 if (!layer->isVisible()) {
5718 return;
5719 }
5720 visitor(layer);
5721 });
5722 }
5723}
5724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005725}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005726
Lloyd Pique074e8122018-07-26 12:57:23 -07005727
Mathias Agopian3f844832013-08-07 21:24:32 -07005728#if defined(__gl_h_)
5729#error "don't include gl/gl.h in this file"
5730#endif
5731
5732#if defined(__gl2_h_)
5733#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005734#endif