blob: acf00139ce2f61af83c7ed5b46d400313a5821bf [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080079#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070082#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080083#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070084#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Steven Thomasb02664d2017-07-26 18:48:28 -070089#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070090#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070091#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070092#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070093#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070094#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070096#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/EventControlThread.h"
98#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070099#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700101#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800102#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700105
David Sodman7e4ae112018-02-09 15:02:28 -0800106#include "android-base/stringprintf.h"
107
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700110#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900112#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
chaviw1d044282017-09-27 12:19:28 -0700114#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900115#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700118
Jaesoo Lee43518572017-01-23 19:03:16 +0900119using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800122using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700123using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700124using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700125using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700126using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127
Steven Thomasb02664d2017-07-26 18:48:28 -0700128namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700129
130#pragma clang diagnostic push
131#pragma clang diagnostic error "-Wswitch-enum"
132
133bool isWideColorMode(const ColorMode colorMode) {
134 switch (colorMode) {
135 case ColorMode::DISPLAY_P3:
136 case ColorMode::ADOBE_RGB:
137 case ColorMode::DCI_P3:
138 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700139 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700140 case ColorMode::BT2100_PQ:
141 case ColorMode::BT2100_HLG:
142 return true;
143 case ColorMode::NATIVE:
144 case ColorMode::STANDARD_BT601_625:
145 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
146 case ColorMode::STANDARD_BT601_525:
147 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
148 case ColorMode::STANDARD_BT709:
149 case ColorMode::SRGB:
150 return false;
151 }
152 return false;
153}
154
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700155ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
156 switch (rotation) {
157 case ISurfaceComposer::eRotateNone:
158 return ui::Transform::ROT_0;
159 case ISurfaceComposer::eRotate90:
160 return ui::Transform::ROT_90;
161 case ISurfaceComposer::eRotate180:
162 return ui::Transform::ROT_180;
163 case ISurfaceComposer::eRotate270:
164 return ui::Transform::ROT_270;
165 }
166 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
167 return ui::Transform::ROT_0;
168}
169
Peiyong Linfca547f2018-07-09 13:03:33 -0700170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Peiyong Lin9d846a52018-11-05 13:18:20 -0800185// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
186bool validateCompositionDataspace(Dataspace dataspace) {
187 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
188}
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190} // namespace anonymous
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192// ---------------------------------------------------------------------------
193
Mathias Agopian99b49842011-06-27 16:05:52 -0700194const String16 sHardwareTest("android.permission.HARDWARE_TEST");
195const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
196const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
197const String16 sDump("android.permission.DUMP");
198
199// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
201int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700202int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700203bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800204uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800205bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800206bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800207int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600208bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700209int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700210bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700211bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700212Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
213ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
214Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
215ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700216
Kalle Raitaa099a242017-01-11 11:17:29 -0800217std::string getHwcServiceName() {
218 char value[PROPERTY_VALUE_MAX] = {};
219 property_get("debug.sf.hwc_service_name", value, "default");
220 ALOGI("Using HWComposer service: '%s'", value);
221 return std::string(value);
222}
223
224bool useTrebleTestingOverride() {
225 char value[PROPERTY_VALUE_MAX] = {};
226 property_get("debug.sf.treble_testing_override", value, "false");
227 ALOGI("Treble testing override: '%s'", value);
228 return std::string(value) == "true";
229}
230
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
232 switch(displayColorSetting) {
233 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700236 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800237 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700238 return std::string("Enhanced");
239 default:
240 return std::string("Unknown ") +
241 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800243}
244
David Sodmanbc815282017-11-05 18:57:52 -0800245SurfaceFlingerBE::SurfaceFlingerBE()
246 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800247 mFrameBuckets(),
248 mTotalTime(0),
249 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800250 mComposerSequenceId(0) {
251}
252
Lloyd Pique90c115d2018-09-18 21:39:42 -0700253SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
254 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800255 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700256 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700257 mTransactionPending(false),
258 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700259 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700260 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800263 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800264 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800265 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700267 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700268 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700269 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700270 mDebugInTransaction(0),
271 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700272 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800273 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700274 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700275 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800276 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800277 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800278 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700279 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700280 mMainThreadId(std::this_thread::get_id()),
281 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800282
Lloyd Pique90c115d2018-09-18 21:39:42 -0700283SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
284 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 vsyncPhaseOffsetNs = vsync_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 sfVsyncPhaseOffsetNs = vsync_sf_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 mDefaultCompositionDataspace =
309 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
310 mWideColorGamutCompositionDataspace =
311 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
312 defaultCompositionDataspace = mDefaultCompositionDataspace;
313 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
314 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
315 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
316 wideColorGamutCompositionPixelFormat =
317 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
322 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
323 switch (tmpPrimaryDisplayOrientation) {
324 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800338
Lloyd Pique90c115d2018-09-18 21:39:42 -0700339 mPrimaryDispSync =
340 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
341 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 property_get("debug.sf.showupdates", value, "0");
350 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700352 property_get("debug.sf.ddms", value, "0");
353 mDebugDDMS = atoi(value);
354 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700355 if (!startDdmConnection()) {
356 // start failed, and DDMS debugging not enabled
357 mDebugDDMS = 0;
358 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700359 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700360 ALOGI_IF(mDebugRegion, "showupdates enabled");
361 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700362
363 property_get("debug.sf.disable_backpressure", value, "0");
364 mPropagateBackpressure = !atoi(value);
365 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700366
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800367 property_get("debug.sf.enable_hwc_vds", value, "0");
368 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800369 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800371 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800372 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800373 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700374
Yiwei Zhang243b3782018-05-15 17:40:04 -0700375 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200379 property_get("debug.sf.early_phase_offset_ns", value, "-1");
380 const int earlySfOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
383 const int earlyGlSfOffsetNs = atoi(value);
384
385 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
386 const int earlyAppOffsetNs = atoi(value);
387
388 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
389 const int earlyGlAppOffsetNs = atoi(value);
390
Ana Krulec98b5b242018-08-10 15:03:23 -0700391 property_get("debug.sf.use_scheduler", value, "0");
392 mUseScheduler = atoi(value);
393
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200394 const VSyncModulator::Offsets earlyOffsets =
395 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
396 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
397 const VSyncModulator::Offsets earlyGlOffsets =
398 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
399 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
400 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
401 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700402
Romain Guy11d63f42017-07-20 12:47:14 -0700403 // We should be reading 'persist.sys.sf.color_saturation' here
404 // but since /data may be encrypted, we need to wait until after vold
405 // comes online to attempt to read the property. The property is
406 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800407
408 if (useTrebleTestingOverride()) {
409 // Without the override SurfaceFlinger cannot connect to HIDL
410 // services that are not listed in the manifests. Considered
411 // deriving the setting from the set service name, but it
412 // would be brittle if the name that's not 'default' is used
413 // for production purposes later on.
414 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418void SurfaceFlinger::onFirstRef()
419{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800420 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421}
422
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423SurfaceFlinger::~SurfaceFlinger()
424{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425}
426
Dan Stozac7014012014-02-14 15:03:43 -0800427void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428{
429 // the window manager died on us. prepare its eulogy.
430
Andy McFadden13a082e2012-08-24 10:16:42 -0700431 // restore initial conditions (default device unblank, etc)
432 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433
434 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700435 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436}
437
Robert Carr1db73f62016-12-21 12:58:51 -0800438static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700439 status_t err = client->initCheck();
440 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800441 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800442 }
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return nullptr;
444}
445
446sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
447 return initClient(new Client(this));
448}
449
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700450sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
451 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452{
453 class DisplayToken : public BBinder {
454 sp<SurfaceFlinger> flinger;
455 virtual ~DisplayToken() {
456 // no more references, this display must be terminated
457 Mutex::Autolock _l(flinger->mStateLock);
458 flinger->mCurrentState.displays.removeItem(this);
459 flinger->setTransactionFlags(eDisplayTransactionNeeded);
460 }
461 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700462 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700463 : flinger(flinger) {
464 }
465 };
466
467 sp<BBinder> token = new DisplayToken(this);
468
469 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 // Display ID is assigned when virtual display is allocated by HWC.
471 DisplayDeviceState state;
472 state.isSecure = secure;
473 state.displayName = displayName;
474 mCurrentState.displays.add(token, state);
475 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 return token;
477}
478
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 Mutex::Autolock _l(mStateLock);
481
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
483 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 return;
486 }
487
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
489 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 ALOGE("destroyDisplay called for non-virtual display");
491 return;
492 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 mInterceptor->saveDisplayDeletion(state.sequenceId);
494 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 setTransactionFlags(eDisplayTransactionNeeded);
496}
497
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499 std::optional<DisplayId> displayId;
500
501 if (id == HWC_DISPLAY_PRIMARY) {
502 displayId = getInternalDisplayId();
503 } else if (id == HWC_DISPLAY_EXTERNAL) {
504 displayId = getExternalDisplayId();
505 }
506
507 if (!displayId) {
508 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800509 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511
512 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513}
514
Ady Abraham37965d42018-11-01 13:43:32 -0700515status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
516 if (!outGetColorManagement) {
517 return BAD_VALUE;
518 }
519 *outGetColorManagement = useColorManagement;
520 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700521}
522
Lloyd Pique441d5042018-10-18 16:49:51 -0700523HWComposer& SurfaceFlinger::getHwComposer() const {
524 return mCompositionEngine->getHwComposer();
525}
526
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700527renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
528 return mCompositionEngine->getRenderEngine();
529}
530
Lloyd Pique70d91362018-10-18 16:02:55 -0700531compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
532 return *mCompositionEngine.get();
533}
534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535void SurfaceFlinger::bootFinished()
536{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700537 if (mStartPropertySetThread->join() != NO_ERROR) {
538 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800539 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 const nsecs_t now = systemTime();
541 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000542 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543
544 // wait patiently for the window manager death
545 const String16 name("window");
546 sp<IBinder> window(defaultServiceManager()->getService(name));
547 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700548 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
Robert Carr720e5062018-07-30 17:45:14 -0700550 sp<IBinder> input(defaultServiceManager()->getService(
551 String16("inputflinger")));
552 if (input == nullptr) {
553 ALOGE("Failed to link to input service");
554 } else {
555 mInputFlinger = interface_cast<IInputFlinger>(input);
556 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 if (mVrFlinger) {
559 mVrFlinger->OnBootFinished();
560 }
561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 // formerly we would just kill the process, but we now ask it to exit so it
564 // can choose where to stop the animation.
565 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700566
567 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
568 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
569 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700570
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800571 postMessageAsync(new LambdaMessage([this] {
572 readPersistentProperties();
573 mBootStage = BootStage::FINISHED;
574 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575}
576
Dan Stoza436ccf32018-06-21 12:10:12 -0700577uint32_t SurfaceFlinger::getNewTexture() {
578 {
579 std::lock_guard lock(mTexturePoolMutex);
580 if (!mTexturePool.empty()) {
581 uint32_t name = mTexturePool.back();
582 mTexturePool.pop_back();
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
584 return name;
585 }
586
587 // The pool was too small, so increase it for the future
588 ++mTexturePoolSize;
589 }
590
591 // The pool was empty, so we need to get a new texture name directly using a
592 // blocking call to the main thread
593 uint32_t name = 0;
594 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
595 return name;
596}
597
Mathias Agopian3f844832013-08-07 21:24:32 -0700598void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700599 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
607
Thierry Strudel2924d012017-08-14 15:19:37 -0700608 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611
Dominik Laskowski83b88212018-12-11 13:34:06 -0800612 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800613
Steven Thomasb02664d2017-07-26 18:48:28 -0700614 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700615 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700616 mScheduler = getFactory().createScheduler([this](bool enabled) {
617 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
618 });
619
Ana Krulec98b5b242018-08-10 15:03:23 -0700620 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700621 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800622 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 impl::EventThread::InterceptVSyncsCallback());
624 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700625 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800626 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mInterceptor->saveVSyncEvent(timestamp);
628 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700631 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
632 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 } else {
634 mEventThreadSource =
635 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
636 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
637 mEventThread =
638 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 impl::EventThread::InterceptVSyncsCallback(),
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
644
645 mSFEventThread =
646 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800651 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700663 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700665 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700666
667 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
668 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700669 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
670 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800671 // Process any initial hotplug and resulting display changes.
672 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 const auto display = getDefaultDisplayDeviceLocked();
674 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700675 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800677
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 // This callback is called from the vr flinger dispatch thread. We
681 // need to call signalTransaction(), which requires holding
682 // mStateLock when we're not on the main thread. Acquiring
683 // mStateLock from the vr flinger dispatch thread might trigger a
684 // deadlock in surface flinger (see b/66916578), so post a message
685 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
688 mVrFlingerRequestsDisplay = requestDisplay;
689 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700690 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700692 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
693 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700694 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700695 .value_or(0),
696 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 if (!mVrFlinger) {
698 ALOGE("Failed to start vrflinger");
699 }
700 }
701
Lloyd Pique90c115d2018-09-18 21:39:42 -0700702 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700704
Mathias Agopian92a979a2012-08-02 18:32:23 -0700705 // initialize our drawing state
706 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700707
Andy McFadden13a082e2012-08-24 10:16:42 -0700708 // set initial conditions (e.g. unblank default device)
709 initializeDisplays();
710
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700712
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700714
715 const bool presentFenceReliable =
716 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
717 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718
719 if (mStartPropertySetThread->Start() != NO_ERROR) {
720 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722
Ana Krulec7d1d6832018-12-27 11:10:09 -0800723 if (mUseScheduler) {
724 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
725 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
Ana Krulecb43429d2019-01-09 14:28:51 -0800726 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
727 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800728 }
729
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700731}
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 Mutex::Autolock _l(mStateLock);
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736 char value[PROPERTY_VALUE_MAX];
737
738 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700740 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100742
743 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700744 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700745}
746
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800748 // Start boot animation service by setting a property mailbox
749 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700750 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800751 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 if (mStartPropertySetThread->join() != NO_ERROR) {
753 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800754 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700758 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700762 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800766
Jamie Gennis582270d2011-08-17 18:19:00 -0700767bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800769 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800770 return authenticateSurfaceTextureLocked(bufferProducer);
771}
772
773bool SurfaceFlinger::authenticateSurfaceTextureLocked(
774 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800775 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800776 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800777}
778
Brian Anderson6b376712017-04-04 10:51:39 -0700779status_t SurfaceFlinger::getSupportedFrameTimestamps(
780 std::vector<FrameEvent>* outSupported) const {
781 *outSupported = {
782 FrameEvent::REQUESTED_PRESENT,
783 FrameEvent::ACQUIRE,
784 FrameEvent::LATCH,
785 FrameEvent::FIRST_REFRESH_START,
786 FrameEvent::LAST_REFRESH_START,
787 FrameEvent::GPU_COMPOSITION_DONE,
788 FrameEvent::DEQUEUE_READY,
789 FrameEvent::RELEASE,
790 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700791 ConditionalLock _l(mStateLock,
792 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700793 if (!getHwComposer().hasCapability(
794 HWC2::Capability::PresentFenceIsNotReliable)) {
795 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
796 }
797 return NO_ERROR;
798}
799
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700800status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
801 Vector<DisplayInfo>* configs) {
802 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 return BAD_VALUE;
804 }
805
Dominik Laskowski075d3172018-05-24 15:50:06 -0700806 const auto displayId = getPhysicalDisplayId(displayToken);
807 if (!displayId) {
808 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700809 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 // TODO: Not sure if display density should handled by SF any longer
812 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700815 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800816 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 }
819 return density;
820 }
821 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700824 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 return getDensityFromProperty("ro.sf.lcd_density"); }
826 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 ConditionalLock _l(mStateLock,
831 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700832 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 DisplayInfo info = DisplayInfo();
834
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 float xdpi = hwConfig->getDpiX();
836 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700838 info.w = hwConfig->getWidth();
839 info.h = hwConfig->getHeight();
840 // Default display viewport to display width and height
841 info.viewportW = info.w;
842 info.viewportH = info.h;
843
Dominik Laskowski075d3172018-05-24 15:50:06 -0700844 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 // The density of the device is provided by a build property
846 float density = Density::getBuildDensity() / 160.0f;
847 if (density == 0) {
848 // the build doesn't provide a density -- this is wrong!
849 // use xdpi instead
850 ALOGE("ro.sf.lcd_density must be defined as a build property");
851 density = xdpi / 160.0f;
852 }
853 if (Density::getEmuDensity()) {
854 // if "qemu.sf.lcd_density" is specified, it overrides everything
855 xdpi = ydpi = density = Density::getEmuDensity();
856 density /= 160.0f;
857 }
858 info.density = density;
859
860 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700861 const auto display = getDefaultDisplayDeviceLocked();
862 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863
864 // This is for screenrecord
865 const Rect viewport = display->getViewport();
866 if (viewport.isValid()) {
867 info.viewportW = uint32_t(viewport.getWidth());
868 info.viewportH = uint32_t(viewport.getHeight());
869 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 } else {
871 // TODO: where should this value come from?
872 static const int TV_DENSITY = 213;
873 info.density = TV_DENSITY / 160.0f;
874 info.orientation = 0;
875 }
876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 info.xdpi = xdpi;
878 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900880 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881
Andy McFadden91b2ca82014-06-13 14:04:23 -0700882 // This is how far in advance a buffer must be queued for
883 // presentation at a given time. If you want a buffer to appear
884 // on the screen at time N, you must submit the buffer before
885 // (N - presentationDeadline).
886 //
887 // Normally it's one full refresh period (to give SF a chance to
888 // latch the buffer), but this can be reduced by configuring a
889 // DispSync offset. Any additional delays introduced by the hardware
890 // composer or panel must be accounted for here.
891 //
892 // We add an additional 1ms to allow for processing time and
893 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800895 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700896
897 // All non-virtual displays are currently considered secure.
898 info.secure = true;
899
Dominik Laskowski075d3172018-05-24 15:50:06 -0700900 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700901 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800902 std::swap(info.w, info.h);
903 }
904
Michael Wright28f24d02016-07-12 13:30:53 -0700905 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906 }
907
Dan Stoza7f7da322014-05-02 15:26:25 -0700908 return NO_ERROR;
909}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
912 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700913 return BAD_VALUE;
914 }
915
Ana Krulece588e312018-09-18 12:32:24 -0700916 if (mUseScheduler) {
917 mScheduler->getDisplayStatInfo(stats);
918 } else {
919 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
920 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
921 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
936 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800937 postMessageAsync(new LambdaMessage(
938 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800939 return NO_ERROR;
940}
941
942status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800944 postMessageSync(new LambdaMessage(
945 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800946 return NO_ERROR;
947}
948
949void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
950 Vector<DisplayInfo> configs;
951 getDisplayConfigs(displayToken, &configs);
952 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
953 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
954 return;
955 }
956
957 const auto display = getDisplayDevice(displayToken);
958 if (!display) {
959 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
960 displayToken.get());
961 return;
962 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800964 ALOGW("Attempt to set active config %d for virtual display", mode);
965 return;
966 }
967 int currentDisplayPowerMode = display->getPowerMode();
968 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
969 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700970 return;
971 }
972
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700974 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800975 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700976 return;
977 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800978 if (mUseScheduler) {
979 mRefreshRateStats->setConfigMode(mode);
980 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981
Dominik Laskowski075d3172018-05-24 15:50:06 -0700982 const auto displayId = display->getId();
983 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700986 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800989 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -0700990}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
993 Vector<ColorMode>* outColorModes) {
994 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return BAD_VALUE;
996 }
997
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998 const auto displayId = getPhysicalDisplayId(displayToken);
999 if (!displayId) {
1000 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1016 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001017 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001018 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001023 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 Vector<ColorMode> modes;
1025 getDisplayColorModes(displayToken, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1027 if (mode < ColorMode::NATIVE || !exists) {
1028 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1029 decodeColorMode(mode).c_str(), mode, displayToken.get());
1030 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001031 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 const auto display = getDisplayDevice(displayToken);
1033 if (!display) {
1034 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1035 decodeColorMode(mode).c_str(), mode, displayToken.get());
1036 } else if (display->isVirtual()) {
1037 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1038 decodeColorMode(mode).c_str(), mode);
1039 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001040 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1041 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 }
1043 }));
1044
Michael Wright28f24d02016-07-12 13:30:53 -07001045 return NO_ERROR;
1046}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001047
Svetoslavd85084b2014-03-20 10:28:31 -07001048status_t SurfaceFlinger::clearAnimationFrameStats() {
1049 Mutex::Autolock _l(mStateLock);
1050 mAnimFrameTracker.clearStats();
1051 return NO_ERROR;
1052}
1053
1054status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1055 Mutex::Autolock _l(mStateLock);
1056 mAnimFrameTracker.getStats(outStats);
1057 return NO_ERROR;
1058}
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1061 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001062 Mutex::Autolock _l(mStateLock);
1063
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDeviceLocked(displayToken);
1065 if (!display) {
1066 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 return BAD_VALUE;
1068 }
1069
Peiyong Linfb069302018-04-25 14:34:31 -07001070 // At this point the DisplayDeivce should already be set up,
1071 // meaning the luminance information is already queried from
1072 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001074 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1075 capabilities.getDesiredMaxLuminance(),
1076 capabilities.getDesiredMaxAverageLuminance(),
1077 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001078
1079 return NO_ERROR;
1080}
1081
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001082status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1083 ui::PixelFormat* outFormat,
1084 ui::Dataspace* outDataspace,
1085 uint8_t* outComponentMask) const {
1086 if (!outFormat || !outDataspace || !outComponentMask) {
1087 return BAD_VALUE;
1088 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001089 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001090 if (!display || !display->getId()) {
1091 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1092 return BAD_VALUE;
1093 }
1094 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1095 outDataspace, outComponentMask);
1096}
1097
Kevin DuBois74e53772018-11-19 10:52:38 -08001098status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1099 bool enable, uint8_t componentMask,
1100 uint64_t maxFrames) const {
1101 const auto display = getDisplayDevice(displayToken);
1102 if (!display || !display->getId()) {
1103 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1104 return BAD_VALUE;
1105 }
1106
1107 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1108 componentMask, maxFrames);
1109}
1110
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001111status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1112 uint64_t maxFrames, uint64_t timestamp,
1113 DisplayedFrameStats* outStats) const {
1114 const auto display = getDisplayDevice(displayToken);
1115 if (!display || !display->getId()) {
1116 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1117 return BAD_VALUE;
1118 }
1119
1120 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1121 outStats);
1122}
1123
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001124status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1125 if (!outSupported) {
1126 return BAD_VALUE;
1127 }
1128 *outSupported = getRenderEngine().supportsProtectedContent();
1129 return NO_ERROR;
1130}
1131
Marissa Wallebc2c052019-01-16 19:16:55 -08001132status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1133 int32_t* outBufferId) {
1134 if (!outBufferId) {
1135 return BAD_VALUE;
1136 }
1137 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1138 return NO_ERROR;
1139}
1140
1141status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1142 mBufferStateLayerCache.release(token, bufferId);
1143 return NO_ERROR;
1144}
1145
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001146status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1147 bool* outIsWideColorDisplay) const {
1148 if (!displayToken || !outIsWideColorDisplay) {
1149 return BAD_VALUE;
1150 }
1151 Mutex::Autolock _l(mStateLock);
1152 const auto display = getDisplayDeviceLocked(displayToken);
1153 if (!display) {
1154 return BAD_VALUE;
1155 }
1156 *outIsWideColorDisplay = display->hasWideColorGamut();
1157 return NO_ERROR;
1158}
1159
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001160status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001161 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 if (mInjectVSyncs == enable) {
1165 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167
Dominik Laskowski83b88212018-12-11 13:34:06 -08001168 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001169
Ana Krulec98b5b242018-08-10 15:03:23 -07001170 // TODO(akrulec): Part of the Injector should be refactored, so that it
1171 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 if (enable) {
1173 ALOGV("VSync Injections enabled");
1174 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001175 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001176 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001177 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001178 impl::EventThread::InterceptVSyncsCallback(),
1179 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001181 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 } else {
1183 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001184 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185 }
1186
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001187 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001188 }));
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 return NO_ERROR;
1191}
1192
1193status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 Mutex::Autolock _l(mStateLock);
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 if (!mInjectVSyncs) {
1197 ALOGE("VSync Injections not enabled");
1198 return BAD_VALUE;
1199 }
1200 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1201 ALOGV("Injecting VSync inside SurfaceFlinger");
1202 mVSyncInjector->onInjectSyncEvent(when);
1203 }
1204 return NO_ERROR;
1205}
1206
Lloyd Pique755e3192018-01-31 16:46:15 -08001207status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1208 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001209 // Try to acquire a lock for 1s, fail gracefully
1210 const status_t err = mStateLock.timedLock(s2ns(1));
1211 const bool locked = (err == NO_ERROR);
1212 if (!locked) {
1213 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1214 return TIMED_OUT;
1215 }
1216
1217 outLayers->clear();
1218 mCurrentState.traverseInZOrder([&](Layer* layer) {
1219 outLayers->push_back(layer->getLayerDebugInfo());
1220 });
1221
1222 mStateLock.unlock();
1223 return NO_ERROR;
1224}
1225
Peiyong Linc6780972018-10-28 15:24:08 -07001226status_t SurfaceFlinger::getCompositionPreference(
1227 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1228 Dataspace* outWideColorGamutDataspace,
1229 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001230 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001231 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001232 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001233 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001234 return NO_ERROR;
1235}
1236
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001237// ----------------------------------------------------------------------------
1238
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001239sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1240 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001241 auto resyncCallback = makeResyncCallback([this] {
1242 Mutex::Autolock lock(mStateLock);
1243 return getVsyncPeriod();
1244 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001245
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 if (mUseScheduler) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001252 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001255 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001257 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001259}
1260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262
1263void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001276 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001286 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 if (res == NO_ERROR) {
1289 msg->wait();
1290 }
1291 return res;
1292}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295 do {
1296 waitForEvent();
1297 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001298}
1299
Dominik Laskowski83b88212018-12-11 13:34:06 -08001300nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1301 const auto displayId = getInternalDisplayId();
1302 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1303 return 0;
1304 }
1305
1306 const auto config = getHwComposer().getActiveConfig(*displayId);
1307 return config ? config->getVsyncPeriod() : 0;
1308}
1309
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310void SurfaceFlinger::enableHardwareVsync() {
1311 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001313 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001314 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001316 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317}
1318
Dominik Laskowski83b88212018-12-11 13:34:06 -08001319void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320 Mutex::Autolock _l(mHWVsyncLock);
1321
Jesse Hall948fe0c2013-10-14 12:56:09 -07001322 if (makeAvailable) {
1323 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001324 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1325 if (mUseScheduler) {
1326 mScheduler->makeHWSyncAvailable(true);
1327 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001329 // Hardware vsync is not currently available, so abort the resync
1330 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331 return;
1332 }
1333
Dominik Laskowski83b88212018-12-11 13:34:06 -08001334 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001335 return;
1336 }
1337
Ana Krulece588e312018-09-18 12:32:24 -07001338 if (mUseScheduler) {
1339 mScheduler->setVsyncPeriod(period);
1340 } else {
1341 mPrimaryDispSync->reset();
1342 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343
Ana Krulece588e312018-09-18 12:32:24 -07001344 if (!mPrimaryHWVsyncEnabled) {
1345 mPrimaryDispSync->beginResync();
1346 mEventControlThread->setVsyncEnabled(true);
1347 mPrimaryHWVsyncEnabled = true;
1348 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349 }
1350}
1351
Jesse Hall948fe0c2013-10-14 12:56:09 -07001352void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353 Mutex::Autolock _l(mHWVsyncLock);
1354 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001356 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357 mPrimaryHWVsyncEnabled = false;
1358 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001359 if (makeUnavailable) {
1360 mHWVsyncAvailable = false;
1361 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001362}
1363
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001366
Dan Stoza57164302017-05-08 14:03:54 -07001367 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001368 const nsecs_t last = lastResyncTime.exchange(now);
1369
1370 if (now - last > kIgnoreDelay) {
1371 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001372 }
1373}
1374
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001375void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1376 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 ATRACE_NAME("SF onVsync");
1378
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001381 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 return;
1387 }
1388
Dominik Laskowski075d3172018-05-24 15:50:06 -07001389 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001390 // For now, we don't do anything with external display vsyncs.
1391 return;
1392 }
1393
Ana Krulece588e312018-09-18 12:32:24 -07001394 if (mUseScheduler) {
1395 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001396 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001397 bool needsHwVsync = false;
1398 { // Scope for the lock
1399 Mutex::Autolock _l(mHWVsyncLock);
1400 if (mPrimaryHWVsyncEnabled) {
1401 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1402 }
1403 }
1404
1405 if (needsHwVsync) {
1406 enableHardwareVsync();
1407 } else {
1408 disableHardwareVsync(false);
1409 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001410 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001411}
1412
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001413void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001414 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1415 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001416}
1417
Ana Krulec7d1d6832018-12-27 11:10:09 -08001418void SurfaceFlinger::setRefreshRateTo(float newFps) {
1419 const auto displayId = getInternalDisplayId();
1420 if (!displayId || mBootStage != BootStage::FINISHED) {
1421 return;
1422 }
1423 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1424 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1425 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1426 // refresh cycle.
1427
1428 // Don't do any updating if the current fps is the same as the new one.
1429 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1430 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1431 if (currentVsyncPeriod == 0) {
1432 return;
1433 }
1434 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1435 // floating numbers.
1436 const float currentFps = 1e9 / currentVsyncPeriod;
1437 if (std::abs(currentFps - newFps) <= 1) {
1438 return;
1439 }
1440
1441 auto configs = getHwComposer().getConfigs(*displayId);
1442 for (int i = 0; i < configs.size(); i++) {
1443 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1444 if (vsyncPeriod == 0) {
1445 continue;
1446 }
1447 const float fps = 1e9 / vsyncPeriod;
1448 // TODO(b/113612090): There should be a better way at determining which config
1449 // has the right refresh rate.
1450 if (std::abs(fps - newFps) <= 1) {
1451 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1452 if (!display) return;
1453 // This is posted in async function to avoid deadlock when getDisplayDevice
1454 // requires mStateLock.
1455 setActiveConfigAsync(display, i);
1456 ATRACE_INT("FPS", newFps);
1457 }
1458 }
1459}
1460
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001461void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001462 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001463 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001464 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465
Lloyd Piqueba04e622017-12-14 17:11:26 -08001466 // Ignore events that do not have the right sequenceId.
1467 if (sequenceId != getBE().mComposerSequenceId) {
1468 return;
1469 }
1470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Only lock if we're not on the main thread. This function is normally
1472 // called on a hwbinder thread, but for the primary display it's called on
1473 // the main thread with the state lock already held, so don't attempt to
1474 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001475 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001478
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001479 if (std::this_thread::get_id() == mMainThreadId) {
1480 // Process all pending hot plug events immediately if we are on the main thread.
1481 processDisplayHotplugEventsLocked();
1482 }
1483
Lloyd Piqueba04e622017-12-14 17:11:26 -08001484 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001487void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001491 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001492 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001493}
1494
Dominik Laskowski075d3172018-05-24 15:50:06 -07001495void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001496 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (const auto displayId = getInternalDisplayId()) {
1499 getHwComposer().setVsyncEnabled(*displayId,
1500 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1501 }
Mathias Agopian86303202012-07-24 22:46:10 -07001502}
1503
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001505void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001506 if (mUseScheduler) {
1507 mScheduler->disableHardwareVsync(true);
1508 } else {
1509 disableHardwareVsync(true);
1510 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001511 // Clear the drawing state so that the logic inside of
1512 // handleTransactionLocked will fire. It will determine the delta between
1513 // mCurrentState and mDrawingState and re-apply all changes when we make the
1514 // transition.
1515 mDrawingState.displays.clear();
1516 mDisplays.clear();
1517}
1518
Steven Thomas050b2c82017-03-06 11:45:16 -08001519void SurfaceFlinger::updateVrFlinger() {
1520 if (!mVrFlinger)
1521 return;
1522 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001523 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001524 return;
1525 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001526
Lloyd Pique441d5042018-10-18 16:49:51 -07001527 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 ALOGE("Vr flinger is only supported for remote hardware composer"
1529 " service connections. Ignoring request to transition to vr"
1530 " flinger.");
1531 mVrFlingerRequestsDisplay = false;
1532 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001533 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001535 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536
Steven Thomas0123ac62018-07-12 11:32:34 -07001537 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001538 LOG_ALWAYS_FATAL_IF(!display);
1539 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001540 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1541 // called below. Clear the reference now so we don't accidentally use it
1542 // later.
1543 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 // Delete the current instance before creating the new one
1551 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1552 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1553 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1554 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001557 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001558
1559 if (vrFlingerRequestsDisplay) {
1560 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001561 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562
1563 mVisibleRegionsDirty = true;
1564 invalidateHwcGeometry();
1565
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 display = getDefaultDisplayDeviceLocked();
1568 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001569 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 const nsecs_t vsyncPeriod = getVsyncPeriod();
1573 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001575 // The present fences returned from vr_hwc are not an accurate
1576 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001577 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001578 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1579 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001580 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001581 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001582 !hasSyncFramework);
1583 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Use phase of 0 since phase is not known.
1586 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001587 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001588 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001589
Dominik Laskowski83b88212018-12-11 13:34:06 -08001590 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001591
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001592 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001593 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594}
1595
Mathias Agopian4fec8732012-06-29 14:12:52 -07001596void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001597 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001598 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001599 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001600 if (mUseScheduler) {
1601 // This call is made each time SF wakes up and creates a new frame.
1602 mScheduler->incrementFrameCounter();
1603 }
Dan Stoza50182882016-07-08 12:02:20 -07001604 bool frameMissed = !mHadClientComposition &&
1605 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 (mPreviousPresentFence->getSignalTime() ==
1607 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001608 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001609 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001610 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001611 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001612 if (mPropagateBackpressure) {
1613 signalLayerUpdate();
1614 break;
1615 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001616 }
Dan Stoza50182882016-07-08 12:02:20 -07001617
Steven Thomas050b2c82017-03-06 11:45:16 -08001618 // Now that we're going to make it to the handleMessageTransaction()
1619 // call below it's safe to call updateVrFlinger(), which will
1620 // potentially trigger a display handoff.
1621 updateVrFlinger();
1622
Dan Stoza6b9454d2014-11-07 16:00:59 -08001623 bool refreshNeeded = handleMessageTransaction();
1624 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001625 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001626 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001627 // Signal a refresh if a transaction modified the window state,
1628 // a new buffer was latched, or if HWC has requested a full
1629 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001630 signalRefresh();
1631 }
1632 break;
1633 }
1634 case MessageQueue::REFRESH: {
1635 handleMessageRefresh();
1636 break;
1637 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001638 }
1639}
1640
Dan Stoza6b9454d2014-11-07 16:00:59 -08001641bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001642 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001643
1644 // Apply any ready transactions in the queues if there are still transactions that have not been
1645 // applied, wake up during the next vsync period and check again
1646 bool transactionNeeded = false;
1647 if (!flushTransactionQueues()) {
1648 transactionNeeded = true;
1649 }
1650
Mathias Agopian4fec8732012-06-29 14:12:52 -07001651 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001652 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001654
1655 if (transactionNeeded) {
1656 setTransactionFlags(eTransactionNeeded);
1657 }
1658
1659 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001660}
1661
Mathias Agopian4fec8732012-06-29 14:12:52 -07001662void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001664
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001665 mRefreshPending = false;
1666
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001667 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001668 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001669 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001670 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671 for (const auto& [token, display] : mDisplays) {
1672 beginFrame(display);
1673 prepareFrame(display);
1674 doDebugFlashRegions(display, repaintEverything);
1675 doComposition(display, repaintEverything);
1676 }
1677
Adrian Roos1e1a1282017-11-01 19:05:31 +01001678 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001679 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680
1681 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001682 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001683
Dan Stozabfbffeb2016-07-21 14:49:33 -07001684 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001685 for (const auto& [token, displayDevice] : mDisplays) {
1686 auto display = displayDevice->getCompositionDisplay();
1687 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001688 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001689 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001690 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691
Alec Mouri86770e52018-09-24 22:40:58 +00001692 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001693 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001694 if (mHadClientComposition) {
1695 base::unique_fd flushFence(getRenderEngine().flush());
1696 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1697 getBE().flushFence = new Fence(std::move(flushFence));
1698 } else {
1699 // Cleanup for hygiene.
1700 getBE().flushFence = Fence::NO_FENCE;
1701 }
1702 }
1703
Jorim Jaggi90535212018-05-23 23:44:06 +02001704 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001705
David Sodman7e4ae112018-02-09 15:02:28 -08001706 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001708 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001709 compositionInfo.hwc.hwcLayer = nullptr;
1710 }
David Sodmanba340492018-08-05 21:51:33 -07001711 }
David Sodman7e4ae112018-02-09 15:02:28 -08001712
1713 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001714}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716
1717bool SurfaceFlinger::handleMessageInvalidate() {
1718 ATRACE_CALL();
1719 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001720}
1721
David Sodman79bba0e2018-08-05 18:07:49 -07001722void SurfaceFlinger::calculateWorkingSet() {
1723 ATRACE_CALL();
1724 ALOGV(__FUNCTION__);
1725
David Sodman79bba0e2018-08-05 18:07:49 -07001726 // build the h/w work list
1727 if (CC_UNLIKELY(mGeometryInvalid)) {
1728 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 for (const auto& [token, displayDevice] : mDisplays) {
1730 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001731 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (!displayId) {
1733 continue;
1734 }
David Sodman79bba0e2018-08-05 18:07:49 -07001735
Lloyd Pique32cbe282018-10-19 13:09:22 -07001736 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737 for (size_t i = 0; i < currentLayers.size(); i++) {
1738 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001739
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 if (!layer->hasHwcLayer(*displayId)) {
1741 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1742 layer->forceClientComposition(*displayId);
1743 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
1745 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746
Lloyd Pique32cbe282018-10-19 13:09:22 -07001747 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748 if (mDebugDisableHWC || mDebugRegion) {
1749 layer->forceClientComposition(*displayId);
1750 }
David Sodman79bba0e2018-08-05 18:07:49 -07001751 }
1752 }
1753 }
1754
1755 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001756 for (const auto& [token, displayDevice] : mDisplays) {
1757 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001758 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001759 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001760 continue;
1761 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001762 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001763
1764 if (mDrawingState.colorMatrixChanged) {
1765 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001767 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001768 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1771 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001772 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001774 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1775 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001776 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001778 }
1779
Peiyong Lind3788632018-09-18 16:01:31 -07001780 // TODO(b/111562338) remove when composer 2.3 is shipped.
1781 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001783 }
1784
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001785 if (layer->getRoundedCornerState().radius > 0.0f) {
1786 layer->forceClientComposition(*displayId);
1787 }
1788
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001790 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001792 continue;
1793 }
1794
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 const auto& displayState = display->getState();
1796 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1797 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001798 }
1799
Peiyong Lin13effd12018-07-24 17:01:47 -07001800 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001801 ColorMode colorMode;
1802 Dataspace dataSpace;
1803 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 }
1807 }
1808
1809 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001810
1811 for (const auto& [token, display] : mDisplays) {
1812 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001813 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001814 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815
1816 if (displayId) {
1817 if (!layer->setHwcLayer(*displayId)) {
1818 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1819 }
1820 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001821 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001822
Dominik Laskowski05275f12018-11-01 15:03:24 -07001823 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001824 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1825 }
1826 }
David Sodman79bba0e2018-08-05 18:07:49 -07001827}
1828
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1830 bool repaintEverything) {
1831 auto display = displayDevice->getCompositionDisplay();
1832 const auto& displayState = display->getState();
1833
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834 // is debugging enabled
1835 if (CC_LIKELY(!mDebugRegion))
1836 return;
1837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001839 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001840 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 if (!dirtyRegion.isEmpty()) {
1842 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844
David Sodmanfa9b2af2017-12-24 13:28:59 -08001845 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001846 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001847 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001848
Lloyd Pique31cb2942018-10-19 17:23:03 -07001849 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850 }
1851 }
1852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854
1855 if (mDebugRegion > 1) {
1856 usleep(mDebugRegion * 1000);
1857 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860}
1861
Adrian Roos1e1a1282017-11-01 19:05:31 +01001862void SurfaceFlinger::doTracing(const char* where) {
1863 ATRACE_CALL();
1864 ATRACE_NAME(where);
1865 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001866 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001867 }
1868}
1869
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001870void SurfaceFlinger::logLayerStats() {
1871 ATRACE_CALL();
1872 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001873 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 if (display->isPrimary()) {
1875 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001876 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001877 }
1878 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001879
1880 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001881 }
1882}
1883
David Sodman2b406362017-12-15 13:33:47 -08001884void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ATRACE_CALL();
1887 ALOGV("preComposition");
1888
David Sodman2b406362017-12-15 13:33:47 -08001889 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001892 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001893 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894 needExtraInvalidate = true;
1895 }
Robert Carr2047fae2016-11-28 14:09:09 -08001896 });
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 if (needExtraInvalidate) {
1899 signalLayerUpdate();
1900 }
1901}
1902
Ana Krulece588e312018-09-18 12:32:24 -07001903void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1904 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 // Update queue of past composite+present times and determine the
1906 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001907 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001909 while (!getBE().mCompositePresentTimes.empty()) {
1910 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Cached values should have been updated before calling this method,
1912 // which helps avoid duplicate syscalls.
1913 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1914 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1915 break;
1916 }
1917 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001918 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 }
1920
1921 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001922 while (getBE().mCompositePresentTimes.size() > 16) {
1923 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 }
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001927}
1928
Ana Krulece588e312018-09-18 12:32:24 -07001929void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1930 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 // Integer division and modulo round toward 0 not -inf, so we need to
1932 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001933 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1934 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1935 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936
Brian Andersond0010582017-03-07 13:20:31 -08001937 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1938 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001939 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001940 }
1941
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Snap the latency to a value that removes scheduling jitter from the
1943 // composition and present times, which often have >1ms of jitter.
1944 // Reducing jitter is important if an app attempts to extrapolate
1945 // something (such as user input) to an accurate diasplay time.
1946 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1947 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001948 nsecs_t bias = stats.vsyncPeriod / 2;
1949 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1950 nsecs_t snappedCompositeToPresentLatency =
1951 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952
David Sodman99974d22017-11-28 12:04:33 -08001953 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001954 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1955 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001956 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957}
1958
Ady Abraham8164d482019-01-11 14:47:59 -08001959// debug patch for b/119477596 - add stack guards to catch stack
1960// corruptions and disable clang optimizations.
1961// The code below is temporary and planned to be removed once stack
1962// corruptions are found.
1963#pragma clang optimize off
1964class StackGuard {
1965public:
1966 StackGuard(const char* name, const char* func, int line) {
1967 guarders.reserve(MIN_CAPACITY);
1968 guarders.push_back({this, name, func, line});
1969 validate();
1970 }
1971 ~StackGuard() {
1972 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1973 if (i->guard == this) {
1974 guarders.erase(i);
1975 break;
1976 }
1977 }
1978 }
1979
1980 static void validate() {
1981 for (const auto& guard : guarders) {
1982 if (guard.guard->cookie != COOKIE_VALUE) {
1983 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1984 CallStack stack(LOG_TAG);
1985 abort();
1986 }
1987 }
1988 }
1989
1990private:
1991 uint64_t cookie = COOKIE_VALUE;
1992 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1993 static constexpr size_t MIN_CAPACITY = 16;
1994
1995 struct GuarderElement {
1996 StackGuard* guard;
1997 const char* name;
1998 const char* func;
1999 int line;
2000 };
2001
2002 static std::vector<GuarderElement> guarders;
2003};
2004std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2005
2006#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2007
2008#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002009void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010{
Ady Abraham8164d482019-01-11 14:47:59 -08002011 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ATRACE_CALL();
2013 ALOGV("postComposition");
2014
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002016 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002017 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002018 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002019 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002020 }
Ady Abraham8164d482019-01-11 14:47:59 -08002021 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002023 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 const auto displayDevice = getDefaultDisplayDeviceLocked();
2025 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002029 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2030
Lloyd Pique32cbe282018-10-19 13:09:22 -07002031 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002033 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2034 ->getRenderSurface()
2035 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037 } else {
2038 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2039 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040
Ady Abraham8164d482019-01-11 14:47:59 -08002041 ASSERT_ON_STACK_GUARD();
2042
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2045 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002046 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002048 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049
Ana Krulece588e312018-09-18 12:32:24 -07002050 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002051 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002052 if (mUseScheduler) {
2053 mScheduler->getDisplayStatInfo(&stats);
2054 } else {
2055 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2056 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2057 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002058
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
2060
David Sodman2b406362017-12-15 13:33:47 -08002061 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 // when we started doing work for this frame, but that should be okay
2063 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002064 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002065 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002066 DEFINE_STACK_GUARD(compositorTiming);
2067
Brian Andersond0010582017-03-07 13:20:31 -08002068 {
David Sodman99974d22017-11-28 12:04:33 -08002069 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002070 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002071 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002072
2073 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002074 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
Robert Carr2047fae2016-11-28 14:09:09 -08002076 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002077 bool frameLatched =
2078 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2079 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002080 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002081 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002082 recordBufferingStats(layer->getName().string(),
2083 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002084 }
Ady Abraham8164d482019-01-11 14:47:59 -08002085 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002086 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002087
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002088 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002090 if (mUseScheduler) {
2091 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002093 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002094 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2095 enableHardwareVsync();
2096 } else {
2097 disableHardwareVsync(false);
2098 }
Ady Abraham8164d482019-01-11 14:47:59 -08002099 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002100 }
2101 }
2102
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002103 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2105 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002106 if (mUseScheduler) {
2107 mScheduler->enableHardwareVsync();
2108 } else {
2109 enableHardwareVsync();
2110 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002111 }
2112 }
2113
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
2115
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 if (mAnimCompositionPending) {
2117 mAnimCompositionPending = false;
2118
Brian Anderson4e606e32017-03-16 15:34:57 -07002119 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002121 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002122
2123 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002124 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002125 // The HWC doesn't support present fences, so use the refresh
2126 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002127 const nsecs_t presentTime =
2128 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002129 DEFINE_STACK_GUARD(presentTime);
2130
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002131 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002133 }
2134 mAnimFrameTracker.advanceFrame();
2135 }
Dan Stozab90cf072015-03-05 11:05:59 -08002136
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
2138
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002139 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002140 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002141 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002142 }
2143
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
2145
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002146 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002147
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
2149
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2151 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002152 return;
2153 }
2154
2155 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002157 if (mHasPoweredOff) {
2158 mHasPoweredOff = false;
2159 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002160 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002161 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002162 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002163 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002164 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2165 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002166 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002167 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002168 }
David Sodman4a36e932017-11-07 14:29:47 -08002169 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002170
2171 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002172 }
David Sodman4a36e932017-11-07 14:29:47 -08002173 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002174 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002175
2176 {
2177 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002179 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002180 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002181 if (refillCount > 0) {
2182 const size_t offset = mTexturePool.size();
2183 mTexturePool.resize(mTexturePoolSize);
2184 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2185 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2186 }
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002188 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002189
Marissa Wallfda30bb2018-10-12 11:34:28 -07002190 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002191 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002192
2193 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194}
Ady Abraham8164d482019-01-11 14:47:59 -08002195#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196
2197void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 ATRACE_CALL();
2199 ALOGV("rebuildLayerStacks");
2200
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002201 // We need to clear these out now as these may be holding on to a
2202 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2203 // also holds a reference. When the set of visible layers is recomputed,
2204 // some layers may be destroyed if the only thing keeping them alive was
2205 // that list of visible layers associated with each display. The layer
2206 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2207 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2208 for (const auto& [token, display] : mDisplays) {
2209 getBE().mCompositionInfo[token].clear();
2210 }
2211
Mathias Agopiancd60f992012-08-16 16:28:27 -07002212 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002214 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 mVisibleRegionsDirty = false;
2216 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002217
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002218 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002219 const auto& displayDevice = pair.second;
2220 auto display = displayDevice->getCompositionDisplay();
2221 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002222 Region opaqueRegion;
2223 Region dirtyRegion;
2224 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002225 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002226 const ui::Transform& tr = displayState.transform;
2227 const Rect bounds = displayState.bounds;
2228 if (displayState.isEnabled) {
2229 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002230
Jeff Sharkey76488112017-02-27 14:15:18 -07002231 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002232 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002233 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002234 if (display->belongsInOutput(layer->getLayerStack(),
2235 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002236 Region drawRegion(tr.transform(
2237 layer->visibleNonTransparentRegion));
2238 drawRegion.andSelf(bounds);
2239 if (!drawRegion.isEmpty()) {
2240 layersSortedByZ.add(layer);
2241 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002242 // Clear out the HWC layer if this layer was
2243 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002244 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002246 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002247 // WM changes display->layerStack upon sleep/awake.
2248 // Here we make sure we delete the HWC layers even if
2249 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002250 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002251 }
2252
2253 // If a layer is not going to get a release fence because
2254 // it is invisible, but it is also going to release its
2255 // old buffer, add it to the list of layers needing
2256 // fences.
2257 if (hwcLayerDestroyed) {
2258 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2259 mLayersWithQueuedFrames.cend(), layer);
2260 if (found != mLayersWithQueuedFrames.cend()) {
2261 layersNeedingFences.add(layer);
2262 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002263 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002264 });
2265 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002266 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2267 displayDevice->setLayersNeedingFences(layersNeedingFences);
2268
2269 Region undefinedRegion{bounds};
2270 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2271
2272 display->editState().undefinedRegion = undefinedRegion;
2273 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002274 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002275 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002276}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002277
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002279// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002280// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002281// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002282// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283// The returned HDR data space is one of
2284// - Dataspace::UNKNOWN
2285// - Dataspace::BT2020_HLG
2286// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2288 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002289 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 *outHdrDataSpace = Dataspace::UNKNOWN;
2291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002293 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294 case Dataspace::V0_SCRGB:
2295 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002296 case Dataspace::BT2020:
2297 case Dataspace::BT2020_ITU:
2298 case Dataspace::BT2020_LINEAR:
2299 case Dataspace::DISPLAY_BT2020:
2300 bestDataSpace = Dataspace::DISPLAY_BT2020;
2301 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002303 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305 case Dataspace::BT2020_PQ:
2306 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002309 case Dataspace::BT2020_HLG:
2310 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 // When there's mixed PQ content and HLG content, we set the HDR
2312 // data space to be BT2020_PQ and convert HLG to PQ.
2313 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2314 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002315 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 break;
2317 default:
2318 break;
2319 }
Romain Guy54f154a2017-10-24 21:40:32 +01002320 }
2321
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002323}
2324
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2327 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2329 *outMode = ColorMode::NATIVE;
2330 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002333 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002334
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002338 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2339
Peiyong Lindfde5112018-06-05 10:58:41 -07002340 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002341 const bool isHdr =
2342 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002343 if (isHdr) {
2344 bestDataSpace = hdrDataSpace;
2345 }
2346
Chia-I Wu0d711262018-05-21 15:19:35 -07002347 RenderIntent intent;
2348 switch (mDisplayColorSetting) {
2349 case DisplayColorSetting::MANAGED:
2350 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002351 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002352 break;
2353 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002354 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002355 break;
2356 default: // vendor display color setting
2357 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2358 break;
2359 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002360
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002361 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002362}
2363
Lloyd Pique32cbe282018-10-19 13:09:22 -07002364void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2365 auto display = displayDevice->getCompositionDisplay();
2366 const auto& displayState = display->getState();
2367
2368 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2369 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2370 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002371
David Sodmanfa9b2af2017-12-24 13:28:59 -08002372 // If nothing has changed (!dirty), don't recompose.
2373 // If something changed, but we don't currently have any visible layers,
2374 // and didn't when we last did a composition, then skip it this time.
2375 // The second rule does two things:
2376 // - When all layers are removed from a display, we'll emit one black
2377 // frame, then nothing more until we get new layers.
2378 // - When a display is created with a private layer stack, we won't
2379 // emit any black frames until a layer is added to the layer stack.
2380 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002381
Dominik Laskowski075d3172018-05-24 15:50:06 -07002382 const char flagPrefix[] = {'-', '+'};
2383 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002384 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2385 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2386 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2387 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002388
Lloyd Pique31cb2942018-10-19 17:23:03 -07002389 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002390
David Sodmanfa9b2af2017-12-24 13:28:59 -08002391 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002393 }
2394}
2395
Lloyd Pique32cbe282018-10-19 13:09:22 -07002396void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2397 auto display = displayDevice->getCompositionDisplay();
2398 const auto& displayState = display->getState();
2399
2400 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002401 return;
David Sodman2b406362017-12-15 13:33:47 -08002402 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002403
Lloyd Pique31cb2942018-10-19 17:23:03 -07002404 status_t result = display->getRenderSurface()->prepareFrame(
2405 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002408}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002409
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002411 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 ALOGV("doComposition");
2413
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 auto display = displayDevice->getCompositionDisplay();
2415 const auto& displayState = display->getState();
2416
2417 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002420
David Sodmanfa9b2af2017-12-24 13:28:59 -08002421 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002423
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002425 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428}
2429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430void SurfaceFlinger::postFrame()
2431{
2432 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 const auto display = getDefaultDisplayDeviceLocked();
2434 if (display && getHwComposer().isConnected(*display->getId())) {
2435 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002436 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2437 logFrameStats();
2438 }
2439 }
2440}
2441
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002443 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 auto display = displayDevice->getCompositionDisplay();
2447 const auto& displayState = display->getState();
2448 const auto displayId = display->getId();
2449
David Sodmanfa9b2af2017-12-24 13:28:59 -08002450 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002451
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 if (displayId) {
2454 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002455 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002456 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002458 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002459
Chia-I Wu7b549592017-11-15 09:14:57 -08002460 // The layer buffer from the previous frame (if any) is released
2461 // by HWC only when the release fence from this frame (if any) is
2462 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 if (displayId && layer->hasHwcLayer(*displayId)) {
2464 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2465 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002466 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002467
2468 // If the layer was client composited in the previous frame, we
2469 // need to merge with the previous client target acquire fence.
2470 // Since we do not track that, always merge with the current
2471 // client target acquire fence when it is available, even though
2472 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002473 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002474 releaseFence =
2475 Fence::merge("LayerRelease", releaseFence,
2476 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002477 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002478
David Sodman15094112018-10-11 09:39:37 -07002479 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 }
Chia-I Wu83806892017-11-16 10:50:20 -08002481
2482 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002484 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002485 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002487 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002489 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002490 }
2491 }
2492
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 if (displayId) {
2494 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002495 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002496 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497}
2498
Mathias Agopian87baae12012-07-31 12:38:26 -07002499void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500{
Mathias Agopian841cde52012-03-01 15:44:37 -08002501 ATRACE_CALL();
2502
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002503 // here we keep a copy of the drawing state (that is the state that's
2504 // going to be overwritten by handleTransactionLocked()) outside of
2505 // mStateLock so that the side-effects of the State assignment
2506 // don't happen with mStateLock held (which can cause deadlocks).
2507 State drawingState(mDrawingState);
2508
Mathias Agopianca4d3602011-05-19 15:38:14 -07002509 Mutex::Autolock _l(mStateLock);
2510 const nsecs_t now = systemTime();
2511 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Mathias Agopianca4d3602011-05-19 15:38:14 -07002513 // Here we're guaranteed that some transaction flags are set
2514 // so we can call handleTransactionLocked() unconditionally.
2515 // We call getTransactionFlags(), which will also clear the flags,
2516 // with mStateLock held to guarantee that mCurrentState won't change
2517 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002518
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002519 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002520 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002521 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002522
Mathias Agopianca4d3602011-05-19 15:38:14 -07002523 mLastTransactionTime = systemTime() - now;
2524 mDebugInTransaction = 0;
2525 invalidateHwcGeometry();
2526 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002527}
2528
Lloyd Piqueba04e622017-12-14 17:11:26 -08002529void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2530 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 const std::optional<DisplayIdentificationInfo> info =
2532 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002535 continue;
2536 }
2537
Lloyd Piqueba04e622017-12-14 17:11:26 -08002538 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002540 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 mPhysicalDisplayTokens[info->id] = new BBinder();
2542 DisplayDeviceState state;
2543 state.displayId = info->id;
2544 state.isSecure = true; // All physical displays are currently considered secure.
2545 state.displayName = info->name;
2546 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2547 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002548 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002549 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002550 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2553 if (index >= 0) {
2554 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2555 mInterceptor->saveDisplayDeletion(state.sequenceId);
2556 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002557 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002559 }
2560
2561 processDisplayChangesLocked();
2562 }
2563
2564 mPendingHotplugEvents.clear();
2565}
2566
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002567void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2568 bool connected) {
2569 if (mUseScheduler) {
2570 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2571 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2572 } else {
2573 mEventThread->onHotplugReceived(displayType, connected);
2574 mSFEventThread->onHotplugReceived(displayType, connected);
2575 }
2576}
2577
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002580 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 const sp<IGraphicBufferProducer>& producer) {
2582 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002583 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 creationArgs.isSecure = state.isSecure;
2586 creationArgs.displaySurface = dispSurface;
2587 creationArgs.hasWideColorGamut = false;
2588 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002589
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2591 creationArgs.isPrimary = isInternalDisplay;
2592
2593 if (useColorManagement && displayId) {
2594 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002596 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002599
Dominik Laskowski7e045462018-05-30 13:02:02 -07002600 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002602 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 }
tangrobin6753a022018-08-10 10:58:54 +08002604 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 if (displayId) {
2607 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002608 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002610 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Lloyd Pique90c115d2018-09-18 21:39:42 -07002612 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 // Make sure that composition can never be stalled by a virtual display
2617 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002618 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002619 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2621 }
2622
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 creationArgs.displayInstallOrientation =
2624 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002625
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002627 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
Lloyd Pique90c115d2018-09-18 21:39:42 -07002629 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630
2631 if (maxFrameBufferAcquiredBuffers >= 3) {
2632 nativeWindowSurface->preallocateBuffers();
2633 }
2634
2635 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002636 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002637 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002639 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002641 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2642 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 if (!state.isVirtual()) {
2644 LOG_ALWAYS_FATAL_IF(!displayId);
2645 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002646 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 display->setLayerStack(state.layerStack);
2649 display->setProjection(state.orientation, state.viewport, state.frame);
2650 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653}
2654
Lloyd Pique347200f2017-12-14 17:00:15 -08002655void SurfaceFlinger::processDisplayChangesLocked() {
2656 // here we take advantage of Vector's copy-on-write semantics to
2657 // improve performance by skipping the transaction entirely when
2658 // know that the lists are identical
2659 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2660 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2661 if (!curr.isIdenticalTo(draw)) {
2662 mVisibleRegionsDirty = true;
2663 const size_t cc = curr.size();
2664 size_t dc = draw.size();
2665
2666 // find the displays that were removed
2667 // (ie: in drawing state but not in current state)
2668 // also handle displays that changed
2669 // (ie: displays that are in both lists)
2670 for (size_t i = 0; i < dc;) {
2671 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2672 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002673 // Save display IDs before disconnecting.
2674 const auto internalDisplayId = getInternalDisplayId();
2675 const auto externalDisplayId = getExternalDisplayId();
2676
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002679 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002682 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002684 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002685 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 } else {
2688 // this display is in both lists. see if something changed.
2689 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2692 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2693 if (state_binder != draw_binder) {
2694 // changing the surface is like destroying and
2695 // recreating the DisplayDevice, so we just remove it
2696 // from the drawing state, so that it get re-added
2697 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002699 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 mDrawingState.displays.removeItemsAt(i);
2703 dc--;
2704 // at this point we must loop to the next item
2705 continue;
2706 }
2707
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712 if ((state.orientation != draw[i].orientation) ||
2713 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002717 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 }
2719 }
2720 }
2721 ++i;
2722 }
2723
2724 // find displays that were added
2725 // (ie: in current state but not in drawing state)
2726 for (size_t i = 0; i < cc; i++) {
2727 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2728 const DisplayDeviceState& state(curr[i]);
2729
Lloyd Pique542307f2018-10-19 13:24:08 -07002730 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 sp<IGraphicBufferProducer> producer;
2732 sp<IGraphicBufferProducer> bqProducer;
2733 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002734 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002737 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 // Virtual displays without a surface are dormant:
2739 // they have external state (layer stack, projection,
2740 // etc.) but no internal state (i.e. a DisplayDevice).
2741 if (state.surface != nullptr) {
2742 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002743 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 int width = 0;
2745 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2747 int height = 0;
2748 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2749 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2750 int intFormat = 0;
2751 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2752 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002753 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 displayId =
2756 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 }
2758
2759 // TODO: Plumb requested format back up to consumer
2760
2761 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002762 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 bqProducer, bqConsumer,
2764 state.displayName);
2765
2766 dispSurface = vds;
2767 producer = vds;
2768 }
2769 } else {
2770 ALOGE_IF(state.surface != nullptr,
2771 "adding a supported display, but rendering "
2772 "surface is provided (%p), ignoring it",
2773 state.surface.get());
2774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 displayId = state.displayId;
2776 LOG_ALWAYS_FATAL_IF(!displayId);
2777 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 producer = bqProducer;
2779 }
2780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002782 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002784 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002786 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002787 LOG_ALWAYS_FATAL_IF(!displayId);
2788
2789 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002790 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002792 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002793 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 }
2795 }
2796 }
2797 }
2798 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002799
2800 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002801}
2802
Mathias Agopian87baae12012-07-31 12:38:26 -07002803void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002804{
Dan Stoza7dde5992015-05-22 09:51:44 -07002805 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mCurrentState.traverseInZOrder([](Layer* layer) {
2807 layer->notifyAvailableFrames();
2808 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002809
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 /*
2811 * Traversal of the children
2812 * (perform the transaction for each of them if needed)
2813 */
2814
Robert Carr720e5062018-07-30 17:45:14 -07002815 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002817 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002819 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820
2821 const uint32_t flags = layer->doTransaction(0);
2822 if (flags & Layer::eVisibleRegion)
2823 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002824
2825 if (flags & Layer::eInputInfoChanged) {
2826 inputChanged = true;
2827 }
Robert Carr2047fae2016-11-28 14:09:09 -08002828 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 }
2830
2831 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002832 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 */
2834
Mathias Agopiane57f2922012-08-09 16:29:12 -07002835 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002836 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002837 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002838 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002840 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002841 // The transform hint might have changed for some layers
2842 // (either because a display has changed, or because a layer
2843 // as changed).
2844 //
2845 // Walk through all the layers in currentLayers,
2846 // and update their transform hint.
2847 //
2848 // If a layer is visible only on a single display, then that
2849 // display is used to calculate the hint, otherwise we use the
2850 // default display.
2851 //
2852 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2853 // the hint is set before we acquire a buffer from the surface texture.
2854 //
2855 // NOTE: layer transactions have taken place already, so we use their
2856 // drawing state. However, SurfaceFlinger's own transaction has not
2857 // happened yet, so we must use the current state layer list
2858 // (soon to become the drawing state list).
2859 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002860 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002861 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002862 bool first = true;
2863 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002864 // NOTE: we rely on the fact that layers are sorted by
2865 // layerStack first (so we don't have to traverse the list
2866 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002868 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002869 currentlayerStack = layerStack;
2870 // figure out if this layerstack is mirrored
2871 // (more than one display) if so, pick the default display,
2872 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002873 hintDisplay = nullptr;
2874 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002875 if (display->getCompositionDisplay()
2876 ->belongsInOutput(layer->getLayerStack(),
2877 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002878 if (hintDisplay) {
2879 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002880 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002882 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002883 }
2884 }
2885 }
2886 }
Chet Haase91d25932013-04-11 15:24:55 -07002887
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002889 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2890 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002891
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002892 // could be null when this layer is using a layerStack
2893 // that is not visible on any display. Also can occur at
2894 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002895 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002896 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002899 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002900 if (hintDisplay) {
2901 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002902 }
Robert Carr2047fae2016-11-28 14:09:09 -08002903
2904 first = false;
2905 });
Mathias Agopian84300952012-11-21 16:02:13 -08002906 }
2907
2908
Mathias Agopian3559b072012-08-15 13:46:03 -07002909 /*
2910 * Perform our own transaction if needed
2911 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912
2913 if (mLayersAdded) {
2914 mLayersAdded = false;
2915 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002916 mVisibleRegionsDirty = true;
2917 }
2918
2919 // some layers might have been removed, so
2920 // we need to update the regions they're exposing.
2921 if (mLayersRemoved) {
2922 mLayersRemoved = false;
2923 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002924 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002926 // this layer is not visible anymore
2927 // TODO: we could traverse the tree from front to back and
2928 // compute the actual visible region
2929 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 Region visibleReg;
2931 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002932 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002933 }
Robert Carr2047fae2016-11-28 14:09:09 -08002934 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 }
2936
2937 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002938
Vishnu Nairde19f852018-12-18 16:11:53 -08002939 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002940 updateInputWindows();
2941 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002942 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002943
Riley Andrews03414a12014-07-01 14:22:59 -07002944 updateCursorAsync();
2945}
2946
Robert Carr720e5062018-07-30 17:45:14 -07002947void SurfaceFlinger::updateInputWindows() {
2948 ATRACE_CALL();
2949
Vishnu Nairde19f852018-12-18 16:11:53 -08002950 if (mInputFlinger == nullptr) {
2951 return;
2952 }
2953
Robert Carr720e5062018-07-30 17:45:14 -07002954 Vector<InputWindowInfo> inputHandles;
2955
2956 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2957 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002958 // When calculating the screen bounds we ignore the transparent region since it may
2959 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002960 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002961 }
2962 });
2963 mInputFlinger->setInputWindows(inputHandles);
2964}
2965
chaviwfbe5d9c2018-12-26 12:23:37 -08002966void SurfaceFlinger::executeInputWindowCommands() {
2967 if (!mInputFlinger) {
2968 return;
2969 }
2970
2971 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2972 if (transferTouchFocusCommand.fromToken != nullptr &&
2973 transferTouchFocusCommand.toToken != nullptr &&
2974 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2975 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2976 transferTouchFocusCommand.toToken);
2977 }
2978 }
2979
2980 mInputWindowCommands.clear();
2981}
2982
Riley Andrews03414a12014-07-01 14:22:59 -07002983void SurfaceFlinger::updateCursorAsync()
2984{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002985 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002986 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002987 continue;
2988 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2991 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002992 }
2993 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994}
2995
chaviw61626f22018-11-15 16:26:27 -08002996void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2997 if (layer->hasReadyFrame()) {
2998 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2999 if (layer->shouldPresentNow(expectedPresentTime)) {
3000 bool ignored = false;
3001 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3002 }
3003 }
3004 layer->releasePendingBuffer(systemTime());
3005}
3006
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007void SurfaceFlinger::commitTransaction()
3008{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003009 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003010 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 for (const auto& l : mLayersPendingRemoval) {
3012 recordBufferingStats(l->getName().string(),
3013 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003014
3015 // We need to release the HWC layers when the Layer is removed
3016 // from the current state otherwise the HWC layer just continues
3017 // showing at its last configured state until we eventually
3018 // abandon the buffer queue.
3019 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003020 l->destroyHwcLayersForAllDisplays();
3021 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003022 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003023 }
3024 mLayersPendingRemoval.clear();
3025 }
3026
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003027 // If this transaction is part of a window animation then the next frame
3028 // we composite should be considered an animation as well.
3029 mAnimCompositionPending = mAnimTransactionPending;
3030
Mathias Agopian4fec8732012-06-29 14:12:52 -07003031 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003032 // clear the "changed" flags in current state
3033 mCurrentState.colorMatrixChanged = false;
3034
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 mDrawingState.traverseInZOrder([](Layer* layer) {
3036 layer->commitChildList();
3037 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003038 mTransactionPending = false;
3039 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003040 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041}
3042
Lloyd Pique32cbe282018-10-19 13:09:22 -07003043void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003045 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003046 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003047
Lloyd Pique32cbe282018-10-19 13:09:22 -07003048 auto display = displayDevice->getCompositionDisplay();
3049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 Region aboveOpaqueLayers;
3051 Region aboveCoveredLayers;
3052 Region dirty;
3053
Mathias Agopian87baae12012-07-31 12:38:26 -07003054 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055
Robert Carr2047fae2016-11-28 14:09:09 -08003056 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003057 // start with the whole surface at its current location
3058 const Layer::State& s(layer->getDrawingState());
3059
Jesse Hall01e29052013-02-19 16:13:35 -08003060 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003061 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003062 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003063 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003064
Mathias Agopianab028732010-03-16 16:41:46 -07003065 /*
3066 * opaqueRegion: area of a surface that is fully opaque.
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 /*
3071 * visibleRegion: area of a surface that is visible on screen
3072 * and not fully transparent. This is essentially the layer's
3073 * footprint minus the opaque regions above it.
3074 * Areas covered by a translucent surface are considered visible.
3075 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003077
3078 /*
3079 * coveredRegion: area of a surface that is covered by all
3080 * visible regions above it (which includes the translucent areas).
3081 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003083
Jesse Halla8026d22012-09-25 13:25:04 -07003084 /*
3085 * transparentRegion: area of a surface that is hinted to be completely
3086 * transparent. This is only used to tell when the layer has no visible
3087 * non-transparent regions and can be removed from the layer list. It
3088 * does not affect the visibleRegion of this layer or any layers
3089 * beneath it. The hint may not be correct if apps don't respect the
3090 * SurfaceView restrictions (which, sadly, some don't).
3091 */
3092 Region transparentRegion;
3093
Mathias Agopianab028732010-03-16 16:41:46 -07003094
3095 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003096 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003097 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003101 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003102 if (!visibleRegion.isEmpty()) {
3103 // Remove the transparent area from the visible region
3104 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003105 if (tr.preserveRects()) {
3106 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003107 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003108 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003109 // transformation too complex, can't do the
3110 // transparent region optimization.
3111 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003112 }
Mathias Agopianab028732010-03-16 16:41:46 -07003113 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114
Mathias Agopianab028732010-03-16 16:41:46 -07003115 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003117 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003118 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003119 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003120 // the opaque region is the layer's footprint
3121 opaqueRegion = visibleRegion;
3122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 }
3124 }
3125
Robert Carre5f4f692018-01-12 13:12:28 -08003126 if (visibleRegion.isEmpty()) {
3127 layer->clearVisibilityRegions();
3128 return;
3129 }
3130
Mathias Agopianab028732010-03-16 16:41:46 -07003131 // Clip the covered region to the visible region
3132 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3133
3134 // Update aboveCoveredLayers for next (lower) layer
3135 aboveCoveredLayers.orSelf(visibleRegion);
3136
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137 // subtract the opaque region covered by the layers above us
3138 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139
3140 // compute this layer's dirty region
3141 if (layer->contentDirty) {
3142 // we need to invalidate the whole region
3143 dirty = visibleRegion;
3144 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003145 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 layer->contentDirty = false;
3147 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003148 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003149 * the exposed region consists of two components:
3150 * 1) what's VISIBLE now and was COVERED before
3151 * 2) what's EXPOSED now less what was EXPOSED before
3152 *
3153 * note that (1) is conservative, we start with the whole
3154 * visible region but only keep what used to be covered by
3155 * something -- which mean it may have been exposed.
3156 *
3157 * (2) handles areas that were not covered by anything but got
3158 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003159 */
Mathias Agopianab028732010-03-16 16:41:46 -07003160 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003161 const Region oldVisibleRegion = layer->visibleRegion;
3162 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003163 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3164 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 }
3166 dirty.subtractSelf(aboveOpaqueLayers);
3167
3168 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003169 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
Mathias Agopianab028732010-03-16 16:41:46 -07003171 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003173
Jesse Halla8026d22012-09-25 13:25:04 -07003174 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 layer->setVisibleRegion(visibleRegion);
3176 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003177 layer->setVisibleNonTransparentRegion(
3178 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003179 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
Mathias Agopian87baae12012-07-31 12:38:26 -07003181 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182}
3183
Chia-I Wuab0c3192017-08-01 11:29:00 -07003184void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003185 for (const auto& [token, displayDevice] : mDisplays) {
3186 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003187 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003188 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003189 }
3190 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003191}
3192
Dan Stoza6b9454d2014-11-07 16:00:59 -08003193bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003195 ALOGV("handlePageFlip");
3196
Brian Andersond6927fb2016-07-23 23:37:30 -07003197 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198
Mathias Agopian4fec8732012-06-29 14:12:52 -07003199 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003200 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003201 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003202
3203 // Store the set of layers that need updates. This set must not change as
3204 // buffers are being latched, as this could result in a deadlock.
3205 // Example: Two producers share the same command stream and:
3206 // 1.) Layer 0 is latched
3207 // 2.) Layer 0 gets a new frame
3208 // 2.) Layer 1 gets a new frame
3209 // 3.) Layer 1 is latched.
3210 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3211 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003212 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003213 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003214 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003215 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3216 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003217 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003218 } else {
3219 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003220 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003221 } else {
3222 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003223 }
Robert Carr2047fae2016-11-28 14:09:09 -08003224 });
3225
Lloyd Piquef2c79392018-12-20 16:23:33 -08003226 if (!mLayersWithQueuedFrames.empty()) {
3227 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3228 // writes to Layer current state. See also b/119481871
3229 Mutex::Autolock lock(mStateLock);
3230
3231 for (auto& layer : mLayersWithQueuedFrames) {
3232 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3233 layer->useSurfaceDamage();
3234 invalidateLayerStack(layer, dirty);
3235 if (layer->isBufferLatched()) {
3236 newDataLatched = true;
3237 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003238 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003239 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003240
Alec Mouri86770e52018-09-24 22:40:58 +00003241 // Clear the renderengine fence here...
3242 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3243 // clear instead of sp::clear.
3244 getBE().flushFence = Fence::NO_FENCE;
3245
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003246 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247
Vishnu Nairde19f852018-12-18 16:11:53 -08003248 if (visibleRegions) {
3249 // Update input window info if the layer receives its first buffer.
3250 updateInputWindows();
3251 }
3252
Dan Stoza6b9454d2014-11-07 16:00:59 -08003253 // If we will need to wake up at some time in the future to deal with a
3254 // queued frame that shouldn't be displayed during this vsync period, wake
3255 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003256 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257 signalLayerUpdate();
3258 }
3259
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003260 // enter boot animation on first buffer latch
3261 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3262 ALOGI("Enter boot animation");
3263 mBootStage = BootStage::BOOTANIMATION;
3264 }
3265
Dan Stoza6b9454d2014-11-07 16:00:59 -08003266 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003267 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268}
3269
Mathias Agopianad456f92011-01-13 17:53:01 -08003270void SurfaceFlinger::invalidateHwcGeometry()
3271{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003272 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003273}
3274
Lloyd Pique32cbe282018-10-19 13:09:22 -07003275void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003276 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003277 auto display = displayDevice->getCompositionDisplay();
3278
Dan Stoza71433162014-02-04 16:22:36 -08003279 // We only need to actually compose the display if:
3280 // 1) It is being handled by hardware composer, which may need this to
3281 // keep its virtual display state machine in sync, or
3282 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003283 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003284 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003285 return;
3286 }
3287
Dan Stoza9e56aa02015-11-02 13:00:03 -08003288 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003290
3291 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003292 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293}
3294
Lloyd Pique32cbe282018-10-19 13:09:22 -07003295bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003296 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003297
Lloyd Pique32cbe282018-10-19 13:09:22 -07003298 auto display = displayDevice->getCompositionDisplay();
3299 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003300 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003301
3302 const Region bounds(displayState.bounds);
3303 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003304 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003305 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003306
Peiyong Lind3788632018-09-18 16:01:31 -07003307 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003308 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003309
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310 // Framebuffer will live in this scope for GPU composition.
3311 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3312
Dan Stoza9e56aa02015-11-02 13:00:03 -08003313 if (hasClientComposition) {
3314 ALOGV("hasClientComposition");
3315
Lloyd Pique31cb2942018-10-19 17:23:03 -07003316 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003317
3318 if (buf == nullptr) {
3319 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3320 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003322 return false;
3323 }
3324
3325 // Bind the framebuffer in this scope.
3326 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3327 buf->getNativeBuffer());
3328
3329 if (fbo->getStatus() != NO_ERROR) {
3330 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003332 return false;
3333 }
3334
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003335 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003336 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003337 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003338 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003339 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003340 getRenderEngine().setOutputDataSpace(outputDataspace);
3341 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003342 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003343
Lloyd Pique441d5042018-10-18 16:49:51 -07003344 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003345 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003346 getHwComposer()
3347 .hasDisplayCapability(displayId,
3348 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003349
Peiyong Lind3788632018-09-18 16:01:31 -07003350 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003351 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3352 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003353 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354 }
3355
Lloyd Pique31cb2942018-10-19 17:23:03 -07003356 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003357
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003358 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003359 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003360 // when using overlays, we assume a fully transparent framebuffer
3361 // NOTE: we could reduce how much we need to clear, for instance
3362 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003363 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003364 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003365 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003366 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003367 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003368 // we're left with the letterbox region
3369 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003371
3372 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003373 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003374
Mathias Agopianb9494d52012-04-18 02:28:45 -07003375 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003376 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003377 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003378 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003379 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003380 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003381
Lloyd Pique32cbe282018-10-19 13:09:22 -07003382 const Rect& bounds = displayState.bounds;
3383 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003384 if (scissor != bounds) {
3385 // scissor doesn't match the screen's dimensions, so we
3386 // need to clear everything outside of it and enable
3387 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003388
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003389 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003390 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003391 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003392 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003393
Mathias Agopian85d751c2012-08-29 16:59:24 -07003394 /*
3395 * and then, render the layers targeted at the framebuffer
3396 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003397
Dan Stoza9e56aa02015-11-02 13:00:03 -08003398 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003399 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003400 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003401 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003402 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003403 displayTransform.transform(layer->visibleRegion)));
3404 ALOGV("Layer: %s", layer->getName().string());
3405 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003407 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 case HWC2::Composition::Cursor:
3409 case HWC2::Composition::Device:
3410 case HWC2::Composition::Sideband:
3411 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003412 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003413 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003414 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003415 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003416 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003417 // never clear the very first layer since we're
3418 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003419 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003420 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003421 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003422 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003423 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003424 if (layer->hasColorTransform()) {
3425 mat4 tmpMatrix;
3426 if (applyColorMatrix) {
3427 tmpMatrix = mDrawingState.colorMatrix;
3428 }
3429 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003430 getRenderEngine().setColorTransform(tmpMatrix);
3431 } else {
3432 getRenderEngine().setColorTransform(colorMatrix);
3433 }
David Sodmanc1498e62018-09-12 14:36:26 -07003434 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003435 break;
3436 }
3437 default:
3438 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003439 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 } else {
3441 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003442 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003443 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003444 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003445
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003446 // Perform some cleanup steps if we used client composition.
3447 if (hasClientComposition) {
3448 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003449 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003450 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003451 // Clear out error flags here so that we don't wait until next
3452 // composition to log.
3453 getRenderEngine().checkErrors();
3454 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003455 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456}
3457
Chia-I Wu28e3a252018-09-07 12:05:02 -07003458void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003459 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003460 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461}
3462
Dan Stoza7d89d062015-04-30 13:29:25 -07003463status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003464 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003465 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003467 const sp<Layer>& parent,
3468 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003469{
Dan Stoza7d89d062015-04-30 13:29:25 -07003470 // add this layer to the current state list
3471 {
3472 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003473 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003474 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3475 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003476 return NO_MEMORY;
3477 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003478 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003480 } else if (parent == nullptr) {
3481 lbc->onRemovedFromCurrentState();
3482 } else if (parent->isRemovedFromCurrentState()) {
3483 parent->addChild(lbc);
3484 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003485 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003486 parent->addChild(lbc);
3487 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003488
Yiwei Zhang243b3782018-05-15 17:40:04 -07003489 if (gbc != nullptr) {
3490 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3491 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3492 mMaxGraphicBufferProducerListSize,
3493 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3494 mGraphicBufferProducerList.size(),
3495 mMaxGraphicBufferProducerListSize, mNumLayers);
3496 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003497 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003498 }
3499
Mathias Agopian96f08192010-06-02 23:28:45 -07003500 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003501 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003502
Dan Stoza7d89d062015-04-30 13:29:25 -07003503 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003504}
3505
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003506uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003507 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003508}
3509
Mathias Agopian3f844832013-08-07 21:24:32 -07003510uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003511 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512}
3513
Mathias Agopian3f844832013-08-07 21:24:32 -07003514uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003515 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003516}
3517
3518uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003519 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003520 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003521 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003523 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 }
3525 return old;
3526}
3527
Marissa Wall713b63f2018-10-17 15:42:43 -07003528bool SurfaceFlinger::flushTransactionQueues() {
3529 Mutex::Autolock _l(mStateLock);
3530 auto it = mTransactionQueues.begin();
3531 while (it != mTransactionQueues.end()) {
3532 auto& [applyToken, transactionQueue] = *it;
3533
3534 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003535 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3536 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003537 break;
3538 }
chaviw273171b2018-12-26 11:46:30 -08003539 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003540 transactionQueue.pop();
3541 }
3542
3543 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3544 }
3545 return mTransactionQueues.empty();
3546}
3547
chaviwca27f252018-02-06 16:46:39 -08003548bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3549 for (const ComposerState& state : states) {
3550 // Here we need to check that the interface we're given is indeed
3551 // one of our own. A malicious client could give us a nullptr
3552 // IInterface, or one of its own or even one of our own but a
3553 // different type. All these situations would cause us to crash.
3554 if (state.client == nullptr) {
3555 return true;
3556 }
3557
3558 sp<IBinder> binder = IInterface::asBinder(state.client);
3559 if (binder == nullptr) {
3560 return true;
3561 }
3562
3563 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3564 return true;
3565 }
3566 }
3567 return false;
3568}
3569
Marissa Wall17b4e452018-12-26 16:32:34 -08003570bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3571 const Vector<ComposerState>& states) {
3572 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3573 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3574 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3575 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3576 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3577 return false;
3578 }
3579
Marissa Wall713b63f2018-10-17 15:42:43 -07003580 for (const ComposerState& state : states) {
3581 const layer_state_t& s = state.state;
3582 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3583 continue;
3584 }
3585 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003586 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003587 }
3588 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003589 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003590}
3591
3592void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3593 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003594 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003595 const InputWindowCommands& inputWindowCommands,
3596 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003597 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003598 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003599
chaviwca27f252018-02-06 16:46:39 -08003600 if (containsAnyInvalidClientState(states)) {
3601 return;
3602 }
3603
Marissa Wall713b63f2018-10-17 15:42:43 -07003604 // If its TransactionQueue already has a pending TransactionState or if it is pending
3605 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003606 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3607 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003608 setTransactionFlags(eTransactionNeeded);
3609 return;
3610 }
3611
chaviw273171b2018-12-26 11:46:30 -08003612 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003613}
3614
3615void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003616 const Vector<DisplayState>& displays, uint32_t flags,
3617 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 uint32_t transactionFlags = 0;
3619
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003620 if (flags & eAnimation) {
3621 // For window updates that are part of an animation we must wait for
3622 // previous animation "frames" to be handled.
3623 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003624 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003625 if (CC_UNLIKELY(err != NO_ERROR)) {
3626 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003627 // caller after a few seconds.
3628 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3629 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 mAnimTransactionPending = false;
3631 break;
3632 }
3633 }
3634 }
3635
chaviwca27f252018-02-06 16:46:39 -08003636 for (const DisplayState& display : displays) {
3637 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003638 }
3639
Marissa Walle2ffb422018-10-12 11:33:52 -07003640 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003641 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003642 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003643 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003644 // If the state doesn't require a traversal and there are callbacks, send them now
3645 if (!(clientStateFlags & eTraversalNeeded)) {
3646 mTransactionCompletedThread.sendCallbacks();
3647 }
3648 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003649
chaviw273171b2018-12-26 11:46:30 -08003650 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3651
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003652 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3653 // anyway. This can be used as a flush mechanism for previous async transactions.
3654 // Empty animation transaction can be used to simulate back-pressure, so also force a
3655 // transaction for empty animation transactions.
3656 if (transactionFlags == 0 &&
3657 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003658 transactionFlags = eTransactionNeeded;
3659 }
3660
Mathias Agopian386aa982011-11-07 21:58:03 -08003661 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003662 if (mInterceptor->isEnabled()) {
3663 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003664 }
Irvel468051e2016-06-13 16:44:44 -07003665
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003667 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3668 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003669 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003670
3671 // if this is a synchronous transaction, wait for it to take effect
3672 // before returning.
3673 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003676 if (flags & eAnimation) {
3677 mAnimTransactionPending = true;
3678 }
3679 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3681 if (CC_UNLIKELY(err != NO_ERROR)) {
3682 // just in case something goes wrong in SF, return to the
3683 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3685 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003686 break;
3687 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003689 }
3690}
3691
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003692uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3693 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3694 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003695
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003697 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3698
3699 const uint32_t what = s.what;
3700 if (what & DisplayState::eSurfaceChanged) {
3701 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3702 state.surface = s.surface;
3703 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003704 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003705 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003706 if (what & DisplayState::eLayerStackChanged) {
3707 if (state.layerStack != s.layerStack) {
3708 state.layerStack = s.layerStack;
3709 flags |= eDisplayTransactionNeeded;
3710 }
3711 }
3712 if (what & DisplayState::eDisplayProjectionChanged) {
3713 if (state.orientation != s.orientation) {
3714 state.orientation = s.orientation;
3715 flags |= eDisplayTransactionNeeded;
3716 }
3717 if (state.frame != s.frame) {
3718 state.frame = s.frame;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 if (state.viewport != s.viewport) {
3722 state.viewport = s.viewport;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 }
3726 if (what & DisplayState::eDisplaySizeChanged) {
3727 if (state.width != s.width) {
3728 state.width = s.width;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 if (state.height != s.height) {
3732 state.height = s.height;
3733 flags |= eDisplayTransactionNeeded;
3734 }
3735 }
3736
Mathias Agopiane57f2922012-08-09 16:29:12 -07003737 return flags;
3738}
3739
Robert Carrd4ae7f32018-06-07 16:10:57 -07003740bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3741 IPCThreadState* ipc = IPCThreadState::self();
3742 const int pid = ipc->getCallingPid();
3743 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003744 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003745 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003746 return false;
3747 }
3748 return true;
3749}
3750
chaviwca27f252018-02-06 16:46:39 -08003751uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3752 const layer_state_t& s = composerState.state;
3753 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3754
Mathias Agopian13127d82013-03-05 17:47:11 -08003755 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003756 if (layer == nullptr) {
3757 return 0;
3758 }
3759
chaviw8b3871a2017-11-01 17:41:01 -07003760 uint32_t flags = 0;
3761
Garfield Tan8a3083e2018-12-03 13:21:07 -08003762 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003763 bool geometryAppliesWithResize =
3764 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003765
3766 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3767 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003768 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003769 layer->pushPendingState();
3770 }
3771
chaviw8b3871a2017-11-01 17:41:01 -07003772 if (what & layer_state_t::ePositionChanged) {
3773 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3774 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003775 }
chaviw8b3871a2017-11-01 17:41:01 -07003776 }
3777 if (what & layer_state_t::eLayerChanged) {
3778 // NOTE: index needs to be calculated before we update the state
3779 const auto& p = layer->getParent();
3780 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003781 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003782 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 mCurrentState.layersSortedByZ.removeAt(idx);
3784 mCurrentState.layersSortedByZ.add(layer);
3785 // we need traversal (state changed)
3786 // AND transaction (list changed)
3787 flags |= eTransactionNeeded|eTraversalNeeded;
3788 }
chaviw8b3871a2017-11-01 17:41:01 -07003789 } else {
3790 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003791 flags |= eTransactionNeeded|eTraversalNeeded;
3792 }
3793 }
chaviw8b3871a2017-11-01 17:41:01 -07003794 }
3795 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003796 // NOTE: index needs to be calculated before we update the state
3797 const auto& p = layer->getParent();
3798 if (p == nullptr) {
3799 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3800 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3801 mCurrentState.layersSortedByZ.removeAt(idx);
3802 mCurrentState.layersSortedByZ.add(layer);
3803 // we need traversal (state changed)
3804 // AND transaction (list changed)
3805 flags |= eTransactionNeeded|eTraversalNeeded;
3806 }
3807 } else {
3808 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3809 flags |= eTransactionNeeded|eTraversalNeeded;
3810 }
chaviw8b3871a2017-11-01 17:41:01 -07003811 }
3812 }
3813 if (what & layer_state_t::eSizeChanged) {
3814 if (layer->setSize(s.w, s.h)) {
3815 flags |= eTraversalNeeded;
3816 }
3817 }
3818 if (what & layer_state_t::eAlphaChanged) {
3819 if (layer->setAlpha(s.alpha))
3820 flags |= eTraversalNeeded;
3821 }
3822 if (what & layer_state_t::eColorChanged) {
3823 if (layer->setColor(s.color))
3824 flags |= eTraversalNeeded;
3825 }
Valerie Haued54efa2019-01-11 20:03:14 -08003826 if (what & layer_state_t::eColorAlphaChanged) {
3827 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3828 }
3829 if (what & layer_state_t::eColorDataspaceChanged) {
3830 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3831 }
Peiyong Lind3788632018-09-18 16:01:31 -07003832 if (what & layer_state_t::eColorTransformChanged) {
3833 if (layer->setColorTransform(s.colorTransform)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
chaviw8b3871a2017-11-01 17:41:01 -07003837 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003838 // TODO: b/109894387
3839 //
3840 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3841 // rotation. To see the problem observe that if we have a square parent, and a child
3842 // of the same size, then we rotate the child 45 degrees around it's center, the child
3843 // must now be cropped to a non rectangular 8 sided region.
3844 //
3845 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3846 // private API, and the WindowManager only uses rotation in one case, which is on a top
3847 // level layer in which cropping is not an issue.
3848 //
3849 // However given that abuse of rotation matrices could lead to surfaces extending outside
3850 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3851 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3852 // transformations.
3853 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003854 flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eTransparentRegionChanged) {
3857 if (layer->setTransparentRegionHint(s.transparentRegion))
3858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eFlagsChanged) {
3861 if (layer->setFlags(s.flags, s.mask))
3862 flags |= eTraversalNeeded;
3863 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003864 if (what & layer_state_t::eCropChanged_legacy) {
3865 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003866 flags |= eTraversalNeeded;
3867 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003868 if (what & layer_state_t::eCornerRadiusChanged) {
3869 if (layer->setCornerRadius(s.cornerRadius))
3870 flags |= eTraversalNeeded;
3871 }
chaviw8b3871a2017-11-01 17:41:01 -07003872 if (what & layer_state_t::eLayerStackChanged) {
3873 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3874 // We only allow setting layer stacks for top level layers,
3875 // everything else inherits layer stack from its parent.
3876 if (layer->hasParent()) {
3877 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3878 layer->getName().string());
3879 } else if (idx < 0) {
3880 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3881 "that also does not appear in the top level layer list. Something"
3882 " has gone wrong.", layer->getName().string());
3883 } else if (layer->setLayerStack(s.layerStack)) {
3884 mCurrentState.layersSortedByZ.removeAt(idx);
3885 mCurrentState.layersSortedByZ.add(layer);
3886 // we need traversal (state changed)
3887 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003888 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003889 }
3890 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003891 if (what & layer_state_t::eDeferTransaction_legacy) {
3892 if (s.barrierHandle_legacy != nullptr) {
3893 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3894 } else if (s.barrierGbp_legacy != nullptr) {
3895 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (authenticateSurfaceTextureLocked(gbp)) {
3897 const auto& otherLayer =
3898 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003899 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003900 } else {
3901 ALOGE("Attempt to defer transaction to to an"
3902 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003903 }
3904 }
chaviw8b3871a2017-11-01 17:41:01 -07003905 // We don't trigger a traversal here because if no other state is
3906 // changed, we don't want this to cause any more work
3907 }
3908 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003909 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003911 if (!hadParent) {
3912 mCurrentState.layersSortedByZ.remove(layer);
3913 }
chaviw8b3871a2017-11-01 17:41:01 -07003914 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003915 }
chaviw8b3871a2017-11-01 17:41:01 -07003916 }
3917 if (what & layer_state_t::eReparentChildren) {
3918 if (layer->reparentChildren(s.reparentHandle)) {
3919 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003920 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 if (what & layer_state_t::eDetachChildren) {
3923 layer->detachChildren();
3924 }
3925 if (what & layer_state_t::eOverrideScalingModeChanged) {
3926 layer->setOverrideScalingMode(s.overrideScalingMode);
3927 // We don't trigger a traversal here because if no other state is
3928 // changed, we don't want this to cause any more work
3929 }
Marissa Wall61c58622018-07-18 10:12:20 -07003930 if (what & layer_state_t::eTransformChanged) {
3931 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3934 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3935 flags |= eTraversalNeeded;
3936 }
3937 if (what & layer_state_t::eCropChanged) {
3938 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3939 }
Marissa Wall861616d2018-10-22 12:52:23 -07003940 if (what & layer_state_t::eFrameChanged) {
3941 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3942 }
Marissa Wall61c58622018-07-18 10:12:20 -07003943 if (what & layer_state_t::eBufferChanged) {
3944 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3945 }
3946 if (what & layer_state_t::eAcquireFenceChanged) {
3947 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3948 }
3949 if (what & layer_state_t::eDataspaceChanged) {
3950 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3951 }
3952 if (what & layer_state_t::eHdrMetadataChanged) {
3953 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3954 }
3955 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3956 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eApiChanged) {
3959 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3960 }
3961 if (what & layer_state_t::eSidebandStreamChanged) {
3962 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3963 }
Robert Carr720e5062018-07-30 17:45:14 -07003964 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003965 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3966 layer->setInputInfo(s.inputInfo);
3967 flags |= eTraversalNeeded;
3968 } else {
3969 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3970 }
Robert Carr720e5062018-07-30 17:45:14 -07003971 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003972 if (what & layer_state_t::eMetadataChanged) {
3973 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3974 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003975 std::vector<sp<CallbackHandle>> callbackHandles;
3976 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3977 mTransactionCompletedThread.run();
3978 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3979 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3980 }
3981 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003982 if (what & layer_state_t::eCachedBufferChanged) {
3983 sp<GraphicBuffer> buffer =
3984 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3985 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3986 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003987 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3988 // Do not put anything that updates layer state or modifies flags after
3989 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003990 return flags;
3991}
3992
chaviw273171b2018-12-26 11:46:30 -08003993uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3994 uint32_t flags = 0;
3995 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3996 flags |= eTraversalNeeded;
3997 }
3998
3999 mInputWindowCommands.merge(inputWindowCommands);
4000 return flags;
4001}
4002
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004003status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4004 uint32_t h, PixelFormat format, uint32_t flags,
4005 LayerMetadata metadata, sp<IBinder>* handle,
4006 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004007 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004008 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004009 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004010 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004011 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004012
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004013 status_t result = NO_ERROR;
4014
4015 sp<Layer> layer;
4016
Cody Northropbc755282017-03-31 12:00:08 -06004017 String8 uniqueName = getUniqueLayerName(name);
4018
Mathias Agopian3165cc22012-08-08 19:42:09 -07004019 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004020 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004021 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4022 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004025 case ISurfaceComposerClient::eFXSurfaceBufferState:
4026 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4027 break;
chaviw13fdc492017-06-27 12:40:18 -07004028 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004029 // check if buffer size is set for color layer.
4030 if (w > 0 || h > 0) {
4031 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4032 int(w), int(h));
4033 return BAD_VALUE;
4034 }
4035
chaviw13fdc492017-06-27 12:40:18 -07004036 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004037 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004038 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004039 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004040 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004041 // check if buffer size is set for container layer.
4042 if (w > 0 || h > 0) {
4043 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4044 int(w), int(h));
4045 return BAD_VALUE;
4046 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004047 result = createContainerLayer(client,
4048 uniqueName, w, h, flags,
4049 handle, &layer);
4050 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004051 default:
4052 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 break;
4054 }
4055
Dan Stoza7d89d062015-04-30 13:29:25 -07004056 if (result != NO_ERROR) {
4057 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004059
Chia-I Wuab0c3192017-08-01 11:29:00 -07004060 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4061 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004062 if (metadata.has(METADATA_WINDOW_TYPE)) {
4063 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4064 if (windowType == 441731) {
4065 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4066 layer->setPrimaryDisplayOnly();
4067 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004068 }
4069
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004070 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004071
Robert Carrb89ea9d2018-12-10 13:01:14 -08004072 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4073 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4074 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004075 if (result != NO_ERROR) {
4076 return result;
4077 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004078 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004079
4080 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004081 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082}
4083
Cody Northropbc755282017-03-31 12:00:08 -06004084String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4085{
4086 bool matchFound = true;
4087 uint32_t dupeCounter = 0;
4088
4089 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4090 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4091
Dan Stoza436ccf32018-06-21 12:10:12 -07004092 // Grab the state lock since we're accessing mCurrentState
4093 Mutex::Autolock lock(mStateLock);
4094
Cody Northropbc755282017-03-31 12:00:08 -06004095 // Loop over layers until we're sure there is no matching name
4096 while (matchFound) {
4097 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004098 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004099 if (layer->getName() == uniqueName) {
4100 matchFound = true;
4101 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4102 }
4103 });
4104 }
4105
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004106 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4107 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004108
4109 return uniqueName;
4110}
4111
Marissa Wallfd668622018-05-10 10:21:13 -07004112status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4113 uint32_t w, uint32_t h, uint32_t flags,
4114 PixelFormat& format, sp<IBinder>* handle,
4115 sp<IGraphicBufferProducer>* gbp,
4116 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004118 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 case PIXEL_FORMAT_TRANSPARENT:
4120 case PIXEL_FORMAT_TRANSLUCENT:
4121 format = PIXEL_FORMAT_RGBA_8888;
4122 break;
4123 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004124 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 break;
4126 }
4127
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004128 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004129 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004130 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004132 *handle = layer->getHandle();
4133 *gbp = layer->getProducer();
4134 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004136
Marissa Wallfd668622018-05-10 10:21:13 -07004137 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004138 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139}
4140
Marissa Wall61c58622018-07-18 10:12:20 -07004141status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4142 uint32_t w, uint32_t h, uint32_t flags,
4143 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004144 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004145 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004146 *handle = layer->getHandle();
4147 *outLayer = layer;
4148
4149 return NO_ERROR;
4150}
4151
chaviw13fdc492017-06-27 12:40:18 -07004152status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004154 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004156 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004157 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004158 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004159}
4160
Robert Carr6b3f6c52018-08-13 13:05:17 -07004161status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4162 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4163 sp<IBinder>* handle, sp<Layer>* outLayer)
4164{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004165 *outLayer =
4166 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004167 *handle = (*outLayer)->getHandle();
4168 return NO_ERROR;
4169}
4170
4171
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004172void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004173 mLayersPendingRemoval.add(layer);
4174 mLayersRemoved = true;
4175 setTransactionFlags(eTransactionNeeded);
4176}
4177
Robert Carr695d5282018-12-18 15:27:58 -08004178void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004179{
Robert Carr2e102c92018-10-23 12:11:15 -07004180 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004181 // If a layer has a parent, we allow it to out-live it's handle
4182 // with the idea that the parent holds a reference and will eventually
4183 // be cleaned up. However no one cleans up the top-level so we do so
4184 // here.
4185 if (layer->getParent() == nullptr) {
4186 mCurrentState.layersSortedByZ.remove(layer);
4187 }
4188 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004189 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004190}
4191
Mathias Agopianb60314a2012-04-10 22:09:54 -07004192// ---------------------------------------------------------------------------
4193
Andy McFadden13a082e2012-08-24 10:16:42 -07004194void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004195 const auto display = getDefaultDisplayDeviceLocked();
4196 if (!display) return;
4197
4198 const sp<IBinder> token = display->getDisplayToken().promote();
4199 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004200
Jesse Hall01e29052013-02-19 16:13:35 -08004201 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004202 Vector<ComposerState> state;
4203 Vector<DisplayState> displays;
4204 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004205 d.what = DisplayState::eDisplayProjectionChanged |
4206 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004207 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004208 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004209 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004210 d.frame.makeInvalid();
4211 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004212 d.width = 0;
4213 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004214 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004215 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004216
Dominik Laskowskie9774092018-12-11 10:04:24 -08004217 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004218
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 const nsecs_t vsyncPeriod = getVsyncPeriod();
4220 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004221
Brian Andersond0010582017-03-07 13:20:31 -08004222 // Use phase of 0 since phase is not known.
4223 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004224 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004225 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004226}
4227
4228void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004229 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004230 postMessageAsync(
4231 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004232}
4233
Dominik Laskowskie9774092018-12-11 10:04:24 -08004234void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 if (display->isVirtual()) {
4236 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004237 return;
4238 }
4239
Dominik Laskowski075d3172018-05-24 15:50:06 -07004240 const auto displayId = display->getId();
4241 LOG_ALWAYS_FATAL_IF(!displayId);
4242
Dominik Laskowski34157762018-10-31 13:07:19 -07004243 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004244
4245 int currentMode = display->getPowerMode();
4246 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004247 return;
4248 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004249
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004250 display->setPowerMode(mode);
4251
Lloyd Pique4dccc412018-01-22 17:21:36 -08004252 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004253 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004254 }
4255
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004256 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004257 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004258 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004259 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004260 if (mUseScheduler) {
4261 mScheduler->onScreenAcquired(mAppConnectionHandle);
4262 } else {
4263 mEventThread->onScreenAcquired();
4264 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004265 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004266 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004267
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004268 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004269 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004270 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004271
4272 struct sched_param param = {0};
4273 param.sched_priority = 1;
4274 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4275 ALOGW("Couldn't set SCHED_FIFO on display on");
4276 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004278 // Turn off the display
4279 struct sched_param param = {0};
4280 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4281 ALOGW("Couldn't set SCHED_OTHER on display off");
4282 }
4283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004285 if (mUseScheduler) {
4286 mScheduler->disableHardwareVsync(true);
4287 } else {
4288 disableHardwareVsync(true); // also cancels any in-progress resync
4289 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004290 if (mUseScheduler) {
4291 mScheduler->onScreenReleased(mAppConnectionHandle);
4292 } else {
4293 mEventThread->onScreenReleased();
4294 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004295 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004296
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004298 mVisibleRegionsDirty = true;
4299 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004300 } else if (mode == HWC_POWER_MODE_DOZE ||
4301 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004302 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004304 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004305 if (mUseScheduler) {
4306 mScheduler->onScreenAcquired(mAppConnectionHandle);
4307 } else {
4308 mEventThread->onScreenAcquired();
4309 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004310 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004311 }
4312 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4313 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004315 if (mUseScheduler) {
4316 mScheduler->disableHardwareVsync(true);
4317 } else {
4318 disableHardwareVsync(true); // also cancels any in-progress resync
4319 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004320 if (mUseScheduler) {
4321 mScheduler->onScreenReleased(mAppConnectionHandle);
4322 } else {
4323 mEventThread->onScreenReleased();
4324 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004325 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004326 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004327 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004328 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004329 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004330 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004332 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004333 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004334 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004335 // Update refresh rate stats.
4336 mRefreshRateStats->setPowerMode(mode);
4337 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004338 }
4339
Dominik Laskowski34157762018-10-31 13:07:19 -07004340 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004341}
4342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004344 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345 const auto display = getDisplayDevice(displayToken);
4346 if (!display) {
4347 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4348 displayToken.get());
4349 } else if (display->isVirtual()) {
4350 ALOGW("Attempt to set power mode %d for virtual display", mode);
4351 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004352 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004353 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004354 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004355}
4356
4357// ---------------------------------------------------------------------------
4358
Dominik Laskowskic2867142019-01-21 11:33:38 -08004359status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4360 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004362
Mathias Agopianbd115332013-04-18 16:41:04 -07004363 IPCThreadState* ipc = IPCThreadState::self();
4364 const int pid = ipc->getCallingPid();
4365 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004366
Mathias Agopianbd115332013-04-18 16:41:04 -07004367 if ((uid != AID_SHELL) &&
4368 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4370 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004372 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004373 // (this would indicate SF is stuck, but we want to be able to
4374 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004375 status_t err = mStateLock.timedLock(s2ns(1));
4376 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004377 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004378 StringAppendF(&result,
4379 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4380 "(no locks held)\n",
4381 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004382 }
4383
Dominik Laskowskic2867142019-01-21 11:33:38 -08004384 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004385
Dominik Laskowskic2867142019-01-21 11:33:38 -08004386 static const std::unordered_map<std::string, Dumper> dumpers = {
4387 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4388 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4389 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4390 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4391 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4392 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4393 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4394 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4395 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4396 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4397 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4398 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4399 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004400 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004401 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4402 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004403
Dominik Laskowskic2867142019-01-21 11:33:38 -08004404 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004405
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4407 (it->second)(args, asProto, result);
4408 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004409 if (asProto) {
4410 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4411 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4412 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004414 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004415 }
4416
Mathias Agopian9795c422009-08-26 16:36:26 -07004417 if (locked) {
4418 mStateLock.unlock();
4419 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004420 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004421 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 return NO_ERROR;
4423}
4424
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 mCurrentState.traverseInZOrder(
4427 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004428}
4429
Dominik Laskowskic2867142019-01-21 11:33:38 -08004430void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004431 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004432
Dominik Laskowskic2867142019-01-21 11:33:38 -08004433 if (args.size() > 1) {
4434 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004435 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004436 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004437 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004438 }
Robert Carr2047fae2016-11-28 14:09:09 -08004439 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440 } else {
4441 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442 }
4443}
4444
Dominik Laskowskic2867142019-01-21 11:33:38 -08004445void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004446 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004447 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004448 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004449 }
Robert Carr2047fae2016-11-28 14:09:09 -08004450 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004451
Svetoslavd85084b2014-03-20 10:28:31 -07004452 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453}
4454
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4456 mTimeStats->parseArgs(asProto, args, result);
4457}
4458
Jamie Gennis6547ff42013-07-16 20:12:42 -07004459// This should only be called from the main thread. Otherwise it would need
4460// the lock and should use mCurrentState rather than mDrawingState.
4461void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004462 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004463 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004464 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004465
4466 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4467}
4468
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004470 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004471
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004472 if (isLayerTripleBufferingDisabled())
4473 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004474
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4476 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4477 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4478 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4479 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4480 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004481 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004482}
4483
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004484void SurfaceFlinger::dumpVSync(std::string& result) const {
4485 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4486 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4487 StringAppendF(&result,
4488 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4489 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4490 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4491 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4492 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4493 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4494
4495 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4496
4497 if (mUseScheduler) {
4498 mScheduler->dump(mAppConnectionHandle, result);
4499 } else {
4500 mEventThread->dump(result);
4501 }
4502}
4503
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4505 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004506 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4507 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004508 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004509 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004510 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004511 }
David Sodman4a36e932017-11-07 14:29:47 -08004512 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004513 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004514 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4516 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004517}
4518
Dan Stozae77c7662016-05-13 11:37:28 -07004519void SurfaceFlinger::recordBufferingStats(const char* layerName,
4520 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004521 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4522 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004523 for (const auto& segment : history) {
4524 if (!segment.usedThirdBuffer) {
4525 stats.twoBufferTime += segment.totalTime;
4526 }
4527 if (segment.occupancyAverage < 1.0f) {
4528 stats.doubleBufferedTime += segment.totalTime;
4529 } else if (segment.occupancyAverage < 2.0f) {
4530 stats.tripleBufferedTime += segment.totalTime;
4531 }
4532 ++stats.numSegments;
4533 stats.totalTime += segment.totalTime;
4534 }
4535}
4536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4538 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004539
4540 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4541 const size_t count = currentLayers.size();
4542 for (size_t i=0 ; i<count ; i++) {
4543 currentLayers[i]->dumpFrameEvents(result);
4544 }
4545}
4546
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004548 result.append("Buffering stats:\n");
4549 result.append(" [Layer name] <Active time> <Two buffer> "
4550 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004551 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004552 typedef std::tuple<std::string, float, float, float> BufferTuple;
4553 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004554 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004555 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004556 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004557 if (stats.numSegments == 0) {
4558 continue;
4559 }
4560 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4561 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4562 stats.totalTime;
4563 float doubleBufferRatio = static_cast<float>(
4564 stats.doubleBufferedTime) / stats.totalTime;
4565 float tripleBufferRatio = static_cast<float>(
4566 stats.tripleBufferedTime) / stats.totalTime;
4567 sorted.insert({activeTime, {name, twoBufferRatio,
4568 doubleBufferRatio, tripleBufferRatio}});
4569 }
4570 for (const auto& sortedPair : sorted) {
4571 float activeTime = sortedPair.first;
4572 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4574 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004575 }
4576 result.append("\n");
4577}
4578
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004580 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004581 const auto displayId = display->getId();
4582 if (!displayId) {
4583 continue;
4584 }
4585 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004586 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004587 continue;
4588 }
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result,
4591 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4592 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004593 uint8_t port;
4594 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004595 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004596 result.append("no identification data\n");
4597 continue;
4598 }
4599
4600 if (!isEdid(data)) {
4601 result.append("unknown identification data: ");
4602 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004603 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 }
4605 result.append("\n");
4606 continue;
4607 }
4608
4609 const auto edid = parseEdid(data);
4610 if (!edid) {
4611 result.append("invalid EDID: ");
4612 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004614 }
4615 result.append("\n");
4616 continue;
4617 }
4618
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004620 result.append(edid->displayName.data(), edid->displayName.length());
4621 result.append("\"\n");
4622 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004623}
4624
Yiwei Zhang5434a782018-12-05 18:06:32 -08004625void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4626 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4627 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4628 StringAppendF(&result, "DisplayColorSetting: %s\n",
4629 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630
4631 // TODO: print out if wide-color mode is active or not
4632
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004633 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004634 const auto displayId = display->getId();
4635 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004636 continue;
4637 }
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004640 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004641 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004643 }
4644
Lloyd Pique32cbe282018-10-19 13:09:22 -07004645 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, " Current color mode: %s (%d)\n",
4647 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 }
4649 result.append("\n");
4650}
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004653 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004654 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4655 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004656 continue;
4657 }
4658
Dominik Laskowski05275f12018-11-01 15:03:24 -07004659 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4661 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004662 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 compositionInfo.dump(result, nullptr);
4664 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004665 }
4666 }
David Sodman7e4ae112018-02-09 15:02:28 -08004667}
4668
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004669LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004670 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004671 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4672 const State& state = useDrawing ? mDrawingState : mCurrentState;
4673 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004674 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004675 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004676 });
4677
4678 return layersProto;
4679}
4680
Lloyd Pique32cbe282018-10-19 13:09:22 -07004681LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004682 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004683
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004684 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004685 resolution->set_w(displayDevice.getWidth());
4686 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004687
Lloyd Pique32cbe282018-10-19 13:09:22 -07004688 auto display = displayDevice.getCompositionDisplay();
4689 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004690
Lloyd Pique32cbe282018-10-19 13:09:22 -07004691 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4692 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4693 layersProto.set_global_transform(displayState.orientation);
4694
4695 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004696 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004697 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004698 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004699 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004700 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701 }
4702 });
4703
4704 return layersProto;
4705}
4706
Dominik Laskowskic2867142019-01-21 11:33:38 -08004707void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4708 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004709 Colorizer colorizer(colorize);
4710
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711 // figure out if we're stuck somewhere
4712 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4715
4716 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004717 * Dump library configuration.
4718 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719
4720 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004721 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004723 appendSfConfigString(result);
4724 appendUiConfigString(result);
4725 appendGuiConfigString(result);
4726 result.append("\n");
4727
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004728 result.append("\nDisplay identification data:\n");
4729 dumpDisplayIdentificationData(result);
4730
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004731 result.append("\nWide-Color information:\n");
4732 dumpWideColorInfo(result);
4733
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004735 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004737 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004738 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004739
Andy McFadden41d67d72014-04-25 16:58:34 -07004740 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004741 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004742 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004743 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004744 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004745
Dan Stozab90cf072015-03-05 11:05:59 -08004746 dumpStaticScreenStats(result);
4747 result.append("\n");
4748
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004750
Dan Stozae77c7662016-05-13 11:37:28 -07004751 dumpBufferingStats(result);
4752
Andy McFadden4803b742012-09-24 19:07:20 -07004753 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754 * Dump the visible layer list
4755 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4758 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4759 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004760 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004761
Chia-I Wu2f884132018-09-13 15:17:58 -07004762 {
4763 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4764 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004766 result.append("\n");
4767 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768
David Sodman7e4ae112018-02-09 15:02:28 -08004769 result.append("\nFrame-Composition information:\n");
4770 dumpFrameCompositionInfo(result);
4771 result.append("\n");
4772
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004774 * Dump Display state
4775 */
4776
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004780 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004781 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004782 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004783 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004784
4785 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004786 * Dump SurfaceFlinger global state
4787 */
4788
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004790 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004792
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004793 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794
Dominik Laskowski075d3172018-05-24 15:50:06 -07004795 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004796 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4797 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4799 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004800 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 StringAppendF(&result,
4802 " transaction-flags : %08x\n"
4803 " gpu_to_cpu_unsupported : %d\n",
4804 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004805
Dominik Laskowski075d3172018-05-24 15:50:06 -07004806 if (const auto displayId = getInternalDisplayId();
4807 displayId && getHwComposer().isConnected(*displayId)) {
4808 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result,
4810 " refresh-rate : %f fps\n"
4811 " x-dpi : %f\n"
4812 " y-dpi : %f\n",
4813 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4814 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004815 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004818
Dan Stozae22aec72016-08-01 13:20:59 -07004819 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004820 * Tracing state
4821 */
4822 mTracing.dump(result);
4823 result.append("\n");
4824
4825 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004826 * HWC layer minidump
4827 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004828 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 const auto displayId = display->getId();
4830 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004831 continue;
4832 }
4833
Yiwei Zhang5434a782018-12-05 18:06:32 -08004834 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004835 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004836 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004837 result.append("\n");
4838 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839
4840 /*
4841 * Dump HWComposer state
4842 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004843 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004844 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004847 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004848 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
4850 /*
4851 * Dump gralloc state
4852 */
4853 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4854 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004855
4856 /*
4857 * Dump VrFlinger state if in use.
4858 */
4859 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4860 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004862 result.append("\n");
4863 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004864
4865 /**
4866 * Scheduler dump state.
4867 */
4868 if (mUseScheduler) {
4869 result.append("\nScheduler state:\n");
4870 result.append(mScheduler->doDump() + "\n");
4871 result.append(mRefreshRateStats->doDump() + "\n");
4872 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004873}
4874
Dominik Laskowski075d3172018-05-24 15:50:06 -07004875const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004876 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004877 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004878 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004879 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004880 }
4881 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004882
Dominik Laskowski34157762018-10-31 13:07:19 -07004883 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004884 static const Vector<sp<Layer>> empty;
4885 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004886}
4887
Keun young Park63f165f2012-08-31 10:53:36 -07004888bool SurfaceFlinger::startDdmConnection()
4889{
4890 void* libddmconnection_dso =
4891 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4892 if (!libddmconnection_dso) {
4893 return false;
4894 }
4895 void (*DdmConnection_start)(const char* name);
4896 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004897 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004898 if (!DdmConnection_start) {
4899 dlclose(libddmconnection_dso);
4900 return false;
4901 }
4902 (*DdmConnection_start)(getServiceName());
4903 return true;
4904}
4905
Chia-I Wu28f320b2018-05-03 11:02:56 -07004906void SurfaceFlinger::updateColorMatrixLocked() {
4907 mat4 colorMatrix;
4908 if (mGlobalSaturationFactor != 1.0f) {
4909 // Rec.709 luma coefficients
4910 float3 luminance{0.213f, 0.715f, 0.072f};
4911 luminance *= 1.0f - mGlobalSaturationFactor;
4912 mat4 saturationMatrix = mat4(
4913 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4914 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4915 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4916 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4917 );
4918 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4919 } else {
4920 colorMatrix = mClientColorMatrix * mDaltonizer();
4921 }
4922
4923 if (mCurrentState.colorMatrix != colorMatrix) {
4924 mCurrentState.colorMatrix = colorMatrix;
4925 mCurrentState.colorMatrixChanged = true;
4926 setTransactionFlags(eTransactionNeeded);
4927 }
4928}
4929
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004930status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931#pragma clang diagnostic push
4932#pragma clang diagnostic error "-Wswitch-enum"
4933 switch (static_cast<ISurfaceComposerTag>(code)) {
4934 // These methods should at minimum make sure that the client requested
4935 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004936 case BOOT_FINISHED:
4937 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004938 case CREATE_DISPLAY:
4939 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004940 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004941 case GET_ACTIVE_COLOR_MODE:
4942 case GET_ANIMATION_FRAME_STATS:
4943 case GET_HDR_CAPABILITIES:
4944 case SET_ACTIVE_CONFIG:
4945 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004946 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004947 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004948 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004949 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4950 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004951 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4952 IPCThreadState* ipc = IPCThreadState::self();
4953 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4954 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004955 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 }
Robert Carr1db73f62016-12-21 12:58:51 -08004957 return OK;
4958 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004960 IPCThreadState* ipc = IPCThreadState::self();
4961 const int pid = ipc->getCallingPid();
4962 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004963 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4964 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004965 return PERMISSION_DENIED;
4966 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004968 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 // Used by apps to hook Choreographer to SurfaceFlinger.
4970 case CREATE_DISPLAY_EVENT_CONNECTION:
4971 // The following calls are currently used by clients that do not
4972 // request necessary permissions. However, they do not expose any secret
4973 // information, so it is OK to pass them.
4974 case AUTHENTICATE_SURFACE:
4975 case GET_ACTIVE_CONFIG:
4976 case GET_BUILT_IN_DISPLAY:
4977 case GET_DISPLAY_COLOR_MODES:
4978 case GET_DISPLAY_CONFIGS:
4979 case GET_DISPLAY_STATS:
4980 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4981 // Calling setTransactionState is safe, because you need to have been
4982 // granted a reference to Client* and Handle* to do anything with it.
4983 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004984 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004985 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004986 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004987 case GET_PROTECTED_CONTENT_SUPPORT:
4988 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08004989 case UNCACHE_BUFFER:
4990 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 return OK;
4992 }
4993 case CAPTURE_LAYERS:
4994 case CAPTURE_SCREEN: {
4995 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004996 IPCThreadState* ipc = IPCThreadState::self();
4997 const int pid = ipc->getCallingPid();
4998 const int uid = ipc->getCallingUid();
4999 if ((uid != AID_GRAPHICS) &&
5000 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5001 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5002 return PERMISSION_DENIED;
5003 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 return OK;
5005 }
5006 // The following codes are deprecated and should never be allowed to access SF.
5007 case CONNECT_DISPLAY_UNUSED:
5008 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5009 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5010 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005012 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013
5014 // These codes are used for the IBinder protocol to either interrogate the recipient
5015 // side of the transaction for its canonical interface descriptor or to dump its state.
5016 // We let them pass by default.
5017 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5018 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5019 code == IBinder::SYSPROPS_TRANSACTION) {
5020 return OK;
5021 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005022 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005024 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005025 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5026 return OK;
5027 }
5028 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5029 return PERMISSION_DENIED;
5030#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005031}
5032
Ana Krulec13be8ad2018-08-21 02:43:56 +00005033status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5034 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005035 status_t credentialCheck = CheckTransactCodeCredentials(code);
5036 if (credentialCheck != OK) {
5037 return credentialCheck;
5038 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5041 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005042 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005043 IPCThreadState* ipc = IPCThreadState::self();
5044 const int uid = ipc->getCallingUid();
5045 if (CC_UNLIKELY(uid != AID_SYSTEM
5046 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005047 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005048 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005049 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 return PERMISSION_DENIED;
5051 }
5052 int n;
5053 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005054 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005055 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 return NO_ERROR;
5057 case 1002: // SHOW_UPDATES
5058 n = data.readInt32();
5059 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005060 invalidateHwcGeometry();
5061 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005062 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005064 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005065 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005067 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005068 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005069 setTransactionFlags(
5070 eTransactionNeeded|
5071 eDisplayTransactionNeeded|
5072 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005073 return NO_ERROR;
5074 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005075 case 1006:{ // send empty update
5076 signalRefresh();
5077 return NO_ERROR;
5078 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005079 case 1008: // toggle use of hw composer
5080 n = data.readInt32();
5081 mDebugDisableHWC = n ? 1 : 0;
5082 invalidateHwcGeometry();
5083 repaintEverything();
5084 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005085 case 1009: // toggle use of transform hint
5086 n = data.readInt32();
5087 mDebugDisableTransformHint = n ? 1 : 0;
5088 invalidateHwcGeometry();
5089 repaintEverything();
5090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005092 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 reply->writeInt32(0);
5094 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005095 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005096 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 return NO_ERROR;
5098 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005099 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005100 if (!display) {
5101 return NAME_NOT_FOUND;
5102 }
5103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005104 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005105 return NO_ERROR;
5106 }
5107 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005108 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005109 // daltonize
5110 n = data.readInt32();
5111 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005112 case 1:
5113 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5114 break;
5115 case 2:
5116 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5117 break;
5118 case 3:
5119 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5120 break;
5121 default:
5122 mDaltonizer.setType(ColorBlindnessType::None);
5123 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005124 }
5125 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005126 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005127 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005128 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005129 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130
5131 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005132 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005133 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005134 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005135 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005136 // apply a color matrix
5137 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005138 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005139 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005140 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005141 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005142 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005143 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005144 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005145 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005146 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005147 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005148
5149 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5150 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005151 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005152 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5153 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5154 }
5155
Chia-I Wu28f320b2018-05-03 11:02:56 -07005156 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005157 return NO_ERROR;
5158 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005159 // This is an experimental interface
5160 // Needs to be shifted to proper binder interface when we productize
5161 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005162 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005163 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005164 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005165 return NO_ERROR;
5166 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005167 case 1017: {
5168 n = data.readInt32();
5169 mForceFullDamage = static_cast<bool>(n);
5170 return NO_ERROR;
5171 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005172 case 1018: { // Modify Choreographer's phase offset
5173 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005174 if (mUseScheduler) {
5175 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5176 } else {
5177 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5178 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005179 return NO_ERROR;
5180 }
5181 case 1019: { // Modify SurfaceFlinger's phase offset
5182 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005183 if (mUseScheduler) {
5184 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5185 } else {
5186 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5187 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005188 return NO_ERROR;
5189 }
Irvel468051e2016-06-13 16:44:44 -07005190 case 1020: { // Layer updates interceptor
5191 n = data.readInt32();
5192 if (n) {
5193 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005194 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005195 }
5196 else{
5197 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005198 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005199 }
5200 return NO_ERROR;
5201 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005202 case 1021: { // Disable HWC virtual displays
5203 n = data.readInt32();
5204 mUseHwcVirtualDisplays = !n;
5205 return NO_ERROR;
5206 }
Romain Guy0147a172017-06-01 13:53:56 -07005207 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005208 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005209 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005210
Chia-I Wu28f320b2018-05-03 11:02:56 -07005211 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005212 return NO_ERROR;
5213 }
Romain Guy54f154a2017-10-24 21:40:32 +01005214 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005215 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005216 invalidateHwcGeometry();
5217 repaintEverything();
5218 return NO_ERROR;
5219 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005220 // Deprecate, use 1030 to check whether the device is color managed.
5221 case 1024: {
5222 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005223 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005224 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005225 n = data.readInt32();
5226 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005227 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005228 mTracing.enable();
5229 doTracing("tracing.enable");
5230 reply->writeInt32(NO_ERROR);
5231 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005232 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005233 status_t err = mTracing.disable();
5234 reply->writeInt32(err);
5235 }
5236 return NO_ERROR;
5237 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005238 case 1026: { // Get layer tracing status
5239 reply->writeBool(mTracing.isEnabled());
5240 return NO_ERROR;
5241 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005242 // Is a DisplayColorSetting supported?
5243 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 const auto display = getDefaultDisplayDevice();
5245 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005246 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005247 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005248
5249 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5250 switch (setting) {
5251 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005252 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005253 break;
5254 case DisplayColorSetting::UNMANAGED:
5255 reply->writeBool(true);
5256 break;
5257 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005258 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005259 break;
5260 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261 reply->writeBool(
5262 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005263 break;
5264 }
5265 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005266 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005267 // Is VrFlinger active?
5268 case 1028: {
5269 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005270 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005271 return NO_ERROR;
5272 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005273 // Is device color managed?
5274 case 1030: {
5275 reply->writeBool(useColorManagement);
5276 return NO_ERROR;
5277 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005278 // Override default composition data space
5279 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5280 // && adb shell stop zygote && adb shell start zygote
5281 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5282 // adb shell stop zygote && adb shell start zygote
5283 case 1031: {
5284 Mutex::Autolock _l(mStateLock);
5285 n = data.readInt32();
5286 if (n) {
5287 n = data.readInt32();
5288 if (n) {
5289 Dataspace dataspace = static_cast<Dataspace>(n);
5290 if (!validateCompositionDataspace(dataspace)) {
5291 return BAD_VALUE;
5292 }
5293 mDefaultCompositionDataspace = dataspace;
5294 }
5295 n = data.readInt32();
5296 if (n) {
5297 Dataspace dataspace = static_cast<Dataspace>(n);
5298 if (!validateCompositionDataspace(dataspace)) {
5299 return BAD_VALUE;
5300 }
5301 mWideColorGamutCompositionDataspace = dataspace;
5302 }
5303 } else {
5304 // restore composition data space.
5305 mDefaultCompositionDataspace = defaultCompositionDataspace;
5306 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5307 }
5308 return NO_ERROR;
5309 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005310 }
5311 }
5312 return err;
5313}
5314
Steven Thomas6d8110b2017-08-31 18:24:21 -07005315void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005316 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005317 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005318}
5319
Ana Krulec7d1d6832018-12-27 11:10:09 -08005320void SurfaceFlinger::repaintEverythingForHWC() {
5321 mRepaintEverything = true;
5322 mEventQueue->invalidateForHWC();
5323}
5324
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5326class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005327public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5329 ~WindowDisconnector() {
5330 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005331 }
5332
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005333private:
5334 ANativeWindow* mWindow;
5335 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005336};
5337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005338status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005339 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5340 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005341 uint32_t reqWidth, uint32_t reqHeight,
5342 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005343 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005344 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005345
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005346 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005347
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005348 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5349
Chia-I Wu20261cb2018-08-23 12:55:44 -07005350 sp<DisplayDevice> display;
5351 {
5352 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005353
Chia-I Wu20261cb2018-08-23 12:55:44 -07005354 display = getDisplayDeviceLocked(displayToken);
5355 if (!display) return BAD_VALUE;
5356
Chia-I Wucb023152018-08-28 12:57:23 -07005357 // set the requested width/height to the logical display viewport size
5358 // by default
5359 if (reqWidth == 0 || reqHeight == 0) {
5360 reqWidth = uint32_t(display->getViewport().width());
5361 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005362 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005363 }
5364
Peiyong Lin0e003c92018-09-17 11:09:51 -07005365 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5366 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005367
5368 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005369 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005370 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5371 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005372}
5373
5374status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005375 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5376 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005377 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005378 ATRACE_CALL();
5379
5380 class LayerRenderArea : public RenderArea {
5381 public:
Robert Carr578038f2018-03-09 12:25:24 -08005382 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005383 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5384 bool childrenOnly)
5385 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005386 mLayer(layer),
5387 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005388 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005389 mFlinger(flinger),
5390 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005391 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005392 Rect getBounds() const override {
5393 const Layer::State& layerState(mLayer->getDrawingState());
5394 return mLayer->getBufferSize(layerState);
5395 }
Marissa Wall61c58622018-07-18 10:12:20 -07005396 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005397 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005398 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005399 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005400 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005401 }
chaviwa76b2712017-09-20 12:02:26 -07005402 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005403 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005404 Rect getSourceCrop() const override {
5405 if (mCrop.isEmpty()) {
5406 return getBounds();
5407 } else {
5408 return mCrop;
5409 }
5410 }
Robert Carr578038f2018-03-09 12:25:24 -08005411 class ReparentForDrawing {
5412 public:
5413 const sp<Layer>& oldParent;
5414 const sp<Layer>& newParent;
5415
5416 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5417 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005418 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005419 }
Robert Carr15eae092018-03-23 13:43:53 -07005420 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005421 };
5422
5423 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005424 const Rect sourceCrop = getSourceCrop();
5425 // no need to check rotation because there is none
5426 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5427 sourceCrop.height() != getReqHeight();
5428
Robert Carr578038f2018-03-09 12:25:24 -08005429 if (!mChildrenOnly) {
5430 mTransform = mLayer->getTransform().inverse();
5431 drawLayers();
5432 } else {
5433 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005434 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005435 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5436 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005437
5438 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5439 drawLayers();
5440 }
5441 }
chaviwa76b2712017-09-20 12:02:26 -07005442
chaviwa76b2712017-09-20 12:02:26 -07005443 private:
chaviw7206d492017-11-10 16:16:12 -08005444 const sp<Layer> mLayer;
5445 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005446
5447 // In the "childrenOnly" case we reparent the children to a screenshot
5448 // layer which has no properties set and which does not draw.
5449 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005450 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005451 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005452
5453 SurfaceFlinger* mFlinger;
5454 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005455 };
5456
5457 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5458 auto parent = layerHandle->owner.promote();
5459
Robert Carr2e102c92018-10-23 12:11:15 -07005460 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005461 ALOGE("captureLayers called with a removed parent");
5462 return NAME_NOT_FOUND;
5463 }
5464
Robert Carr578038f2018-03-09 12:25:24 -08005465 const int uid = IPCThreadState::self()->getCallingUid();
5466 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005467 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005468 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5469 return PERMISSION_DENIED;
5470 }
5471
chaviw7206d492017-11-10 16:16:12 -08005472 Rect crop(sourceCrop);
5473 if (sourceCrop.width() <= 0) {
5474 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005475 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005476 }
5477
5478 if (sourceCrop.height() <= 0) {
5479 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005480 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005481 }
5482
5483 int32_t reqWidth = crop.width() * frameScale;
5484 int32_t reqHeight = crop.height() * frameScale;
5485
Chia-I Wu20261cb2018-08-23 12:55:44 -07005486 // really small crop or frameScale
5487 if (reqWidth <= 0) {
5488 reqWidth = 1;
5489 }
5490 if (reqHeight <= 0) {
5491 reqHeight = 1;
5492 }
5493
Peiyong Lin0e003c92018-09-17 11:09:51 -07005494 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005495
Robert Carr578038f2018-03-09 12:25:24 -08005496 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005497 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5498 if (!layer->isVisible()) {
5499 return;
Robert Carr578038f2018-03-09 12:25:24 -08005500 } else if (childrenOnly && layer == parent.get()) {
5501 return;
chaviwa76b2712017-09-20 12:02:26 -07005502 }
5503 visitor(layer);
5504 });
5505 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005506 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005507}
5508
5509status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5510 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005511 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005512 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005513 bool useIdentityTransform) {
5514 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005515
Peiyong Lin0e003c92018-09-17 11:09:51 -07005516 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005517 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5518 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005519 *outBuffer =
5520 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5521 static_cast<android_pixel_format>(reqPixelFormat), 1,
5522 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005523
5524 // This mutex protects syncFd and captureResult for communication of the return values from the
5525 // main thread back to this Binder thread
5526 std::mutex captureMutex;
5527 std::condition_variable captureCondition;
5528 std::unique_lock<std::mutex> captureLock(captureMutex);
5529 int syncFd = -1;
5530 std::optional<status_t> captureResult;
5531
Robert Carr03480e22018-01-04 16:02:06 -08005532 const int uid = IPCThreadState::self()->getCallingUid();
5533 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5534
Dominik Laskowski8c001672018-05-30 16:52:06 -07005535 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536 // If there is a refresh pending, bug out early and tell the binder thread to try again
5537 // after the refresh.
5538 if (mRefreshPending) {
5539 ATRACE_NAME("Skipping screenshot for now");
5540 std::unique_lock<std::mutex> captureLock(captureMutex);
5541 captureResult = std::make_optional<status_t>(EAGAIN);
5542 captureCondition.notify_one();
5543 return;
5544 }
5545
5546 status_t result = NO_ERROR;
5547 int fd = -1;
5548 {
5549 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005550 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005551 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5552 useIdentityTransform, forSystem, &fd);
5553 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554 }
5555
5556 {
5557 std::unique_lock<std::mutex> captureLock(captureMutex);
5558 syncFd = fd;
5559 captureResult = std::make_optional<status_t>(result);
5560 captureCondition.notify_one();
5561 }
5562 });
5563
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005564 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005566 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 while (*captureResult == EAGAIN) {
5568 captureResult.reset();
5569 result = postMessageAsync(message);
5570 if (result != NO_ERROR) {
5571 return result;
5572 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005573 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005574 }
5575 result = *captureResult;
5576 }
5577
5578 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005579 sync_wait(syncFd, -1);
5580 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005581 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005582
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005584}
5585
chaviwa76b2712017-09-20 12:02:26 -07005586void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005587 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005588 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005589 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005590
Lloyd Pique144e1162017-12-20 16:44:52 -08005591 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005592
chaviwa76b2712017-09-20 12:02:26 -07005593 const auto reqWidth = renderArea.getReqWidth();
5594 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005595 const auto sourceCrop = renderArea.getSourceCrop();
5596 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005597
Peiyong Lin0e003c92018-09-17 11:09:51 -07005598 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005599 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005600
Mathias Agopian180f10d2013-04-10 22:55:41 -07005601 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005602 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005603
5604 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005605 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005606 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005607
chaviw50da5042018-04-09 13:49:37 -07005608 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005609 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005610 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005611
chaviwa76b2712017-09-20 12:02:26 -07005612 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005613 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005614 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005615 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005616 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617}
5618
chaviwa76b2712017-09-20 12:02:26 -07005619status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5620 TraverseLayersFunction traverseLayers,
5621 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005622 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005623 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005624 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005625 ATRACE_CALL();
5626
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005627 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005628
5629 traverseLayers([&](Layer* layer) {
5630 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5631 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005632
Robert Carr03480e22018-01-04 16:02:06 -08005633 // We allow the system server to take screenshots of secure layers for
5634 // use in situations like the Screen-rotation animation and place
5635 // the impetus on WindowManager to not persist them.
5636 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005637 ALOGW("FB is protected: PERMISSION_DENIED");
5638 return PERMISSION_DENIED;
5639 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005640 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005641
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005642 // this binds the given EGLImage as a framebuffer for the
5643 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005644 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005645 if (bufferBond.getStatus() != NO_ERROR) {
5646 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005647 return INVALID_OPERATION;
5648 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005649
Dan Stozaabcda352017-06-01 14:37:39 -07005650 // this will in fact render into our dequeued buffer
5651 // via an FBO, which means we didn't have to create
5652 // an EGLSurface and therefore we're not
5653 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005654 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005655
Peiyong Linfb530cf2018-12-15 05:07:38 +00005656 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005657 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005658 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005659 }
Alec Mouri492bc572018-09-11 21:40:04 +00005660 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005661
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005662 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005663}
5664
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005665// ---------------------------------------------------------------------------
5666
Dan Stoza412903f2017-04-27 13:42:17 -07005667void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5668 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005669}
5670
Dan Stoza412903f2017-04-27 13:42:17 -07005671void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5672 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005673}
5674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005675void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005676 const LayerVector::Visitor& visitor) {
5677 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005678 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005679 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005680 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005681 continue;
5682 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005683 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005684 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005685 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005686 return;
5687 }
chaviwa76b2712017-09-20 12:02:26 -07005688 if (!layer->isVisible()) {
5689 return;
5690 }
5691 visitor(layer);
5692 });
5693 }
5694}
5695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005696}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005697
Lloyd Pique074e8122018-07-26 12:57:23 -07005698
Mathias Agopian3f844832013-08-07 21:24:32 -07005699#if defined(__gl_h_)
5700#error "don't include gl/gl.h in this file"
5701#endif
5702
5703#if defined(__gl2_h_)
5704#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005705#endif