blob: 706e59a89777118d136c49c198eece19e94b8f8a [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mouri0f714832018-11-12 15:31:06 -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
Alec Mouri0f714832018-11-12 15:31:06 -08001840 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001842 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001844 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845
Alec Mouri0f714832018-11-12 15:31:06 -08001846 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847 }
1848 }
1849
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851
1852 if (mDebugRegion > 1) {
1853 usleep(mDebugRegion * 1000);
1854 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001855
Lloyd Pique32cbe282018-10-19 13:09:22 -07001856 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857}
1858
Adrian Roos1e1a1282017-11-01 19:05:31 +01001859void SurfaceFlinger::doTracing(const char* where) {
1860 ATRACE_CALL();
1861 ATRACE_NAME(where);
1862 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001863 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001864 }
1865}
1866
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001867void SurfaceFlinger::logLayerStats() {
1868 ATRACE_CALL();
1869 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001870 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001871 if (display->isPrimary()) {
1872 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001873 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001874 }
1875 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001876
1877 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001878 }
1879}
1880
David Sodman2b406362017-12-15 13:33:47 -08001881void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 ATRACE_CALL();
1884 ALOGV("preComposition");
1885
David Sodman2b406362017-12-15 13:33:47 -08001886 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1887
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001889 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001890 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 needExtraInvalidate = true;
1892 }
Robert Carr2047fae2016-11-28 14:09:09 -08001893 });
1894
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895 if (needExtraInvalidate) {
1896 signalLayerUpdate();
1897 }
1898}
1899
Ana Krulece588e312018-09-18 12:32:24 -07001900void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1901 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 // Update queue of past composite+present times and determine the
1903 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001904 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001906 while (!getBE().mCompositePresentTimes.empty()) {
1907 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 // Cached values should have been updated before calling this method,
1909 // which helps avoid duplicate syscalls.
1910 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1911 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1912 break;
1913 }
1914 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001915 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916 }
1917
1918 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001919 while (getBE().mCompositePresentTimes.size() > 16) {
1920 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 }
1922
Ana Krulece588e312018-09-18 12:32:24 -07001923 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001924}
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1927 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 // Integer division and modulo round toward 0 not -inf, so we need to
1929 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001930 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1931 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1932 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001933
Brian Andersond0010582017-03-07 13:20:31 -08001934 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1935 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001936 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001937 }
1938
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 // Snap the latency to a value that removes scheduling jitter from the
1940 // composition and present times, which often have >1ms of jitter.
1941 // Reducing jitter is important if an app attempts to extrapolate
1942 // something (such as user input) to an accurate diasplay time.
1943 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1944 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001945 nsecs_t bias = stats.vsyncPeriod / 2;
1946 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1947 nsecs_t snappedCompositeToPresentLatency =
1948 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949
David Sodman99974d22017-11-28 12:04:33 -08001950 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001951 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1952 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001953 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954}
1955
Ady Abraham8164d482019-01-11 14:47:59 -08001956// debug patch for b/119477596 - add stack guards to catch stack
1957// corruptions and disable clang optimizations.
1958// The code below is temporary and planned to be removed once stack
1959// corruptions are found.
1960#pragma clang optimize off
1961class StackGuard {
1962public:
1963 StackGuard(const char* name, const char* func, int line) {
1964 guarders.reserve(MIN_CAPACITY);
1965 guarders.push_back({this, name, func, line});
1966 validate();
1967 }
1968 ~StackGuard() {
1969 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1970 if (i->guard == this) {
1971 guarders.erase(i);
1972 break;
1973 }
1974 }
1975 }
1976
1977 static void validate() {
1978 for (const auto& guard : guarders) {
1979 if (guard.guard->cookie != COOKIE_VALUE) {
1980 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1981 CallStack stack(LOG_TAG);
1982 abort();
1983 }
1984 }
1985 }
1986
1987private:
1988 uint64_t cookie = COOKIE_VALUE;
1989 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1990 static constexpr size_t MIN_CAPACITY = 16;
1991
1992 struct GuarderElement {
1993 StackGuard* guard;
1994 const char* name;
1995 const char* func;
1996 int line;
1997 };
1998
1999 static std::vector<GuarderElement> guarders;
2000};
2001std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2002
2003#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2004
2005#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002006void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007{
Ady Abraham8164d482019-01-11 14:47:59 -08002008 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 ATRACE_CALL();
2010 ALOGV("postComposition");
2011
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002013 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002014 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002016 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002017 }
Ady Abraham8164d482019-01-11 14:47:59 -08002018 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002020 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002021 const auto displayDevice = getDefaultDisplayDeviceLocked();
2022 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2027
Lloyd Pique32cbe282018-10-19 13:09:22 -07002028 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002030 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2031 ->getRenderSurface()
2032 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 } else {
2035 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2036 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037
Ady Abraham8164d482019-01-11 14:47:59 -08002038 ASSERT_ON_STACK_GUARD();
2039
David Sodman73beded2017-11-15 11:56:06 -08002040 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002041 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2042 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002043 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002045 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046
Ana Krulece588e312018-09-18 12:32:24 -07002047 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002048 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002049 if (mUseScheduler) {
2050 mScheduler->getDisplayStatInfo(&stats);
2051 } else {
2052 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2053 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2054 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Ady Abraham8164d482019-01-11 14:47:59 -08002056 ASSERT_ON_STACK_GUARD();
2057
David Sodman2b406362017-12-15 13:33:47 -08002058 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059 // when we started doing work for this frame, but that should be okay
2060 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002061 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002062 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002063 DEFINE_STACK_GUARD(compositorTiming);
2064
Brian Andersond0010582017-03-07 13:20:31 -08002065 {
David Sodman99974d22017-11-28 12:04:33 -08002066 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002068 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002069
2070 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002071 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072
Robert Carr2047fae2016-11-28 14:09:09 -08002073 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002074 bool frameLatched =
2075 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2076 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002077 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002078 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002079 recordBufferingStats(layer->getName().string(),
2080 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002081 }
Ady Abraham8164d482019-01-11 14:47:59 -08002082 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002083 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002084
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002085 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002087 if (mUseScheduler) {
2088 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002090 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002091 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2092 enableHardwareVsync();
2093 } else {
2094 disableHardwareVsync(false);
2095 }
Ady Abraham8164d482019-01-11 14:47:59 -08002096 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002097 }
2098 }
2099
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002100 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2102 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002103 if (mUseScheduler) {
2104 mScheduler->enableHardwareVsync();
2105 } else {
2106 enableHardwareVsync();
2107 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002108 }
2109 }
2110
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
2112
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 if (mAnimCompositionPending) {
2114 mAnimCompositionPending = false;
2115
Brian Anderson4e606e32017-03-16 15:34:57 -07002116 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002117 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002118 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002119
2120 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002121 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002122 // The HWC doesn't support present fences, so use the refresh
2123 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002124 const nsecs_t presentTime =
2125 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002126 DEFINE_STACK_GUARD(presentTime);
2127
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002128 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002129 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002130 }
2131 mAnimFrameTracker.advanceFrame();
2132 }
Dan Stozab90cf072015-03-05 11:05:59 -08002133
Ady Abraham8164d482019-01-11 14:47:59 -08002134 ASSERT_ON_STACK_GUARD();
2135
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002136 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002137 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002138 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002139 }
2140
Ady Abraham8164d482019-01-11 14:47:59 -08002141 ASSERT_ON_STACK_GUARD();
2142
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002143 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002144
Ady Abraham8164d482019-01-11 14:47:59 -08002145 ASSERT_ON_STACK_GUARD();
2146
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2148 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002149 return;
2150 }
2151
2152 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002153 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002154 if (mHasPoweredOff) {
2155 mHasPoweredOff = false;
2156 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002157 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002159 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002161 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2162 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002163 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002164 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002165 }
David Sodman4a36e932017-11-07 14:29:47 -08002166 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002167
2168 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002169 }
David Sodman4a36e932017-11-07 14:29:47 -08002170 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002172
2173 {
2174 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002175 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002176 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002177 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002178 if (refillCount > 0) {
2179 const size_t offset = mTexturePool.size();
2180 mTexturePool.resize(mTexturePoolSize);
2181 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2182 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2183 }
Ady Abraham8164d482019-01-11 14:47:59 -08002184 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002185 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002186
Marissa Wallfda30bb2018-10-12 11:34:28 -07002187 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002188 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002189
2190 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002191}
Ady Abraham8164d482019-01-11 14:47:59 -08002192#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002193
2194void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 ATRACE_CALL();
2196 ALOGV("rebuildLayerStacks");
2197
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002198 // We need to clear these out now as these may be holding on to a
2199 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2200 // also holds a reference. When the set of visible layers is recomputed,
2201 // some layers may be destroyed if the only thing keeping them alive was
2202 // that list of visible layers associated with each display. The layer
2203 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2204 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2205 for (const auto& [token, display] : mDisplays) {
2206 getBE().mCompositionInfo[token].clear();
2207 }
2208
Mathias Agopiancd60f992012-08-16 16:28:27 -07002209 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002211 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002212 mVisibleRegionsDirty = false;
2213 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002214
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002215 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002216 const auto& displayDevice = pair.second;
2217 auto display = displayDevice->getCompositionDisplay();
2218 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002219 Region opaqueRegion;
2220 Region dirtyRegion;
2221 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002222 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002223 const ui::Transform& tr = displayState.transform;
2224 const Rect bounds = displayState.bounds;
2225 if (displayState.isEnabled) {
2226 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002227
Jeff Sharkey76488112017-02-27 14:15:18 -07002228 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002229 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002230 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002231 if (display->belongsInOutput(layer->getLayerStack(),
2232 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002233 Region drawRegion(tr.transform(
2234 layer->visibleNonTransparentRegion));
2235 drawRegion.andSelf(bounds);
2236 if (!drawRegion.isEmpty()) {
2237 layersSortedByZ.add(layer);
2238 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002239 // Clear out the HWC layer if this layer was
2240 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002241 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002242 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002243 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002244 // WM changes display->layerStack upon sleep/awake.
2245 // Here we make sure we delete the HWC layers even if
2246 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002247 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002248 }
2249
2250 // If a layer is not going to get a release fence because
2251 // it is invisible, but it is also going to release its
2252 // old buffer, add it to the list of layers needing
2253 // fences.
2254 if (hwcLayerDestroyed) {
2255 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2256 mLayersWithQueuedFrames.cend(), layer);
2257 if (found != mLayersWithQueuedFrames.cend()) {
2258 layersNeedingFences.add(layer);
2259 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002260 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002261 });
2262 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2264 displayDevice->setLayersNeedingFences(layersNeedingFences);
2265
2266 Region undefinedRegion{bounds};
2267 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2268
2269 display->editState().undefinedRegion = undefinedRegion;
2270 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002271 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002272 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002273}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002274
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002277// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002279// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280// The returned HDR data space is one of
2281// - Dataspace::UNKNOWN
2282// - Dataspace::BT2020_HLG
2283// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2285 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002286 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 *outHdrDataSpace = Dataspace::UNKNOWN;
2288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002290 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002291 case Dataspace::V0_SCRGB:
2292 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002293 case Dataspace::BT2020:
2294 case Dataspace::BT2020_ITU:
2295 case Dataspace::BT2020_LINEAR:
2296 case Dataspace::DISPLAY_BT2020:
2297 bestDataSpace = Dataspace::DISPLAY_BT2020;
2298 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002299 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002300 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002302 case Dataspace::BT2020_PQ:
2303 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002306 case Dataspace::BT2020_HLG:
2307 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002308 // When there's mixed PQ content and HLG content, we set the HDR
2309 // data space to be BT2020_PQ and convert HLG to PQ.
2310 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2311 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002312 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002313 break;
2314 default:
2315 break;
2316 }
Romain Guy54f154a2017-10-24 21:40:32 +01002317 }
2318
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002320}
2321
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2324 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2326 *outMode = ColorMode::NATIVE;
2327 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002330 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002331
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002335 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2336
Peiyong Lindfde5112018-06-05 10:58:41 -07002337 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002338 const bool isHdr =
2339 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002340 if (isHdr) {
2341 bestDataSpace = hdrDataSpace;
2342 }
2343
Chia-I Wu0d711262018-05-21 15:19:35 -07002344 RenderIntent intent;
2345 switch (mDisplayColorSetting) {
2346 case DisplayColorSetting::MANAGED:
2347 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002349 break;
2350 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002351 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002352 break;
2353 default: // vendor display color setting
2354 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2355 break;
2356 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002357
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002358 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002359}
2360
Lloyd Pique32cbe282018-10-19 13:09:22 -07002361void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2362 auto display = displayDevice->getCompositionDisplay();
2363 const auto& displayState = display->getState();
2364
Alec Mouri0f714832018-11-12 15:31:06 -08002365 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2367 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002368
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369 // If nothing has changed (!dirty), don't recompose.
2370 // If something changed, but we don't currently have any visible layers,
2371 // and didn't when we last did a composition, then skip it this time.
2372 // The second rule does two things:
2373 // - When all layers are removed from a display, we'll emit one black
2374 // frame, then nothing more until we get new layers.
2375 // - When a display is created with a private layer stack, we won't
2376 // emit any black frames until a layer is added to the layer stack.
2377 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002378
Dominik Laskowski075d3172018-05-24 15:50:06 -07002379 const char flagPrefix[] = {'-', '+'};
2380 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2382 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2383 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2384 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002385
Lloyd Pique31cb2942018-10-19 17:23:03 -07002386 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002387
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002390 }
2391}
2392
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2394 auto display = displayDevice->getCompositionDisplay();
2395 const auto& displayState = display->getState();
2396
2397 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398 return;
David Sodman2b406362017-12-15 13:33:47 -08002399 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400
Lloyd Pique31cb2942018-10-19 17:23:03 -07002401 status_t result = display->getRenderSurface()->prepareFrame(
2402 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002405}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002408 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 ALOGV("doComposition");
2410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411 auto display = displayDevice->getCompositionDisplay();
2412 const auto& displayState = display->getState();
2413
2414 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002416 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002417
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002422 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002423 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002425}
2426
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427void SurfaceFlinger::postFrame()
2428{
2429 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 const auto display = getDefaultDisplayDeviceLocked();
2431 if (display && getHwComposer().isConnected(*display->getId())) {
2432 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002433 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2434 logFrameStats();
2435 }
2436 }
2437}
2438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002440 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 auto display = displayDevice->getCompositionDisplay();
2444 const auto& displayState = display->getState();
2445 const auto displayId = display->getId();
2446
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 if (displayId) {
2451 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002452 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002455 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002456
Chia-I Wu7b549592017-11-15 09:14:57 -08002457 // The layer buffer from the previous frame (if any) is released
2458 // by HWC only when the release fence from this frame (if any) is
2459 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 if (displayId && layer->hasHwcLayer(*displayId)) {
2461 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2462 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002463 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002464
2465 // If the layer was client composited in the previous frame, we
2466 // need to merge with the previous client target acquire fence.
2467 // Since we do not track that, always merge with the current
2468 // client target acquire fence when it is available, even though
2469 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002470 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002471 releaseFence =
2472 Fence::merge("LayerRelease", releaseFence,
2473 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002474 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002475
David Sodman15094112018-10-11 09:39:37 -07002476 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 }
Chia-I Wu83806892017-11-16 10:50:20 -08002478
2479 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002481 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002484 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002485 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002486 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002487 }
2488 }
2489
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 if (displayId) {
2491 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002492 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002493 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494}
2495
Mathias Agopian87baae12012-07-31 12:38:26 -07002496void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497{
Mathias Agopian841cde52012-03-01 15:44:37 -08002498 ATRACE_CALL();
2499
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002500 // here we keep a copy of the drawing state (that is the state that's
2501 // going to be overwritten by handleTransactionLocked()) outside of
2502 // mStateLock so that the side-effects of the State assignment
2503 // don't happen with mStateLock held (which can cause deadlocks).
2504 State drawingState(mDrawingState);
2505
Mathias Agopianca4d3602011-05-19 15:38:14 -07002506 Mutex::Autolock _l(mStateLock);
2507 const nsecs_t now = systemTime();
2508 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509
Mathias Agopianca4d3602011-05-19 15:38:14 -07002510 // Here we're guaranteed that some transaction flags are set
2511 // so we can call handleTransactionLocked() unconditionally.
2512 // We call getTransactionFlags(), which will also clear the flags,
2513 // with mStateLock held to guarantee that mCurrentState won't change
2514 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002515
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002516 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002517 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002518 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002519
Mathias Agopianca4d3602011-05-19 15:38:14 -07002520 mLastTransactionTime = systemTime() - now;
2521 mDebugInTransaction = 0;
2522 invalidateHwcGeometry();
2523 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002524}
2525
Lloyd Piqueba04e622017-12-14 17:11:26 -08002526void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2527 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 const std::optional<DisplayIdentificationInfo> info =
2529 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002532 continue;
2533 }
2534
Lloyd Piqueba04e622017-12-14 17:11:26 -08002535 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002537 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 mPhysicalDisplayTokens[info->id] = new BBinder();
2539 DisplayDeviceState state;
2540 state.displayId = info->id;
2541 state.isSecure = true; // All physical displays are currently considered secure.
2542 state.displayName = info->name;
2543 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2544 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002545 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002546 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002547 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2550 if (index >= 0) {
2551 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2552 mInterceptor->saveDisplayDeletion(state.sequenceId);
2553 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556 }
2557
2558 processDisplayChangesLocked();
2559 }
2560
2561 mPendingHotplugEvents.clear();
2562}
2563
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002564void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2565 bool connected) {
2566 if (mUseScheduler) {
2567 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2568 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2569 } else {
2570 mEventThread->onHotplugReceived(displayType, connected);
2571 mSFEventThread->onHotplugReceived(displayType, connected);
2572 }
2573}
2574
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002577 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 const sp<IGraphicBufferProducer>& producer) {
2579 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002580 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002582 creationArgs.isSecure = state.isSecure;
2583 creationArgs.displaySurface = dispSurface;
2584 creationArgs.hasWideColorGamut = false;
2585 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002586
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2588 creationArgs.isPrimary = isInternalDisplay;
2589
2590 if (useColorManagement && displayId) {
2591 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002593 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002594 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002596
Dominik Laskowski7e045462018-05-30 13:02:02 -07002597 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002599 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 }
tangrobin6753a022018-08-10 10:58:54 +08002601 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002602
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 if (displayId) {
2604 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002605 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002607 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608
Lloyd Pique90c115d2018-09-18 21:39:42 -07002609 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002611 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 // Make sure that composition can never be stalled by a virtual display
2614 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002615 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002616 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2618 }
2619
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 creationArgs.displayInstallOrientation =
2621 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002622
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002624 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625
Lloyd Pique90c115d2018-09-18 21:39:42 -07002626 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627
2628 if (maxFrameBufferAcquiredBuffers >= 3) {
2629 nativeWindowSurface->preallocateBuffers();
2630 }
2631
2632 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002633 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002634 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002636 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002638 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2639 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 if (!state.isVirtual()) {
2641 LOG_ALWAYS_FATAL_IF(!displayId);
2642 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002643 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 display->setLayerStack(state.layerStack);
2646 display->setProjection(state.orientation, state.viewport, state.frame);
2647 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002649 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650}
2651
Lloyd Pique347200f2017-12-14 17:00:15 -08002652void SurfaceFlinger::processDisplayChangesLocked() {
2653 // here we take advantage of Vector's copy-on-write semantics to
2654 // improve performance by skipping the transaction entirely when
2655 // know that the lists are identical
2656 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2657 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2658 if (!curr.isIdenticalTo(draw)) {
2659 mVisibleRegionsDirty = true;
2660 const size_t cc = curr.size();
2661 size_t dc = draw.size();
2662
2663 // find the displays that were removed
2664 // (ie: in drawing state but not in current state)
2665 // also handle displays that changed
2666 // (ie: displays that are in both lists)
2667 for (size_t i = 0; i < dc;) {
2668 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2669 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 // Save display IDs before disconnecting.
2671 const auto internalDisplayId = getInternalDisplayId();
2672 const auto externalDisplayId = getExternalDisplayId();
2673
Lloyd Pique347200f2017-12-14 17:00:15 -08002674 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002676 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002677 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002678 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002679 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002680 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002681 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002682 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002683 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 } else {
2685 // this display is in both lists. see if something changed.
2686 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002688 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2689 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2690 if (state_binder != draw_binder) {
2691 // changing the surface is like destroying and
2692 // recreating the DisplayDevice, so we just remove it
2693 // from the drawing state, so that it get re-added
2694 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002696 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002698 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699 mDrawingState.displays.removeItemsAt(i);
2700 dc--;
2701 // at this point we must loop to the next item
2702 continue;
2703 }
2704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
2709 if ((state.orientation != draw[i].orientation) ||
2710 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716 }
2717 }
2718 ++i;
2719 }
2720
2721 // find displays that were added
2722 // (ie: in current state but not in drawing state)
2723 for (size_t i = 0; i < cc; i++) {
2724 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2725 const DisplayDeviceState& state(curr[i]);
2726
Lloyd Pique542307f2018-10-19 13:24:08 -07002727 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 sp<IGraphicBufferProducer> producer;
2729 sp<IGraphicBufferProducer> bqProducer;
2730 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002731 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002734 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 // Virtual displays without a surface are dormant:
2736 // they have external state (layer stack, projection,
2737 // etc.) but no internal state (i.e. a DisplayDevice).
2738 if (state.surface != nullptr) {
2739 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 int width = 0;
2742 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2744 int height = 0;
2745 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2747 int intFormat = 0;
2748 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2749 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002750 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 displayId =
2753 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 }
2755
2756 // TODO: Plumb requested format back up to consumer
2757
2758 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002759 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 bqProducer, bqConsumer,
2761 state.displayName);
2762
2763 dispSurface = vds;
2764 producer = vds;
2765 }
2766 } else {
2767 ALOGE_IF(state.surface != nullptr,
2768 "adding a supported display, but rendering "
2769 "surface is provided (%p), ignoring it",
2770 state.surface.get());
2771
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 displayId = state.displayId;
2773 LOG_ALWAYS_FATAL_IF(!displayId);
2774 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 producer = bqProducer;
2776 }
2777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002778 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002779 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002781 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002783 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002784 LOG_ALWAYS_FATAL_IF(!displayId);
2785
2786 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002787 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002788 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002789 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002790 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002791 }
2792 }
2793 }
2794 }
2795 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002796
2797 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002798}
2799
Mathias Agopian87baae12012-07-31 12:38:26 -07002800void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002801{
Dan Stoza7dde5992015-05-22 09:51:44 -07002802 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002803 mCurrentState.traverseInZOrder([](Layer* layer) {
2804 layer->notifyAvailableFrames();
2805 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002806
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 /*
2808 * Traversal of the children
2809 * (perform the transaction for each of them if needed)
2810 */
2811
Robert Carr720e5062018-07-30 17:45:14 -07002812 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002813 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002816 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
2818 const uint32_t flags = layer->doTransaction(0);
2819 if (flags & Layer::eVisibleRegion)
2820 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002821
2822 if (flags & Layer::eInputInfoChanged) {
2823 inputChanged = true;
2824 }
Robert Carr2047fae2016-11-28 14:09:09 -08002825 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 }
2827
2828 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002829 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830 */
2831
Mathias Agopiane57f2922012-08-09 16:29:12 -07002832 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002833 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002834 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002837 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002838 // The transform hint might have changed for some layers
2839 // (either because a display has changed, or because a layer
2840 // as changed).
2841 //
2842 // Walk through all the layers in currentLayers,
2843 // and update their transform hint.
2844 //
2845 // If a layer is visible only on a single display, then that
2846 // display is used to calculate the hint, otherwise we use the
2847 // default display.
2848 //
2849 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2850 // the hint is set before we acquire a buffer from the surface texture.
2851 //
2852 // NOTE: layer transactions have taken place already, so we use their
2853 // drawing state. However, SurfaceFlinger's own transaction has not
2854 // happened yet, so we must use the current state layer list
2855 // (soon to become the drawing state list).
2856 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002857 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002858 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002859 bool first = true;
2860 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002861 // NOTE: we rely on the fact that layers are sorted by
2862 // layerStack first (so we don't have to traverse the list
2863 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002865 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002866 currentlayerStack = layerStack;
2867 // figure out if this layerstack is mirrored
2868 // (more than one display) if so, pick the default display,
2869 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002870 hintDisplay = nullptr;
2871 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002872 if (display->getCompositionDisplay()
2873 ->belongsInOutput(layer->getLayerStack(),
2874 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002875 if (hintDisplay) {
2876 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002877 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002880 }
2881 }
2882 }
2883 }
Chet Haase91d25932013-04-11 15:24:55 -07002884
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002886 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2887 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002888
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002889 // could be null when this layer is using a layerStack
2890 // that is not visible on any display. Also can occur at
2891 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002892 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002893 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002895 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002896 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002897 if (hintDisplay) {
2898 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002899 }
Robert Carr2047fae2016-11-28 14:09:09 -08002900
2901 first = false;
2902 });
Mathias Agopian84300952012-11-21 16:02:13 -08002903 }
2904
2905
Mathias Agopian3559b072012-08-15 13:46:03 -07002906 /*
2907 * Perform our own transaction if needed
2908 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909
2910 if (mLayersAdded) {
2911 mLayersAdded = false;
2912 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002913 mVisibleRegionsDirty = true;
2914 }
2915
2916 // some layers might have been removed, so
2917 // we need to update the regions they're exposing.
2918 if (mLayersRemoved) {
2919 mLayersRemoved = false;
2920 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002921 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002922 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002923 // this layer is not visible anymore
2924 // TODO: we could traverse the tree from front to back and
2925 // compute the actual visible region
2926 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002927 Region visibleReg;
2928 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002929 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002930 }
Robert Carr2047fae2016-11-28 14:09:09 -08002931 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932 }
2933
2934 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002935
Vishnu Nairde19f852018-12-18 16:11:53 -08002936 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002937 updateInputWindows();
2938 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002939 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002940
Riley Andrews03414a12014-07-01 14:22:59 -07002941 updateCursorAsync();
2942}
2943
Robert Carr720e5062018-07-30 17:45:14 -07002944void SurfaceFlinger::updateInputWindows() {
2945 ATRACE_CALL();
2946
Vishnu Nairde19f852018-12-18 16:11:53 -08002947 if (mInputFlinger == nullptr) {
2948 return;
2949 }
2950
Robert Carr720e5062018-07-30 17:45:14 -07002951 Vector<InputWindowInfo> inputHandles;
2952
2953 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2954 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002955 // When calculating the screen bounds we ignore the transparent region since it may
2956 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002957 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002958 }
2959 });
2960 mInputFlinger->setInputWindows(inputHandles);
2961}
2962
chaviwfbe5d9c2018-12-26 12:23:37 -08002963void SurfaceFlinger::executeInputWindowCommands() {
2964 if (!mInputFlinger) {
2965 return;
2966 }
2967
2968 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2969 if (transferTouchFocusCommand.fromToken != nullptr &&
2970 transferTouchFocusCommand.toToken != nullptr &&
2971 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2972 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2973 transferTouchFocusCommand.toToken);
2974 }
2975 }
2976
2977 mInputWindowCommands.clear();
2978}
2979
Riley Andrews03414a12014-07-01 14:22:59 -07002980void SurfaceFlinger::updateCursorAsync()
2981{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002982 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002983 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002984 continue;
2985 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002987 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2988 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002989 }
2990 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991}
2992
chaviw61626f22018-11-15 16:26:27 -08002993void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2994 if (layer->hasReadyFrame()) {
2995 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2996 if (layer->shouldPresentNow(expectedPresentTime)) {
2997 bool ignored = false;
2998 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2999 }
3000 }
3001 layer->releasePendingBuffer(systemTime());
3002}
3003
Mathias Agopian4fec8732012-06-29 14:12:52 -07003004void SurfaceFlinger::commitTransaction()
3005{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003006 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003008 for (const auto& l : mLayersPendingRemoval) {
3009 recordBufferingStats(l->getName().string(),
3010 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003011
3012 // We need to release the HWC layers when the Layer is removed
3013 // from the current state otherwise the HWC layer just continues
3014 // showing at its last configured state until we eventually
3015 // abandon the buffer queue.
3016 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003017 l->destroyHwcLayersForAllDisplays();
3018 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003019 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003020 }
3021 mLayersPendingRemoval.clear();
3022 }
3023
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003024 // If this transaction is part of a window animation then the next frame
3025 // we composite should be considered an animation as well.
3026 mAnimCompositionPending = mAnimTransactionPending;
3027
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003029 // clear the "changed" flags in current state
3030 mCurrentState.colorMatrixChanged = false;
3031
Robert Carr1f0a16a2016-10-24 16:27:39 -07003032 mDrawingState.traverseInZOrder([](Layer* layer) {
3033 layer->commitChildList();
3034 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003035 mTransactionPending = false;
3036 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003037 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038}
3039
Lloyd Pique32cbe282018-10-19 13:09:22 -07003040void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003041 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003042 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003044
Lloyd Pique32cbe282018-10-19 13:09:22 -07003045 auto display = displayDevice->getCompositionDisplay();
3046
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 Region aboveOpaqueLayers;
3048 Region aboveCoveredLayers;
3049 Region dirty;
3050
Mathias Agopian87baae12012-07-31 12:38:26 -07003051 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052
Robert Carr2047fae2016-11-28 14:09:09 -08003053 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003054 // start with the whole surface at its current location
3055 const Layer::State& s(layer->getDrawingState());
3056
Jesse Hall01e29052013-02-19 16:13:35 -08003057 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003058 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003059 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003060 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003061
Mathias Agopianab028732010-03-16 16:41:46 -07003062 /*
3063 * opaqueRegion: area of a surface that is fully opaque.
3064 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003066
3067 /*
3068 * visibleRegion: area of a surface that is visible on screen
3069 * and not fully transparent. This is essentially the layer's
3070 * footprint minus the opaque regions above it.
3071 * Areas covered by a translucent surface are considered visible.
3072 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003074
3075 /*
3076 * coveredRegion: area of a surface that is covered by all
3077 * visible regions above it (which includes the translucent areas).
3078 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003080
Jesse Halla8026d22012-09-25 13:25:04 -07003081 /*
3082 * transparentRegion: area of a surface that is hinted to be completely
3083 * transparent. This is only used to tell when the layer has no visible
3084 * non-transparent regions and can be removed from the layer list. It
3085 * does not affect the visibleRegion of this layer or any layers
3086 * beneath it. The hint may not be correct if apps don't respect the
3087 * SurfaceView restrictions (which, sadly, some don't).
3088 */
3089 Region transparentRegion;
3090
Mathias Agopianab028732010-03-16 16:41:46 -07003091
3092 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003093 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003094 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003096
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003098 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003099 if (!visibleRegion.isEmpty()) {
3100 // Remove the transparent area from the visible region
3101 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003102 if (tr.preserveRects()) {
3103 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003104 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003106 // transformation too complex, can't do the
3107 // transparent region optimization.
3108 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003109 }
Mathias Agopianab028732010-03-16 16:41:46 -07003110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111
Mathias Agopianab028732010-03-16 16:41:46 -07003112 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003114 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003115 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003116 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003117 // the opaque region is the layer's footprint
3118 opaqueRegion = visibleRegion;
3119 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 }
3121 }
3122
Robert Carre5f4f692018-01-12 13:12:28 -08003123 if (visibleRegion.isEmpty()) {
3124 layer->clearVisibilityRegions();
3125 return;
3126 }
3127
Mathias Agopianab028732010-03-16 16:41:46 -07003128 // Clip the covered region to the visible region
3129 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3130
3131 // Update aboveCoveredLayers for next (lower) layer
3132 aboveCoveredLayers.orSelf(visibleRegion);
3133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 // subtract the opaque region covered by the layers above us
3135 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136
3137 // compute this layer's dirty region
3138 if (layer->contentDirty) {
3139 // we need to invalidate the whole region
3140 dirty = visibleRegion;
3141 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003142 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 layer->contentDirty = false;
3144 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003145 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003146 * the exposed region consists of two components:
3147 * 1) what's VISIBLE now and was COVERED before
3148 * 2) what's EXPOSED now less what was EXPOSED before
3149 *
3150 * note that (1) is conservative, we start with the whole
3151 * visible region but only keep what used to be covered by
3152 * something -- which mean it may have been exposed.
3153 *
3154 * (2) handles areas that were not covered by anything but got
3155 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003156 */
Mathias Agopianab028732010-03-16 16:41:46 -07003157 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003158 const Region oldVisibleRegion = layer->visibleRegion;
3159 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003160 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3161 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
3163 dirty.subtractSelf(aboveOpaqueLayers);
3164
3165 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003166 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167
Mathias Agopianab028732010-03-16 16:41:46 -07003168 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003170
Jesse Halla8026d22012-09-25 13:25:04 -07003171 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 layer->setVisibleRegion(visibleRegion);
3173 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003174 layer->setVisibleNonTransparentRegion(
3175 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003176 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177
Mathias Agopian87baae12012-07-31 12:38:26 -07003178 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179}
3180
Chia-I Wuab0c3192017-08-01 11:29:00 -07003181void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003182 for (const auto& [token, displayDevice] : mDisplays) {
3183 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003184 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003185 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003186 }
3187 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003188}
3189
Dan Stoza6b9454d2014-11-07 16:00:59 -08003190bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003192 ALOGV("handlePageFlip");
3193
Brian Andersond6927fb2016-07-23 23:37:30 -07003194 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195
Mathias Agopian4fec8732012-06-29 14:12:52 -07003196 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003197 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003198 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003199
3200 // Store the set of layers that need updates. This set must not change as
3201 // buffers are being latched, as this could result in a deadlock.
3202 // Example: Two producers share the same command stream and:
3203 // 1.) Layer 0 is latched
3204 // 2.) Layer 0 gets a new frame
3205 // 2.) Layer 1 gets a new frame
3206 // 3.) Layer 1 is latched.
3207 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3208 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003209 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003210 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003211 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003212 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3213 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003214 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003215 } else {
3216 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003217 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003218 } else {
3219 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003220 }
Robert Carr2047fae2016-11-28 14:09:09 -08003221 });
3222
Lloyd Piquef2c79392018-12-20 16:23:33 -08003223 if (!mLayersWithQueuedFrames.empty()) {
3224 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3225 // writes to Layer current state. See also b/119481871
3226 Mutex::Autolock lock(mStateLock);
3227
3228 for (auto& layer : mLayersWithQueuedFrames) {
3229 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3230 layer->useSurfaceDamage();
3231 invalidateLayerStack(layer, dirty);
3232 if (layer->isBufferLatched()) {
3233 newDataLatched = true;
3234 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003235 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003236 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003237
Alec Mouri86770e52018-09-24 22:40:58 +00003238 // Clear the renderengine fence here...
3239 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3240 // clear instead of sp::clear.
3241 getBE().flushFence = Fence::NO_FENCE;
3242
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003243 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003244
Vishnu Nairde19f852018-12-18 16:11:53 -08003245 if (visibleRegions) {
3246 // Update input window info if the layer receives its first buffer.
3247 updateInputWindows();
3248 }
3249
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 // If we will need to wake up at some time in the future to deal with a
3251 // queued frame that shouldn't be displayed during this vsync period, wake
3252 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003253 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 signalLayerUpdate();
3255 }
3256
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003257 // enter boot animation on first buffer latch
3258 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3259 ALOGI("Enter boot animation");
3260 mBootStage = BootStage::BOOTANIMATION;
3261 }
3262
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003264 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265}
3266
Mathias Agopianad456f92011-01-13 17:53:01 -08003267void SurfaceFlinger::invalidateHwcGeometry()
3268{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003269 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003270}
3271
Lloyd Pique32cbe282018-10-19 13:09:22 -07003272void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003273 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003274 auto display = displayDevice->getCompositionDisplay();
3275
Dan Stoza71433162014-02-04 16:22:36 -08003276 // We only need to actually compose the display if:
3277 // 1) It is being handled by hardware composer, which may need this to
3278 // keep its virtual display state machine in sync, or
3279 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003280 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003281 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003282 return;
3283 }
3284
Dan Stoza9e56aa02015-11-02 13:00:03 -08003285 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003286 base::unique_fd readyFence;
3287 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003288
3289 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003290 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291}
3292
Alec Mouri0f714832018-11-12 15:31:06 -08003293bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3294 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003295 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003296
Lloyd Pique32cbe282018-10-19 13:09:22 -07003297 auto display = displayDevice->getCompositionDisplay();
3298 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003299 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003300
3301 const Region bounds(displayState.bounds);
3302 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003303 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003304 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003305
Peiyong Lind3788632018-09-18 16:01:31 -07003306 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003307 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003308
Alec Mouri0f714832018-11-12 15:31:06 -08003309 renderengine::DisplaySettings clientCompositionDisplay;
3310 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3311 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003312
Dan Stoza9e56aa02015-11-02 13:00:03 -08003313 if (hasClientComposition) {
3314 ALOGV("hasClientComposition");
3315
Alec Mouri0f714832018-11-12 15:31:06 -08003316 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
Alec Mouri0f714832018-11-12 15:31:06 -08003325 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3326 clientCompositionDisplay.clip = displayState.scissor;
3327 const ui::Transform& displayTransform = displayState.transform;
3328 mat4 m;
3329 m[0][0] = displayTransform[0][0];
3330 m[0][1] = displayTransform[0][1];
3331 m[0][3] = displayTransform[0][2];
3332 m[1][0] = displayTransform[1][0];
3333 m[1][1] = displayTransform[1][1];
3334 m[1][3] = displayTransform[1][2];
3335 m[3][0] = displayTransform[2][0];
3336 m[3][1] = displayTransform[2][1];
3337 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338
Alec Mouri0f714832018-11-12 15:31:06 -08003339 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003340
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003341 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003342 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003343 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003345 }
Alec Mouri0f714832018-11-12 15:31:06 -08003346 clientCompositionDisplay.outputDataspace = outputDataspace;
3347 clientCompositionDisplay.maxLuminance =
3348 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003349
Lloyd Pique441d5042018-10-18 16:49:51 -07003350 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003351 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003352 getHwComposer()
3353 .hasDisplayCapability(displayId,
3354 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003355
Peiyong Lind3788632018-09-18 16:01:31 -07003356 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003357 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3358 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003359 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003360 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003361 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003362
Mathias Agopian85d751c2012-08-29 16:59:24 -07003363 /*
3364 * and then, render the layers targeted at the framebuffer
3365 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003366
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003368 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003369 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003371 const Region viewportRegion(displayState.viewport);
3372 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003373 ALOGV("Layer: %s", layer->getName().string());
3374 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003375 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003376 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003377 case HWC2::Composition::Cursor:
3378 case HWC2::Composition::Device:
3379 case HWC2::Composition::Sideband:
3380 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003381 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003382 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003383 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003384 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003385 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003386 // never clear the very first layer since we're
3387 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003388 renderengine::LayerSettings layerSettings;
3389 Region dummyRegion;
3390 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3391 layerSettings);
3392
3393 if (prepared) {
3394 layerSettings.source.buffer.buffer = nullptr;
3395 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3396 layerSettings.alpha = half(0.0);
3397 layerSettings.disableBlending = true;
3398 clientCompositionLayers.push_back(layerSettings);
3399 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003400 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003402 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003404 renderengine::LayerSettings layerSettings;
3405 bool prepared =
3406 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3407 if (prepared) {
3408 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003409 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 break;
3411 }
3412 default:
3413 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 } else {
3416 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003417 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003418 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003419 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003420
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003421 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003422 clientCompositionDisplay.clearRegion = clearRegion;
3423 if (!debugRegion.isEmpty()) {
3424 Region::const_iterator it = debugRegion.begin();
3425 Region::const_iterator end = debugRegion.end();
3426 while (it != end) {
3427 const Rect& rect = *it++;
3428 renderengine::LayerSettings layerSettings;
3429 layerSettings.source.buffer.buffer = nullptr;
3430 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3431 layerSettings.geometry.boundaries = rect.toFloatRect();
3432 layerSettings.alpha = half(1.0);
3433 clientCompositionLayers.push_back(layerSettings);
3434 }
3435 }
3436 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3437 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003438 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003439 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440}
3441
Chia-I Wu28e3a252018-09-07 12:05:02 -07003442void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003443 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003444 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003445}
3446
Dan Stoza7d89d062015-04-30 13:29:25 -07003447status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003448 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003449 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003451 const sp<Layer>& parent,
3452 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003453{
Dan Stoza7d89d062015-04-30 13:29:25 -07003454 // add this layer to the current state list
3455 {
3456 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003457 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003458 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3459 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003460 return NO_MEMORY;
3461 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003464 } else if (parent == nullptr) {
3465 lbc->onRemovedFromCurrentState();
3466 } else if (parent->isRemovedFromCurrentState()) {
3467 parent->addChild(lbc);
3468 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003469 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003470 parent->addChild(lbc);
3471 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003472
Yiwei Zhang243b3782018-05-15 17:40:04 -07003473 if (gbc != nullptr) {
3474 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3475 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3476 mMaxGraphicBufferProducerListSize,
3477 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3478 mGraphicBufferProducerList.size(),
3479 mMaxGraphicBufferProducerListSize, mNumLayers);
3480 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003481 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003482 }
3483
Mathias Agopian96f08192010-06-02 23:28:45 -07003484 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003485 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003486
Dan Stoza7d89d062015-04-30 13:29:25 -07003487 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003488}
3489
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003490uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003491 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003492}
3493
Mathias Agopian3f844832013-08-07 21:24:32 -07003494uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003495 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496}
3497
Mathias Agopian3f844832013-08-07 21:24:32 -07003498uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003499 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003500}
3501
3502uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003503 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003504 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003505 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003507 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 }
3509 return old;
3510}
3511
Marissa Wall713b63f2018-10-17 15:42:43 -07003512bool SurfaceFlinger::flushTransactionQueues() {
3513 Mutex::Autolock _l(mStateLock);
3514 auto it = mTransactionQueues.begin();
3515 while (it != mTransactionQueues.end()) {
3516 auto& [applyToken, transactionQueue] = *it;
3517
3518 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003519 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3520 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003521 break;
3522 }
chaviw273171b2018-12-26 11:46:30 -08003523 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003524 transactionQueue.pop();
3525 }
3526
3527 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3528 }
3529 return mTransactionQueues.empty();
3530}
3531
chaviwca27f252018-02-06 16:46:39 -08003532bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3533 for (const ComposerState& state : states) {
3534 // Here we need to check that the interface we're given is indeed
3535 // one of our own. A malicious client could give us a nullptr
3536 // IInterface, or one of its own or even one of our own but a
3537 // different type. All these situations would cause us to crash.
3538 if (state.client == nullptr) {
3539 return true;
3540 }
3541
3542 sp<IBinder> binder = IInterface::asBinder(state.client);
3543 if (binder == nullptr) {
3544 return true;
3545 }
3546
3547 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3548 return true;
3549 }
3550 }
3551 return false;
3552}
3553
Marissa Wall17b4e452018-12-26 16:32:34 -08003554bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3555 const Vector<ComposerState>& states) {
3556 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3557 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3558 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3559 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3560 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3561 return false;
3562 }
3563
Marissa Wall713b63f2018-10-17 15:42:43 -07003564 for (const ComposerState& state : states) {
3565 const layer_state_t& s = state.state;
3566 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3567 continue;
3568 }
3569 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003570 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 }
3572 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003574}
3575
3576void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3577 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003578 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003579 const InputWindowCommands& inputWindowCommands,
3580 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003581 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003582 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583
chaviwca27f252018-02-06 16:46:39 -08003584 if (containsAnyInvalidClientState(states)) {
3585 return;
3586 }
3587
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 // If its TransactionQueue already has a pending TransactionState or if it is pending
3589 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003590 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3591 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003592 setTransactionFlags(eTransactionNeeded);
3593 return;
3594 }
3595
chaviw273171b2018-12-26 11:46:30 -08003596 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003597}
3598
3599void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003600 const Vector<DisplayState>& displays, uint32_t flags,
3601 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003602 uint32_t transactionFlags = 0;
3603
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003604 if (flags & eAnimation) {
3605 // For window updates that are part of an animation we must wait for
3606 // previous animation "frames" to be handled.
3607 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003608 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003609 if (CC_UNLIKELY(err != NO_ERROR)) {
3610 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003611 // caller after a few seconds.
3612 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3613 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003614 mAnimTransactionPending = false;
3615 break;
3616 }
3617 }
3618 }
3619
chaviwca27f252018-02-06 16:46:39 -08003620 for (const DisplayState& display : displays) {
3621 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003622 }
3623
Marissa Walle2ffb422018-10-12 11:33:52 -07003624 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003625 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003626 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003627 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003628 // If the state doesn't require a traversal and there are callbacks, send them now
3629 if (!(clientStateFlags & eTraversalNeeded)) {
3630 mTransactionCompletedThread.sendCallbacks();
3631 }
3632 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003633
chaviw273171b2018-12-26 11:46:30 -08003634 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3635
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003636 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3637 // anyway. This can be used as a flush mechanism for previous async transactions.
3638 // Empty animation transaction can be used to simulate back-pressure, so also force a
3639 // transaction for empty animation transactions.
3640 if (transactionFlags == 0 &&
3641 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003642 transactionFlags = eTransactionNeeded;
3643 }
3644
Mathias Agopian386aa982011-11-07 21:58:03 -08003645 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003646 if (mInterceptor->isEnabled()) {
3647 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003648 }
Irvel468051e2016-06-13 16:44:44 -07003649
Mathias Agopian386aa982011-11-07 21:58:03 -08003650 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003651 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3652 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003653 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003654
3655 // if this is a synchronous transaction, wait for it to take effect
3656 // before returning.
3657 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003658 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003659 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003660 if (flags & eAnimation) {
3661 mAnimTransactionPending = true;
3662 }
3663 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003664 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3665 if (CC_UNLIKELY(err != NO_ERROR)) {
3666 // just in case something goes wrong in SF, return to the
3667 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003668 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3669 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003670 break;
3671 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673 }
3674}
3675
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003676uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3677 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3678 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003679
Mathias Agopiane57f2922012-08-09 16:29:12 -07003680 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003681 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3682
3683 const uint32_t what = s.what;
3684 if (what & DisplayState::eSurfaceChanged) {
3685 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3686 state.surface = s.surface;
3687 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003688 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003689 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003690 if (what & DisplayState::eLayerStackChanged) {
3691 if (state.layerStack != s.layerStack) {
3692 state.layerStack = s.layerStack;
3693 flags |= eDisplayTransactionNeeded;
3694 }
3695 }
3696 if (what & DisplayState::eDisplayProjectionChanged) {
3697 if (state.orientation != s.orientation) {
3698 state.orientation = s.orientation;
3699 flags |= eDisplayTransactionNeeded;
3700 }
3701 if (state.frame != s.frame) {
3702 state.frame = s.frame;
3703 flags |= eDisplayTransactionNeeded;
3704 }
3705 if (state.viewport != s.viewport) {
3706 state.viewport = s.viewport;
3707 flags |= eDisplayTransactionNeeded;
3708 }
3709 }
3710 if (what & DisplayState::eDisplaySizeChanged) {
3711 if (state.width != s.width) {
3712 state.width = s.width;
3713 flags |= eDisplayTransactionNeeded;
3714 }
3715 if (state.height != s.height) {
3716 state.height = s.height;
3717 flags |= eDisplayTransactionNeeded;
3718 }
3719 }
3720
Mathias Agopiane57f2922012-08-09 16:29:12 -07003721 return flags;
3722}
3723
Robert Carrd4ae7f32018-06-07 16:10:57 -07003724bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3725 IPCThreadState* ipc = IPCThreadState::self();
3726 const int pid = ipc->getCallingPid();
3727 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003728 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003729 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003730 return false;
3731 }
3732 return true;
3733}
3734
chaviwca27f252018-02-06 16:46:39 -08003735uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3736 const layer_state_t& s = composerState.state;
3737 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3738
Mathias Agopian13127d82013-03-05 17:47:11 -08003739 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003740 if (layer == nullptr) {
3741 return 0;
3742 }
3743
chaviw8b3871a2017-11-01 17:41:01 -07003744 uint32_t flags = 0;
3745
Garfield Tan8a3083e2018-12-03 13:21:07 -08003746 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003747 bool geometryAppliesWithResize =
3748 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003749
3750 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3751 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003752 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003753 layer->pushPendingState();
3754 }
3755
chaviw8b3871a2017-11-01 17:41:01 -07003756 if (what & layer_state_t::ePositionChanged) {
3757 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3758 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 }
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 if (what & layer_state_t::eLayerChanged) {
3762 // NOTE: index needs to be calculated before we update the state
3763 const auto& p = layer->getParent();
3764 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003765 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003767 mCurrentState.layersSortedByZ.removeAt(idx);
3768 mCurrentState.layersSortedByZ.add(layer);
3769 // we need traversal (state changed)
3770 // AND transaction (list changed)
3771 flags |= eTransactionNeeded|eTraversalNeeded;
3772 }
chaviw8b3871a2017-11-01 17:41:01 -07003773 } else {
3774 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003775 flags |= eTransactionNeeded|eTraversalNeeded;
3776 }
3777 }
chaviw8b3871a2017-11-01 17:41:01 -07003778 }
3779 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003780 // NOTE: index needs to be calculated before we update the state
3781 const auto& p = layer->getParent();
3782 if (p == nullptr) {
3783 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3784 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3785 mCurrentState.layersSortedByZ.removeAt(idx);
3786 mCurrentState.layersSortedByZ.add(layer);
3787 // we need traversal (state changed)
3788 // AND transaction (list changed)
3789 flags |= eTransactionNeeded|eTraversalNeeded;
3790 }
3791 } else {
3792 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3793 flags |= eTransactionNeeded|eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 }
3796 }
3797 if (what & layer_state_t::eSizeChanged) {
3798 if (layer->setSize(s.w, s.h)) {
3799 flags |= eTraversalNeeded;
3800 }
3801 }
3802 if (what & layer_state_t::eAlphaChanged) {
3803 if (layer->setAlpha(s.alpha))
3804 flags |= eTraversalNeeded;
3805 }
3806 if (what & layer_state_t::eColorChanged) {
3807 if (layer->setColor(s.color))
3808 flags |= eTraversalNeeded;
3809 }
Valerie Haued54efa2019-01-11 20:03:14 -08003810 if (what & layer_state_t::eColorAlphaChanged) {
3811 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3812 }
3813 if (what & layer_state_t::eColorDataspaceChanged) {
3814 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3815 }
Peiyong Lind3788632018-09-18 16:01:31 -07003816 if (what & layer_state_t::eColorTransformChanged) {
3817 if (layer->setColorTransform(s.colorTransform)) {
3818 flags |= eTraversalNeeded;
3819 }
3820 }
chaviw8b3871a2017-11-01 17:41:01 -07003821 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003822 // TODO: b/109894387
3823 //
3824 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3825 // rotation. To see the problem observe that if we have a square parent, and a child
3826 // of the same size, then we rotate the child 45 degrees around it's center, the child
3827 // must now be cropped to a non rectangular 8 sided region.
3828 //
3829 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3830 // private API, and the WindowManager only uses rotation in one case, which is on a top
3831 // level layer in which cropping is not an issue.
3832 //
3833 // However given that abuse of rotation matrices could lead to surfaces extending outside
3834 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3835 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3836 // transformations.
3837 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003838 flags |= eTraversalNeeded;
3839 }
3840 if (what & layer_state_t::eTransparentRegionChanged) {
3841 if (layer->setTransparentRegionHint(s.transparentRegion))
3842 flags |= eTraversalNeeded;
3843 }
3844 if (what & layer_state_t::eFlagsChanged) {
3845 if (layer->setFlags(s.flags, s.mask))
3846 flags |= eTraversalNeeded;
3847 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003848 if (what & layer_state_t::eCropChanged_legacy) {
3849 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003850 flags |= eTraversalNeeded;
3851 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003852 if (what & layer_state_t::eCornerRadiusChanged) {
3853 if (layer->setCornerRadius(s.cornerRadius))
3854 flags |= eTraversalNeeded;
3855 }
chaviw8b3871a2017-11-01 17:41:01 -07003856 if (what & layer_state_t::eLayerStackChanged) {
3857 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3858 // We only allow setting layer stacks for top level layers,
3859 // everything else inherits layer stack from its parent.
3860 if (layer->hasParent()) {
3861 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3862 layer->getName().string());
3863 } else if (idx < 0) {
3864 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3865 "that also does not appear in the top level layer list. Something"
3866 " has gone wrong.", layer->getName().string());
3867 } else if (layer->setLayerStack(s.layerStack)) {
3868 mCurrentState.layersSortedByZ.removeAt(idx);
3869 mCurrentState.layersSortedByZ.add(layer);
3870 // we need traversal (state changed)
3871 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003872 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003873 }
3874 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003875 if (what & layer_state_t::eDeferTransaction_legacy) {
3876 if (s.barrierHandle_legacy != nullptr) {
3877 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3878 } else if (s.barrierGbp_legacy != nullptr) {
3879 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003880 if (authenticateSurfaceTextureLocked(gbp)) {
3881 const auto& otherLayer =
3882 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003883 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003884 } else {
3885 ALOGE("Attempt to defer transaction to to an"
3886 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003887 }
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 // We don't trigger a traversal here because if no other state is
3890 // changed, we don't want this to cause any more work
3891 }
3892 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003893 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003895 if (!hadParent) {
3896 mCurrentState.layersSortedByZ.remove(layer);
3897 }
chaviw8b3871a2017-11-01 17:41:01 -07003898 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 }
3901 if (what & layer_state_t::eReparentChildren) {
3902 if (layer->reparentChildren(s.reparentHandle)) {
3903 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003904 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003905 }
chaviw8b3871a2017-11-01 17:41:01 -07003906 if (what & layer_state_t::eDetachChildren) {
3907 layer->detachChildren();
3908 }
3909 if (what & layer_state_t::eOverrideScalingModeChanged) {
3910 layer->setOverrideScalingMode(s.overrideScalingMode);
3911 // We don't trigger a traversal here because if no other state is
3912 // changed, we don't want this to cause any more work
3913 }
Marissa Wall61c58622018-07-18 10:12:20 -07003914 if (what & layer_state_t::eTransformChanged) {
3915 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3916 }
3917 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3918 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3919 flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eCropChanged) {
3922 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3923 }
Marissa Wall861616d2018-10-22 12:52:23 -07003924 if (what & layer_state_t::eFrameChanged) {
3925 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3926 }
Marissa Wall61c58622018-07-18 10:12:20 -07003927 if (what & layer_state_t::eBufferChanged) {
3928 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eAcquireFenceChanged) {
3931 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eDataspaceChanged) {
3934 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3935 }
3936 if (what & layer_state_t::eHdrMetadataChanged) {
3937 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3940 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eApiChanged) {
3943 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eSidebandStreamChanged) {
3946 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3947 }
Robert Carr720e5062018-07-30 17:45:14 -07003948 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003949 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3950 layer->setInputInfo(s.inputInfo);
3951 flags |= eTraversalNeeded;
3952 } else {
3953 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3954 }
Robert Carr720e5062018-07-30 17:45:14 -07003955 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003956 if (what & layer_state_t::eMetadataChanged) {
3957 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3958 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003959 std::vector<sp<CallbackHandle>> callbackHandles;
3960 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3961 mTransactionCompletedThread.run();
3962 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3963 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3964 }
3965 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003966 if (what & layer_state_t::eCachedBufferChanged) {
3967 sp<GraphicBuffer> buffer =
3968 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3969 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3970 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003971 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3972 // Do not put anything that updates layer state or modifies flags after
3973 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003974 return flags;
3975}
3976
chaviw273171b2018-12-26 11:46:30 -08003977uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3978 uint32_t flags = 0;
3979 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3980 flags |= eTraversalNeeded;
3981 }
3982
3983 mInputWindowCommands.merge(inputWindowCommands);
3984 return flags;
3985}
3986
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003987status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3988 uint32_t h, PixelFormat format, uint32_t flags,
3989 LayerMetadata metadata, sp<IBinder>* handle,
3990 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003991 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003992 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003993 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003994 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003995 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003996
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003997 status_t result = NO_ERROR;
3998
3999 sp<Layer> layer;
4000
Cody Northropbc755282017-03-31 12:00:08 -06004001 String8 uniqueName = getUniqueLayerName(name);
4002
Mathias Agopian3165cc22012-08-08 19:42:09 -07004003 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004004 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004005 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4006 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004007
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004009 case ISurfaceComposerClient::eFXSurfaceBufferState:
4010 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4011 break;
chaviw13fdc492017-06-27 12:40:18 -07004012 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004013 // check if buffer size is set for color layer.
4014 if (w > 0 || h > 0) {
4015 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4016 int(w), int(h));
4017 return BAD_VALUE;
4018 }
4019
chaviw13fdc492017-06-27 12:40:18 -07004020 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004021 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004022 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004023 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004024 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004025 // check if buffer size is set for container layer.
4026 if (w > 0 || h > 0) {
4027 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4028 int(w), int(h));
4029 return BAD_VALUE;
4030 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004031 result = createContainerLayer(client,
4032 uniqueName, w, h, flags,
4033 handle, &layer);
4034 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 default:
4036 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 break;
4038 }
4039
Dan Stoza7d89d062015-04-30 13:29:25 -07004040 if (result != NO_ERROR) {
4041 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004043
Chia-I Wuab0c3192017-08-01 11:29:00 -07004044 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4045 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004046 if (metadata.has(METADATA_WINDOW_TYPE)) {
4047 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4048 if (windowType == 441731) {
4049 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4050 layer->setPrimaryDisplayOnly();
4051 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004052 }
4053
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004054 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004055
Robert Carrb89ea9d2018-12-10 13:01:14 -08004056 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4057 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4058 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004059 if (result != NO_ERROR) {
4060 return result;
4061 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004062 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004063
4064 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004065 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066}
4067
Cody Northropbc755282017-03-31 12:00:08 -06004068String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4069{
4070 bool matchFound = true;
4071 uint32_t dupeCounter = 0;
4072
4073 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4074 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4075
Dan Stoza436ccf32018-06-21 12:10:12 -07004076 // Grab the state lock since we're accessing mCurrentState
4077 Mutex::Autolock lock(mStateLock);
4078
Cody Northropbc755282017-03-31 12:00:08 -06004079 // Loop over layers until we're sure there is no matching name
4080 while (matchFound) {
4081 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004082 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004083 if (layer->getName() == uniqueName) {
4084 matchFound = true;
4085 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4086 }
4087 });
4088 }
4089
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004090 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4091 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004092
4093 return uniqueName;
4094}
4095
Marissa Wallfd668622018-05-10 10:21:13 -07004096status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4097 uint32_t w, uint32_t h, uint32_t flags,
4098 PixelFormat& format, sp<IBinder>* handle,
4099 sp<IGraphicBufferProducer>* gbp,
4100 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004101 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004102 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103 case PIXEL_FORMAT_TRANSPARENT:
4104 case PIXEL_FORMAT_TRANSLUCENT:
4105 format = PIXEL_FORMAT_RGBA_8888;
4106 break;
4107 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004108 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 break;
4110 }
4111
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004112 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004113 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004114 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004115 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004116 *handle = layer->getHandle();
4117 *gbp = layer->getProducer();
4118 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004120
Marissa Wallfd668622018-05-10 10:21:13 -07004121 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004122 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123}
4124
Marissa Wall61c58622018-07-18 10:12:20 -07004125status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4126 uint32_t w, uint32_t h, uint32_t flags,
4127 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004128 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004129 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004130 *handle = layer->getHandle();
4131 *outLayer = layer;
4132
4133 return NO_ERROR;
4134}
4135
chaviw13fdc492017-06-27 12:40:18 -07004136status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004137 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004138 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004140 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004141 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004142 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004143}
4144
Robert Carr6b3f6c52018-08-13 13:05:17 -07004145status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4147 sp<IBinder>* handle, sp<Layer>* outLayer)
4148{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004149 *outLayer =
4150 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004151 *handle = (*outLayer)->getHandle();
4152 return NO_ERROR;
4153}
4154
4155
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004156void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004157 mLayersPendingRemoval.add(layer);
4158 mLayersRemoved = true;
4159 setTransactionFlags(eTransactionNeeded);
4160}
4161
Robert Carr695d5282018-12-18 15:27:58 -08004162void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004163{
Robert Carr2e102c92018-10-23 12:11:15 -07004164 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004165 // If a layer has a parent, we allow it to out-live it's handle
4166 // with the idea that the parent holds a reference and will eventually
4167 // be cleaned up. However no one cleans up the top-level so we do so
4168 // here.
4169 if (layer->getParent() == nullptr) {
4170 mCurrentState.layersSortedByZ.remove(layer);
4171 }
4172 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004173 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004174}
4175
Mathias Agopianb60314a2012-04-10 22:09:54 -07004176// ---------------------------------------------------------------------------
4177
Andy McFadden13a082e2012-08-24 10:16:42 -07004178void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004179 const auto display = getDefaultDisplayDeviceLocked();
4180 if (!display) return;
4181
4182 const sp<IBinder> token = display->getDisplayToken().promote();
4183 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004184
Jesse Hall01e29052013-02-19 16:13:35 -08004185 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004186 Vector<ComposerState> state;
4187 Vector<DisplayState> displays;
4188 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004189 d.what = DisplayState::eDisplayProjectionChanged |
4190 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004191 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004192 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004193 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004194 d.frame.makeInvalid();
4195 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004196 d.width = 0;
4197 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004198 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004199 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004200
Dominik Laskowskie9774092018-12-11 10:04:24 -08004201 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004202
Dominik Laskowski83b88212018-12-11 13:34:06 -08004203 const nsecs_t vsyncPeriod = getVsyncPeriod();
4204 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004205
Brian Andersond0010582017-03-07 13:20:31 -08004206 // Use phase of 0 since phase is not known.
4207 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004208 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004209 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004210}
4211
4212void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004213 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 postMessageAsync(
4215 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004216}
4217
Dominik Laskowskie9774092018-12-11 10:04:24 -08004218void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004219 if (display->isVirtual()) {
4220 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004221 return;
4222 }
4223
Dominik Laskowski075d3172018-05-24 15:50:06 -07004224 const auto displayId = display->getId();
4225 LOG_ALWAYS_FATAL_IF(!displayId);
4226
Dominik Laskowski34157762018-10-31 13:07:19 -07004227 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004228
4229 int currentMode = display->getPowerMode();
4230 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004231 return;
4232 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004233
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004234 display->setPowerMode(mode);
4235
Lloyd Pique4dccc412018-01-22 17:21:36 -08004236 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004237 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004238 }
4239
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004240 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004241 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004242 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004244 if (mUseScheduler) {
4245 mScheduler->onScreenAcquired(mAppConnectionHandle);
4246 } else {
4247 mEventThread->onScreenAcquired();
4248 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004250 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004252 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004253 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004254 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004255
4256 struct sched_param param = {0};
4257 param.sched_priority = 1;
4258 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4259 ALOGW("Couldn't set SCHED_FIFO on display on");
4260 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004262 // Turn off the display
4263 struct sched_param param = {0};
4264 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4265 ALOGW("Couldn't set SCHED_OTHER on display off");
4266 }
4267
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004268 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004269 if (mUseScheduler) {
4270 mScheduler->disableHardwareVsync(true);
4271 } else {
4272 disableHardwareVsync(true); // also cancels any in-progress resync
4273 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004274 if (mUseScheduler) {
4275 mScheduler->onScreenReleased(mAppConnectionHandle);
4276 } else {
4277 mEventThread->onScreenReleased();
4278 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004279 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280
Dominik Laskowski075d3172018-05-24 15:50:06 -07004281 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004282 mVisibleRegionsDirty = true;
4283 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004284 } else if (mode == HWC_POWER_MODE_DOZE ||
4285 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004286 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004287 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004289 if (mUseScheduler) {
4290 mScheduler->onScreenAcquired(mAppConnectionHandle);
4291 } else {
4292 mEventThread->onScreenAcquired();
4293 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004294 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004295 }
4296 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4297 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004299 if (mUseScheduler) {
4300 mScheduler->disableHardwareVsync(true);
4301 } else {
4302 disableHardwareVsync(true); // also cancels any in-progress resync
4303 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004304 if (mUseScheduler) {
4305 mScheduler->onScreenReleased(mAppConnectionHandle);
4306 } else {
4307 mEventThread->onScreenReleased();
4308 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004309 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004311 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004312 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004313 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004316 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004317 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004318 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004319 // Update refresh rate stats.
4320 mRefreshRateStats->setPowerMode(mode);
4321 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004322 }
4323
Dominik Laskowski34157762018-10-31 13:07:19 -07004324 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325}
4326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004328 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 const auto display = getDisplayDevice(displayToken);
4330 if (!display) {
4331 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4332 displayToken.get());
4333 } else if (display->isVirtual()) {
4334 ALOGW("Attempt to set power mode %d for virtual display", mode);
4335 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004336 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004337 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004339}
4340
4341// ---------------------------------------------------------------------------
4342
Dominik Laskowskic2867142019-01-21 11:33:38 -08004343status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4344 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004346
Mathias Agopianbd115332013-04-18 16:41:04 -07004347 IPCThreadState* ipc = IPCThreadState::self();
4348 const int pid = ipc->getCallingPid();
4349 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004350
Mathias Agopianbd115332013-04-18 16:41:04 -07004351 if ((uid != AID_SHELL) &&
4352 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4354 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004355 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004356 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004357 // (this would indicate SF is stuck, but we want to be able to
4358 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004359 status_t err = mStateLock.timedLock(s2ns(1));
4360 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004361 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 StringAppendF(&result,
4363 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4364 "(no locks held)\n",
4365 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 }
4367
Dominik Laskowskic2867142019-01-21 11:33:38 -08004368 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004369
Dominik Laskowskic2867142019-01-21 11:33:38 -08004370 static const std::unordered_map<std::string, Dumper> dumpers = {
4371 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4372 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4373 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4374 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4375 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4376 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4377 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4378 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4379 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4380 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4381 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4382 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4383 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004384 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004385 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4386 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004387
Dominik Laskowskic2867142019-01-21 11:33:38 -08004388 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004389
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4391 (it->second)(args, asProto, result);
4392 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004393 if (asProto) {
4394 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4395 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4396 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004398 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004399 }
4400
Mathias Agopian9795c422009-08-26 16:36:26 -07004401 if (locked) {
4402 mStateLock.unlock();
4403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004404 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004406 return NO_ERROR;
4407}
4408
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410 mCurrentState.traverseInZOrder(
4411 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004412}
4413
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004415 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417 if (args.size() > 1) {
4418 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004419 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004420 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004421 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004422 }
Robert Carr2047fae2016-11-28 14:09:09 -08004423 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004424 } else {
4425 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426 }
4427}
4428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004430 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004431 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004432 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004433 }
Robert Carr2047fae2016-11-28 14:09:09 -08004434 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004435
Svetoslavd85084b2014-03-20 10:28:31 -07004436 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004437}
4438
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4440 mTimeStats->parseArgs(asProto, args, result);
4441}
4442
Jamie Gennis6547ff42013-07-16 20:12:42 -07004443// This should only be called from the main thread. Otherwise it would need
4444// the lock and should use mCurrentState rather than mDrawingState.
4445void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004446 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004447 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004448 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004449
4450 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4451}
4452
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004454 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004455
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004456 if (isLayerTripleBufferingDisabled())
4457 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4460 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4461 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4462 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4463 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4464 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004465 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004466}
4467
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004468void SurfaceFlinger::dumpVSync(std::string& result) const {
4469 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4470 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4471 StringAppendF(&result,
4472 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4473 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4474 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4475 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4476 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4477 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4478
4479 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4480
4481 if (mUseScheduler) {
4482 mScheduler->dump(mAppConnectionHandle, result);
4483 } else {
4484 mEventThread->dump(result);
4485 }
4486}
4487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4489 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004490 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4491 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004492 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004493 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004495 }
David Sodman4a36e932017-11-07 14:29:47 -08004496 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004497 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004498 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4500 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004501}
4502
Dan Stozae77c7662016-05-13 11:37:28 -07004503void SurfaceFlinger::recordBufferingStats(const char* layerName,
4504 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004505 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4506 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004507 for (const auto& segment : history) {
4508 if (!segment.usedThirdBuffer) {
4509 stats.twoBufferTime += segment.totalTime;
4510 }
4511 if (segment.occupancyAverage < 1.0f) {
4512 stats.doubleBufferedTime += segment.totalTime;
4513 } else if (segment.occupancyAverage < 2.0f) {
4514 stats.tripleBufferedTime += segment.totalTime;
4515 }
4516 ++stats.numSegments;
4517 stats.totalTime += segment.totalTime;
4518 }
4519}
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4522 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004523
4524 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4525 const size_t count = currentLayers.size();
4526 for (size_t i=0 ; i<count ; i++) {
4527 currentLayers[i]->dumpFrameEvents(result);
4528 }
4529}
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004532 result.append("Buffering stats:\n");
4533 result.append(" [Layer name] <Active time> <Two buffer> "
4534 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004535 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004536 typedef std::tuple<std::string, float, float, float> BufferTuple;
4537 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004538 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004539 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004540 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004541 if (stats.numSegments == 0) {
4542 continue;
4543 }
4544 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4545 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4546 stats.totalTime;
4547 float doubleBufferRatio = static_cast<float>(
4548 stats.doubleBufferedTime) / stats.totalTime;
4549 float tripleBufferRatio = static_cast<float>(
4550 stats.tripleBufferedTime) / stats.totalTime;
4551 sorted.insert({activeTime, {name, twoBufferRatio,
4552 doubleBufferRatio, tripleBufferRatio}});
4553 }
4554 for (const auto& sortedPair : sorted) {
4555 float activeTime = sortedPair.first;
4556 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4558 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004559 }
4560 result.append("\n");
4561}
4562
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004564 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004565 const auto displayId = display->getId();
4566 if (!displayId) {
4567 continue;
4568 }
4569 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004570 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004571 continue;
4572 }
4573
Yiwei Zhang5434a782018-12-05 18:06:32 -08004574 StringAppendF(&result,
4575 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4576 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004577 uint8_t port;
4578 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004579 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 result.append("no identification data\n");
4581 continue;
4582 }
4583
4584 if (!isEdid(data)) {
4585 result.append("unknown identification data: ");
4586 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004588 }
4589 result.append("\n");
4590 continue;
4591 }
4592
4593 const auto edid = parseEdid(data);
4594 if (!edid) {
4595 result.append("invalid EDID: ");
4596 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598 }
4599 result.append("\n");
4600 continue;
4601 }
4602
Yiwei Zhang5434a782018-12-05 18:06:32 -08004603 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 result.append(edid->displayName.data(), edid->displayName.length());
4605 result.append("\"\n");
4606 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004607}
4608
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4610 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4611 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4612 StringAppendF(&result, "DisplayColorSetting: %s\n",
4613 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004614
4615 // TODO: print out if wide-color mode is active or not
4616
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004617 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004618 const auto displayId = display->getId();
4619 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004620 continue;
4621 }
4622
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004624 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004627 }
4628
Lloyd Pique32cbe282018-10-19 13:09:22 -07004629 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, " Current color mode: %s (%d)\n",
4631 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004632 }
4633 result.append("\n");
4634}
4635
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004638 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4639 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004640 continue;
4641 }
4642
Dominik Laskowski05275f12018-11-01 15:03:24 -07004643 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4645 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004646 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 compositionInfo.dump(result, nullptr);
4648 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004649 }
4650 }
David Sodman7e4ae112018-02-09 15:02:28 -08004651}
4652
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004653LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004654 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004655 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4656 const State& state = useDrawing ? mDrawingState : mCurrentState;
4657 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004658 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004659 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004660 });
4661
4662 return layersProto;
4663}
4664
Lloyd Pique32cbe282018-10-19 13:09:22 -07004665LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004666 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004667
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004668 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004669 resolution->set_w(displayDevice.getWidth());
4670 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004671
Lloyd Pique32cbe282018-10-19 13:09:22 -07004672 auto display = displayDevice.getCompositionDisplay();
4673 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004674
Lloyd Pique32cbe282018-10-19 13:09:22 -07004675 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4676 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4677 layersProto.set_global_transform(displayState.orientation);
4678
4679 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004680 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004682 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004683 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004684 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004685 }
4686 });
4687
4688 return layersProto;
4689}
4690
Dominik Laskowskic2867142019-01-21 11:33:38 -08004691void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4692 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004693 Colorizer colorizer(colorize);
4694
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695 // figure out if we're stuck somewhere
4696 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004698 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4699
4700 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004701 * Dump library configuration.
4702 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703
4704 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004705 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004706 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004707 appendSfConfigString(result);
4708 appendUiConfigString(result);
4709 appendGuiConfigString(result);
4710 result.append("\n");
4711
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004712 result.append("\nDisplay identification data:\n");
4713 dumpDisplayIdentificationData(result);
4714
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004715 result.append("\nWide-Color information:\n");
4716 dumpWideColorInfo(result);
4717
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004718 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004719 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004721 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004722 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004723
Andy McFadden41d67d72014-04-25 16:58:34 -07004724 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004725 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004726 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004727 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004728 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004729
Dan Stozab90cf072015-03-05 11:05:59 -08004730 dumpStaticScreenStats(result);
4731 result.append("\n");
4732
Yiwei Zhang5434a782018-12-05 18:06:32 -08004733 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004734
Dan Stozae77c7662016-05-13 11:37:28 -07004735 dumpBufferingStats(result);
4736
Andy McFadden4803b742012-09-24 19:07:20 -07004737 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004738 * Dump the visible layer list
4739 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004740 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4742 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4743 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004744 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004745
Chia-I Wu2f884132018-09-13 15:17:58 -07004746 {
4747 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4748 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004750 result.append("\n");
4751 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752
David Sodman7e4ae112018-02-09 15:02:28 -08004753 result.append("\nFrame-Composition information:\n");
4754 dumpFrameCompositionInfo(result);
4755 result.append("\n");
4756
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004758 * Dump Display state
4759 */
4760
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004761 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004764 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004765 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004766 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004767 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004768
4769 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770 * Dump SurfaceFlinger global state
4771 */
4772
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004774 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004777 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Dominik Laskowski075d3172018-05-24 15:50:06 -07004779 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004780 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4781 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4783 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004784 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result,
4786 " transaction-flags : %08x\n"
4787 " gpu_to_cpu_unsupported : %d\n",
4788 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004789
Dominik Laskowski075d3172018-05-24 15:50:06 -07004790 if (const auto displayId = getInternalDisplayId();
4791 displayId && getHwComposer().isConnected(*displayId)) {
4792 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 StringAppendF(&result,
4794 " refresh-rate : %f fps\n"
4795 " x-dpi : %f\n"
4796 " y-dpi : %f\n",
4797 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4798 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004799 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004800
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802
Dan Stozae22aec72016-08-01 13:20:59 -07004803 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004804 * Tracing state
4805 */
4806 mTracing.dump(result);
4807 result.append("\n");
4808
4809 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004810 * HWC layer minidump
4811 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004812 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004813 const auto displayId = display->getId();
4814 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004815 continue;
4816 }
4817
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004819 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004820 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004821 result.append("\n");
4822 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004823
4824 /*
4825 * Dump HWComposer state
4826 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004827 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004828 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004829 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004830 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004832 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004833
4834 /*
4835 * Dump gralloc state
4836 */
4837 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4838 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004839
4840 /*
4841 * Dump VrFlinger state if in use.
4842 */
4843 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4844 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004845 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004846 result.append("\n");
4847 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004848
4849 /**
4850 * Scheduler dump state.
4851 */
4852 if (mUseScheduler) {
4853 result.append("\nScheduler state:\n");
4854 result.append(mScheduler->doDump() + "\n");
4855 result.append(mRefreshRateStats->doDump() + "\n");
4856 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004857}
4858
Dominik Laskowski075d3172018-05-24 15:50:06 -07004859const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004860 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004861 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004862 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004863 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004864 }
4865 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004866
Dominik Laskowski34157762018-10-31 13:07:19 -07004867 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004868 static const Vector<sp<Layer>> empty;
4869 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004870}
4871
Keun young Park63f165f2012-08-31 10:53:36 -07004872bool SurfaceFlinger::startDdmConnection()
4873{
4874 void* libddmconnection_dso =
4875 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4876 if (!libddmconnection_dso) {
4877 return false;
4878 }
4879 void (*DdmConnection_start)(const char* name);
4880 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004881 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004882 if (!DdmConnection_start) {
4883 dlclose(libddmconnection_dso);
4884 return false;
4885 }
4886 (*DdmConnection_start)(getServiceName());
4887 return true;
4888}
4889
Chia-I Wu28f320b2018-05-03 11:02:56 -07004890void SurfaceFlinger::updateColorMatrixLocked() {
4891 mat4 colorMatrix;
4892 if (mGlobalSaturationFactor != 1.0f) {
4893 // Rec.709 luma coefficients
4894 float3 luminance{0.213f, 0.715f, 0.072f};
4895 luminance *= 1.0f - mGlobalSaturationFactor;
4896 mat4 saturationMatrix = mat4(
4897 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4898 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4899 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4900 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4901 );
4902 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4903 } else {
4904 colorMatrix = mClientColorMatrix * mDaltonizer();
4905 }
4906
4907 if (mCurrentState.colorMatrix != colorMatrix) {
4908 mCurrentState.colorMatrix = colorMatrix;
4909 mCurrentState.colorMatrixChanged = true;
4910 setTransactionFlags(eTransactionNeeded);
4911 }
4912}
4913
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004914status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915#pragma clang diagnostic push
4916#pragma clang diagnostic error "-Wswitch-enum"
4917 switch (static_cast<ISurfaceComposerTag>(code)) {
4918 // These methods should at minimum make sure that the client requested
4919 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004920 case BOOT_FINISHED:
4921 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 case CREATE_DISPLAY:
4923 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004924 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 case GET_ACTIVE_COLOR_MODE:
4926 case GET_ANIMATION_FRAME_STATS:
4927 case GET_HDR_CAPABILITIES:
4928 case SET_ACTIVE_CONFIG:
4929 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004930 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004931 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004932 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004933 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4934 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004935 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4936 IPCThreadState* ipc = IPCThreadState::self();
4937 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4938 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004939 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004940 }
Robert Carr1db73f62016-12-21 12:58:51 -08004941 return OK;
4942 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004943 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004944 IPCThreadState* ipc = IPCThreadState::self();
4945 const int pid = ipc->getCallingPid();
4946 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4948 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004949 return PERMISSION_DENIED;
4950 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004953 // Used by apps to hook Choreographer to SurfaceFlinger.
4954 case CREATE_DISPLAY_EVENT_CONNECTION:
4955 // The following calls are currently used by clients that do not
4956 // request necessary permissions. However, they do not expose any secret
4957 // information, so it is OK to pass them.
4958 case AUTHENTICATE_SURFACE:
4959 case GET_ACTIVE_CONFIG:
4960 case GET_BUILT_IN_DISPLAY:
4961 case GET_DISPLAY_COLOR_MODES:
4962 case GET_DISPLAY_CONFIGS:
4963 case GET_DISPLAY_STATS:
4964 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4965 // Calling setTransactionState is safe, because you need to have been
4966 // granted a reference to Client* and Handle* to do anything with it.
4967 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004968 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004969 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004970 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004971 case GET_PROTECTED_CONTENT_SUPPORT:
4972 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08004973 case UNCACHE_BUFFER:
4974 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004975 return OK;
4976 }
4977 case CAPTURE_LAYERS:
4978 case CAPTURE_SCREEN: {
4979 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004980 IPCThreadState* ipc = IPCThreadState::self();
4981 const int pid = ipc->getCallingPid();
4982 const int uid = ipc->getCallingUid();
4983 if ((uid != AID_GRAPHICS) &&
4984 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4985 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4986 return PERMISSION_DENIED;
4987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 return OK;
4989 }
4990 // The following codes are deprecated and should never be allowed to access SF.
4991 case CONNECT_DISPLAY_UNUSED:
4992 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4993 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4994 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004995 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004996 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997
4998 // These codes are used for the IBinder protocol to either interrogate the recipient
4999 // side of the transaction for its canonical interface descriptor or to dump its state.
5000 // We let them pass by default.
5001 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5002 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5003 code == IBinder::SYSPROPS_TRANSACTION) {
5004 return OK;
5005 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005006 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005008 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005009 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5010 return OK;
5011 }
5012 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5013 return PERMISSION_DENIED;
5014#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005015}
5016
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5018 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005019 status_t credentialCheck = CheckTransactCodeCredentials(code);
5020 if (credentialCheck != OK) {
5021 return credentialCheck;
5022 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5025 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005026 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005027 IPCThreadState* ipc = IPCThreadState::self();
5028 const int uid = ipc->getCallingUid();
5029 if (CC_UNLIKELY(uid != AID_SYSTEM
5030 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005031 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005032 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005033 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005034 return PERMISSION_DENIED;
5035 }
5036 int n;
5037 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005038 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005039 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 return NO_ERROR;
5041 case 1002: // SHOW_UPDATES
5042 n = data.readInt32();
5043 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005044 invalidateHwcGeometry();
5045 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005048 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005049 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005051 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005052 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005053 setTransactionFlags(
5054 eTransactionNeeded|
5055 eDisplayTransactionNeeded|
5056 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005057 return NO_ERROR;
5058 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005059 case 1006:{ // send empty update
5060 signalRefresh();
5061 return NO_ERROR;
5062 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005063 case 1008: // toggle use of hw composer
5064 n = data.readInt32();
5065 mDebugDisableHWC = n ? 1 : 0;
5066 invalidateHwcGeometry();
5067 repaintEverything();
5068 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005069 case 1009: // toggle use of transform hint
5070 n = data.readInt32();
5071 mDebugDisableTransformHint = n ? 1 : 0;
5072 invalidateHwcGeometry();
5073 repaintEverything();
5074 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005076 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005077 reply->writeInt32(0);
5078 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005079 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005080 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005081 return NO_ERROR;
5082 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005083 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005084 if (!display) {
5085 return NAME_NOT_FOUND;
5086 }
5087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005088 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005089 return NO_ERROR;
5090 }
5091 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005092 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005093 // daltonize
5094 n = data.readInt32();
5095 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 case 1:
5097 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5098 break;
5099 case 2:
5100 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5101 break;
5102 case 3:
5103 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5104 break;
5105 default:
5106 mDaltonizer.setType(ColorBlindnessType::None);
5107 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005108 }
5109 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005110 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005111 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005112 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005113 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114
5115 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005116 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005118 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005119 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005120 // apply a color matrix
5121 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005122 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005123 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005124 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005125 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005126 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005127 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005128 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005129 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005131 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005132
5133 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5134 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005135 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005136 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5137 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5138 }
5139
Chia-I Wu28f320b2018-05-03 11:02:56 -07005140 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005141 return NO_ERROR;
5142 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005143 // This is an experimental interface
5144 // Needs to be shifted to proper binder interface when we productize
5145 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005146 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005147 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005148 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005149 return NO_ERROR;
5150 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005151 case 1017: {
5152 n = data.readInt32();
5153 mForceFullDamage = static_cast<bool>(n);
5154 return NO_ERROR;
5155 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005156 case 1018: { // Modify Choreographer's phase offset
5157 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005158 if (mUseScheduler) {
5159 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5160 } else {
5161 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5162 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005163 return NO_ERROR;
5164 }
5165 case 1019: { // Modify SurfaceFlinger's phase offset
5166 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005167 if (mUseScheduler) {
5168 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5169 } else {
5170 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5171 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005172 return NO_ERROR;
5173 }
Irvel468051e2016-06-13 16:44:44 -07005174 case 1020: { // Layer updates interceptor
5175 n = data.readInt32();
5176 if (n) {
5177 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005178 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005179 }
5180 else{
5181 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005182 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005183 }
5184 return NO_ERROR;
5185 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005186 case 1021: { // Disable HWC virtual displays
5187 n = data.readInt32();
5188 mUseHwcVirtualDisplays = !n;
5189 return NO_ERROR;
5190 }
Romain Guy0147a172017-06-01 13:53:56 -07005191 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005192 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005193 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005194
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005196 return NO_ERROR;
5197 }
Romain Guy54f154a2017-10-24 21:40:32 +01005198 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005199 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005200 invalidateHwcGeometry();
5201 repaintEverything();
5202 return NO_ERROR;
5203 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005204 // Deprecate, use 1030 to check whether the device is color managed.
5205 case 1024: {
5206 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005207 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005208 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005209 n = data.readInt32();
5210 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005211 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005212 mTracing.enable();
5213 doTracing("tracing.enable");
5214 reply->writeInt32(NO_ERROR);
5215 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005216 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005217 status_t err = mTracing.disable();
5218 reply->writeInt32(err);
5219 }
5220 return NO_ERROR;
5221 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005222 case 1026: { // Get layer tracing status
5223 reply->writeBool(mTracing.isEnabled());
5224 return NO_ERROR;
5225 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 // Is a DisplayColorSetting supported?
5227 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005228 const auto display = getDefaultDisplayDevice();
5229 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005230 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005231 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005232
5233 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5234 switch (setting) {
5235 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005236 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005237 break;
5238 case DisplayColorSetting::UNMANAGED:
5239 reply->writeBool(true);
5240 break;
5241 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005242 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005243 break;
5244 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005245 reply->writeBool(
5246 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005247 break;
5248 }
5249 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005250 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005251 // Is VrFlinger active?
5252 case 1028: {
5253 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005254 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005255 return NO_ERROR;
5256 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005257 // Is device color managed?
5258 case 1030: {
5259 reply->writeBool(useColorManagement);
5260 return NO_ERROR;
5261 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005262 // Override default composition data space
5263 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5264 // && adb shell stop zygote && adb shell start zygote
5265 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5266 // adb shell stop zygote && adb shell start zygote
5267 case 1031: {
5268 Mutex::Autolock _l(mStateLock);
5269 n = data.readInt32();
5270 if (n) {
5271 n = data.readInt32();
5272 if (n) {
5273 Dataspace dataspace = static_cast<Dataspace>(n);
5274 if (!validateCompositionDataspace(dataspace)) {
5275 return BAD_VALUE;
5276 }
5277 mDefaultCompositionDataspace = dataspace;
5278 }
5279 n = data.readInt32();
5280 if (n) {
5281 Dataspace dataspace = static_cast<Dataspace>(n);
5282 if (!validateCompositionDataspace(dataspace)) {
5283 return BAD_VALUE;
5284 }
5285 mWideColorGamutCompositionDataspace = dataspace;
5286 }
5287 } else {
5288 // restore composition data space.
5289 mDefaultCompositionDataspace = defaultCompositionDataspace;
5290 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5291 }
5292 return NO_ERROR;
5293 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005294 }
5295 }
5296 return err;
5297}
5298
Steven Thomas6d8110b2017-08-31 18:24:21 -07005299void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005300 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005301 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005302}
5303
Ana Krulec7d1d6832018-12-27 11:10:09 -08005304void SurfaceFlinger::repaintEverythingForHWC() {
5305 mRepaintEverything = true;
5306 mEventQueue->invalidateForHWC();
5307}
5308
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005309// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5310class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005311public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005312 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5313 ~WindowDisconnector() {
5314 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005315 }
5316
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005317private:
5318 ANativeWindow* mWindow;
5319 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005320};
5321
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005322status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005323 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5324 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005325 uint32_t reqWidth, uint32_t reqHeight,
5326 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005327 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005330 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005331
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005332 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5333
Chia-I Wu20261cb2018-08-23 12:55:44 -07005334 sp<DisplayDevice> display;
5335 {
5336 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005337
Chia-I Wu20261cb2018-08-23 12:55:44 -07005338 display = getDisplayDeviceLocked(displayToken);
5339 if (!display) return BAD_VALUE;
5340
Chia-I Wucb023152018-08-28 12:57:23 -07005341 // set the requested width/height to the logical display viewport size
5342 // by default
5343 if (reqWidth == 0 || reqHeight == 0) {
5344 reqWidth = uint32_t(display->getViewport().width());
5345 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005346 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005347 }
5348
Peiyong Lin0e003c92018-09-17 11:09:51 -07005349 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5350 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005351
5352 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005353 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005354 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5355 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005356}
5357
5358status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005359 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5360 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005361 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005362 ATRACE_CALL();
5363
5364 class LayerRenderArea : public RenderArea {
5365 public:
Robert Carr578038f2018-03-09 12:25:24 -08005366 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005367 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5368 bool childrenOnly)
5369 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005370 mLayer(layer),
5371 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005372 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005373 mFlinger(flinger),
5374 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005375 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005376 Rect getBounds() const override {
5377 const Layer::State& layerState(mLayer->getDrawingState());
5378 return mLayer->getBufferSize(layerState);
5379 }
Marissa Wall61c58622018-07-18 10:12:20 -07005380 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005381 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005382 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005383 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005384 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005385 }
chaviwa76b2712017-09-20 12:02:26 -07005386 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005387 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005388 Rect getSourceCrop() const override {
5389 if (mCrop.isEmpty()) {
5390 return getBounds();
5391 } else {
5392 return mCrop;
5393 }
5394 }
Robert Carr578038f2018-03-09 12:25:24 -08005395 class ReparentForDrawing {
5396 public:
5397 const sp<Layer>& oldParent;
5398 const sp<Layer>& newParent;
5399
5400 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5401 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005402 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005403 }
Robert Carr15eae092018-03-23 13:43:53 -07005404 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005405 };
5406
5407 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005408 const Rect sourceCrop = getSourceCrop();
5409 // no need to check rotation because there is none
5410 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5411 sourceCrop.height() != getReqHeight();
5412
Robert Carr578038f2018-03-09 12:25:24 -08005413 if (!mChildrenOnly) {
5414 mTransform = mLayer->getTransform().inverse();
5415 drawLayers();
5416 } else {
5417 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005418 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005419 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5420 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005421
5422 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5423 drawLayers();
5424 }
5425 }
chaviwa76b2712017-09-20 12:02:26 -07005426
chaviwa76b2712017-09-20 12:02:26 -07005427 private:
chaviw7206d492017-11-10 16:16:12 -08005428 const sp<Layer> mLayer;
5429 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005430
5431 // In the "childrenOnly" case we reparent the children to a screenshot
5432 // layer which has no properties set and which does not draw.
5433 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005434 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005435 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005436
5437 SurfaceFlinger* mFlinger;
5438 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005439 };
5440
5441 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5442 auto parent = layerHandle->owner.promote();
5443
Robert Carr2e102c92018-10-23 12:11:15 -07005444 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005445 ALOGE("captureLayers called with a removed parent");
5446 return NAME_NOT_FOUND;
5447 }
5448
Robert Carr578038f2018-03-09 12:25:24 -08005449 const int uid = IPCThreadState::self()->getCallingUid();
5450 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005451 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005452 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5453 return PERMISSION_DENIED;
5454 }
5455
chaviw7206d492017-11-10 16:16:12 -08005456 Rect crop(sourceCrop);
5457 if (sourceCrop.width() <= 0) {
5458 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005459 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005460 }
5461
5462 if (sourceCrop.height() <= 0) {
5463 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005464 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005465 }
5466
5467 int32_t reqWidth = crop.width() * frameScale;
5468 int32_t reqHeight = crop.height() * frameScale;
5469
Chia-I Wu20261cb2018-08-23 12:55:44 -07005470 // really small crop or frameScale
5471 if (reqWidth <= 0) {
5472 reqWidth = 1;
5473 }
5474 if (reqHeight <= 0) {
5475 reqHeight = 1;
5476 }
5477
Peiyong Lin0e003c92018-09-17 11:09:51 -07005478 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005479
Robert Carr578038f2018-03-09 12:25:24 -08005480 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005481 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5482 if (!layer->isVisible()) {
5483 return;
Robert Carr578038f2018-03-09 12:25:24 -08005484 } else if (childrenOnly && layer == parent.get()) {
5485 return;
chaviwa76b2712017-09-20 12:02:26 -07005486 }
5487 visitor(layer);
5488 });
5489 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005490 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005491}
5492
5493status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5494 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005495 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005496 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005497 bool useIdentityTransform) {
5498 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005499
Peiyong Lin0e003c92018-09-17 11:09:51 -07005500 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005501 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5502 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005503 *outBuffer =
5504 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5505 static_cast<android_pixel_format>(reqPixelFormat), 1,
5506 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507
5508 // This mutex protects syncFd and captureResult for communication of the return values from the
5509 // main thread back to this Binder thread
5510 std::mutex captureMutex;
5511 std::condition_variable captureCondition;
5512 std::unique_lock<std::mutex> captureLock(captureMutex);
5513 int syncFd = -1;
5514 std::optional<status_t> captureResult;
5515
Robert Carr03480e22018-01-04 16:02:06 -08005516 const int uid = IPCThreadState::self()->getCallingUid();
5517 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5518
Dominik Laskowski8c001672018-05-30 16:52:06 -07005519 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005520 // If there is a refresh pending, bug out early and tell the binder thread to try again
5521 // after the refresh.
5522 if (mRefreshPending) {
5523 ATRACE_NAME("Skipping screenshot for now");
5524 std::unique_lock<std::mutex> captureLock(captureMutex);
5525 captureResult = std::make_optional<status_t>(EAGAIN);
5526 captureCondition.notify_one();
5527 return;
5528 }
5529
5530 status_t result = NO_ERROR;
5531 int fd = -1;
5532 {
5533 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005534 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005535 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5536 useIdentityTransform, forSystem, &fd);
5537 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538 }
5539
5540 {
5541 std::unique_lock<std::mutex> captureLock(captureMutex);
5542 syncFd = fd;
5543 captureResult = std::make_optional<status_t>(result);
5544 captureCondition.notify_one();
5545 }
5546 });
5547
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005548 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005549 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005550 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005551 while (*captureResult == EAGAIN) {
5552 captureResult.reset();
5553 result = postMessageAsync(message);
5554 if (result != NO_ERROR) {
5555 return result;
5556 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005557 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005558 }
5559 result = *captureResult;
5560 }
5561
5562 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005563 sync_wait(syncFd, -1);
5564 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005566
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005568}
5569
chaviwa76b2712017-09-20 12:02:26 -07005570void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005571 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005572 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5573 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005574 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005575
chaviwa76b2712017-09-20 12:02:26 -07005576 const auto reqWidth = renderArea.getReqWidth();
5577 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005578 const auto sourceCrop = renderArea.getSourceCrop();
5579 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005580
Alec Mouri0f714832018-11-12 15:31:06 -08005581 renderengine::DisplaySettings clientCompositionDisplay;
5582 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005583
Alec Mouri0f714832018-11-12 15:31:06 -08005584 // assume that bounds are never offset, and that they are the same as the
5585 // buffer bounds.
5586 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5587 ui::Transform transform = renderArea.getTransform();
5588 mat4 m;
5589 m[0][0] = transform[0][0];
5590 m[0][1] = transform[0][1];
5591 m[0][3] = transform[0][2];
5592 m[1][0] = transform[1][0];
5593 m[1][1] = transform[1][1];
5594 m[1][3] = transform[1][2];
5595 m[3][0] = transform[2][0];
5596 m[3][1] = transform[2][1];
5597 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005598
Alec Mouri0f714832018-11-12 15:31:06 -08005599 clientCompositionDisplay.globalTransform = m;
5600 mat4 rotMatrix;
5601 // Displacement for repositioning the clipping rectangle after rotating it
5602 // with the rotation hint.
5603 int displacementX = 0;
5604 int displacementY = 0;
5605 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5606 switch (rotation) {
5607 case ui::Transform::ROT_90:
5608 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5609 displacementX = reqWidth;
5610 break;
5611 case ui::Transform::ROT_180:
5612 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5613 displacementX = reqWidth;
5614 displacementY = reqHeight;
5615 break;
5616 case ui::Transform::ROT_270:
5617 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5618 displacementY = reqHeight;
5619 break;
5620 default:
5621 break;
5622 }
5623 // We need to transform the clipping window into the right spot.
5624 // First, rotate the clipping rectangle by the rotation hint to get the
5625 // right orientation
5626 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5627 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5628 const vec4 rotClipTL = rotMatrix * clipTL;
5629 const vec4 rotClipBR = rotMatrix * clipBR;
5630 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5631 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5632 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5633 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5634
5635 // Now reposition the clipping rectangle with the displacement vector
5636 // computed above.
5637 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5638
5639 clientCompositionDisplay.clip =
5640 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5641 newClipRight + displacementX, newClipBottom + displacementY);
5642
5643 // We need to perform the same transformation in layer space, so propagate
5644 // it to the global transform.
5645 mat4 clipTransform = displacementMat * rotMatrix;
5646 clientCompositionDisplay.globalTransform *= clipTransform;
5647 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5648 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005649
chaviw50da5042018-04-09 13:49:37 -07005650 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651
Alec Mouri0f714832018-11-12 15:31:06 -08005652 renderengine::LayerSettings fillLayer;
5653 fillLayer.source.buffer.buffer = nullptr;
5654 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5655 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5656 fillLayer.alpha = half(alpha);
5657 clientCompositionLayers.push_back(fillLayer);
5658
5659 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005660 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005661 renderengine::LayerSettings layerSettings;
5662 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5663 layerSettings);
5664 if (prepared) {
5665 clientCompositionLayers.push_back(layerSettings);
5666 }
chaviwa76b2712017-09-20 12:02:26 -07005667 });
Alec Mouri0f714832018-11-12 15:31:06 -08005668
5669 clientCompositionDisplay.clearRegion = clearRegion;
5670 base::unique_fd drawFence;
5671 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5672 &drawFence);
5673
5674 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005675}
5676
chaviwa76b2712017-09-20 12:02:26 -07005677status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5678 TraverseLayersFunction traverseLayers,
5679 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005680 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005681 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005682 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005683 ATRACE_CALL();
5684
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005685 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005686
5687 traverseLayers([&](Layer* layer) {
5688 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5689 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005690
Robert Carr03480e22018-01-04 16:02:06 -08005691 // We allow the system server to take screenshots of secure layers for
5692 // use in situations like the Screen-rotation animation and place
5693 // the impetus on WindowManager to not persist them.
5694 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005695 ALOGW("FB is protected: PERMISSION_DENIED");
5696 return PERMISSION_DENIED;
5697 }
Alec Mouri0f714832018-11-12 15:31:06 -08005698 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005699 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005700}
5701
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005702// ---------------------------------------------------------------------------
5703
Dan Stoza412903f2017-04-27 13:42:17 -07005704void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5705 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005706}
5707
Dan Stoza412903f2017-04-27 13:42:17 -07005708void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5709 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005710}
5711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005712void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005713 const LayerVector::Visitor& visitor) {
5714 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005715 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005716 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005717 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005718 continue;
5719 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005720 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005721 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005722 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005723 return;
5724 }
chaviwa76b2712017-09-20 12:02:26 -07005725 if (!layer->isVisible()) {
5726 return;
5727 }
5728 visitor(layer);
5729 });
5730 }
5731}
5732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005733}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005734
Lloyd Pique074e8122018-07-26 12:57:23 -07005735
Mathias Agopian3f844832013-08-07 21:24:32 -07005736#if defined(__gl_h_)
5737#error "don't include gl/gl.h in this file"
5738#endif
5739
5740#if defined(__gl2_h_)
5741#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005742#endif