blob: dcf3b336481cbdf5164fa57bcbc42b71b858dd1c [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080079#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070082#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080083#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070084#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Steven Thomasb02664d2017-07-26 18:48:28 -070089#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070090#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070091#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070092#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070093#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070094#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070096#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/EventControlThread.h"
98#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070099#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700101#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800102#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700105
David Sodman7e4ae112018-02-09 15:02:28 -0800106#include "android-base/stringprintf.h"
107
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700110#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900112#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
chaviw1d044282017-09-27 12:19:28 -0700114#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900115#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700118
Jaesoo Lee43518572017-01-23 19:03:16 +0900119using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800122using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700123using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700124using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700125using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700126using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127
Steven Thomasb02664d2017-07-26 18:48:28 -0700128namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700129
130#pragma clang diagnostic push
131#pragma clang diagnostic error "-Wswitch-enum"
132
133bool isWideColorMode(const ColorMode colorMode) {
134 switch (colorMode) {
135 case ColorMode::DISPLAY_P3:
136 case ColorMode::ADOBE_RGB:
137 case ColorMode::DCI_P3:
138 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700139 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700140 case ColorMode::BT2100_PQ:
141 case ColorMode::BT2100_HLG:
142 return true;
143 case ColorMode::NATIVE:
144 case ColorMode::STANDARD_BT601_625:
145 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
146 case ColorMode::STANDARD_BT601_525:
147 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
148 case ColorMode::STANDARD_BT709:
149 case ColorMode::SRGB:
150 return false;
151 }
152 return false;
153}
154
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700155ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
156 switch (rotation) {
157 case ISurfaceComposer::eRotateNone:
158 return ui::Transform::ROT_0;
159 case ISurfaceComposer::eRotate90:
160 return ui::Transform::ROT_90;
161 case ISurfaceComposer::eRotate180:
162 return ui::Transform::ROT_180;
163 case ISurfaceComposer::eRotate270:
164 return ui::Transform::ROT_270;
165 }
166 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
167 return ui::Transform::ROT_0;
168}
169
Peiyong Linfca547f2018-07-09 13:03:33 -0700170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Peiyong Lin9d846a52018-11-05 13:18:20 -0800185// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
186bool validateCompositionDataspace(Dataspace dataspace) {
187 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
188}
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190} // namespace anonymous
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192// ---------------------------------------------------------------------------
193
Mathias Agopian99b49842011-06-27 16:05:52 -0700194const String16 sHardwareTest("android.permission.HARDWARE_TEST");
195const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
196const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
197const String16 sDump("android.permission.DUMP");
198
199// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700200int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700201bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800202uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800203bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800204bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800205int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600206bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700207int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700208bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700209bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700210Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
211ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
212Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
213ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700214
Kalle Raitaa099a242017-01-11 11:17:29 -0800215std::string getHwcServiceName() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.hwc_service_name", value, "default");
218 ALOGI("Using HWComposer service: '%s'", value);
219 return std::string(value);
220}
221
222bool useTrebleTestingOverride() {
223 char value[PROPERTY_VALUE_MAX] = {};
224 property_get("debug.sf.treble_testing_override", value, "false");
225 ALOGI("Treble testing override: '%s'", value);
226 return std::string(value) == "true";
227}
228
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
230 switch(displayColorSetting) {
231 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700236 return std::string("Enhanced");
237 default:
238 return std::string("Unknown ") +
239 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241}
242
David Sodmanbc815282017-11-05 18:57:52 -0800243SurfaceFlingerBE::SurfaceFlingerBE()
244 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800245 mFrameBuckets(),
246 mTotalTime(0),
247 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800248 mComposerSequenceId(0) {
249}
250
Lloyd Pique90c115d2018-09-18 21:39:42 -0700251SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
252 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800253 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700254 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700255 mTransactionPending(false),
256 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700257 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700258 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800260 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800262 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800263 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800264 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700266 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700267 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700268 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700269 mDebugInTransaction(0),
270 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700271 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800272 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700273 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700274 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800275 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800276 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700278 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700279 mMainThreadId(std::this_thread::get_id()),
280 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800281
Lloyd Pique90c115d2018-09-18 21:39:42 -0700282SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
283 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 mDefaultCompositionDataspace =
304 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
305 mWideColorGamutCompositionDataspace =
306 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
307 defaultCompositionDataspace = mDefaultCompositionDataspace;
308 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311 wideColorGamutCompositionPixelFormat =
312 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
317 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
318 switch (tmpPrimaryDisplayOrientation) {
319 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
331 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800333
Lloyd Pique90c115d2018-09-18 21:39:42 -0700334 mPrimaryDispSync =
335 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // debugging stuff...
339 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700342 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 property_get("debug.sf.showupdates", value, "0");
345 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347 property_get("debug.sf.ddms", value, "0");
348 mDebugDDMS = atoi(value);
349 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700350 if (!startDdmConnection()) {
351 // start failed, and DDMS debugging not enabled
352 mDebugDDMS = 0;
353 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
356 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700357
358 property_get("debug.sf.disable_backpressure", value, "0");
359 mPropagateBackpressure = !atoi(value);
360 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700361
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800362 property_get("debug.sf.enable_hwc_vds", value, "0");
363 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800364 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800366 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800368 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700369
Yiwei Zhang243b3782018-05-15 17:40:04 -0700370 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Ana Krulec98b5b242018-08-10 15:03:23 -0700374 property_get("debug.sf.use_scheduler", value, "0");
375 mUseScheduler = atoi(value);
376
Ana Krulec757f63a2019-01-25 10:46:18 -0800377 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
378 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400SurfaceFlinger::~SurfaceFlinger()
401{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402}
403
Dan Stozac7014012014-02-14 15:03:43 -0800404void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405{
406 // the window manager died on us. prepare its eulogy.
407
Andy McFadden13a082e2012-08-24 10:16:42 -0700408 // restore initial conditions (default device unblank, etc)
409 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
411 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
Robert Carr1db73f62016-12-21 12:58:51 -0800415static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700416 status_t err = client->initCheck();
417 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419 }
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return nullptr;
421}
422
423sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
424 return initClient(new Client(this));
425}
426
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700427sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
428 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429{
430 class DisplayToken : public BBinder {
431 sp<SurfaceFlinger> flinger;
432 virtual ~DisplayToken() {
433 // no more references, this display must be terminated
434 Mutex::Autolock _l(flinger->mStateLock);
435 flinger->mCurrentState.displays.removeItem(this);
436 flinger->setTransactionFlags(eDisplayTransactionNeeded);
437 }
438 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700439 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 : flinger(flinger) {
441 }
442 };
443
444 sp<BBinder> token = new DisplayToken(this);
445
446 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 // Display ID is assigned when virtual display is allocated by HWC.
448 DisplayDeviceState state;
449 state.isSecure = secure;
450 state.displayName = displayName;
451 mCurrentState.displays.add(token, state);
452 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 return token;
454}
455
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700456void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 Mutex::Autolock _l(mStateLock);
458
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
460 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 return;
463 }
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
466 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 ALOGE("destroyDisplay called for non-virtual display");
468 return;
469 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 mInterceptor->saveDisplayDeletion(state.sequenceId);
471 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 setTransactionFlags(eDisplayTransactionNeeded);
473}
474
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 std::optional<DisplayId> displayId;
477
478 if (id == HWC_DISPLAY_PRIMARY) {
479 displayId = getInternalDisplayId();
480 } else if (id == HWC_DISPLAY_EXTERNAL) {
481 displayId = getExternalDisplayId();
482 }
483
484 if (!displayId) {
485 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800486 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488
489 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700490}
491
Ady Abraham37965d42018-11-01 13:43:32 -0700492status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
493 if (!outGetColorManagement) {
494 return BAD_VALUE;
495 }
496 *outGetColorManagement = useColorManagement;
497 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700498}
499
Lloyd Pique441d5042018-10-18 16:49:51 -0700500HWComposer& SurfaceFlinger::getHwComposer() const {
501 return mCompositionEngine->getHwComposer();
502}
503
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700504renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
505 return mCompositionEngine->getRenderEngine();
506}
507
Lloyd Pique70d91362018-10-18 16:02:55 -0700508compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
509 return *mCompositionEngine.get();
510}
511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512void SurfaceFlinger::bootFinished()
513{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700514 if (mStartPropertySetThread->join() != NO_ERROR) {
515 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800517 const nsecs_t now = systemTime();
518 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000519 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520
521 // wait patiently for the window manager death
522 const String16 name("window");
523 sp<IBinder> window(defaultServiceManager()->getService(name));
524 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700525 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700526 }
Robert Carr720e5062018-07-30 17:45:14 -0700527 sp<IBinder> input(defaultServiceManager()->getService(
528 String16("inputflinger")));
529 if (input == nullptr) {
530 ALOGE("Failed to link to input service");
531 } else {
532 mInputFlinger = interface_cast<IInputFlinger>(input);
533 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534
Steven Thomas050b2c82017-03-06 11:45:16 -0800535 if (mVrFlinger) {
536 mVrFlinger->OnBootFinished();
537 }
538
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700539 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700540 // formerly we would just kill the process, but we now ask it to exit so it
541 // can choose where to stop the animation.
542 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700543
544 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
545 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
546 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700547
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800548 postMessageAsync(new LambdaMessage([this] {
549 readPersistentProperties();
550 mBootStage = BootStage::FINISHED;
551 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552}
553
Dan Stoza436ccf32018-06-21 12:10:12 -0700554uint32_t SurfaceFlinger::getNewTexture() {
555 {
556 std::lock_guard lock(mTexturePoolMutex);
557 if (!mTexturePool.empty()) {
558 uint32_t name = mTexturePool.back();
559 mTexturePool.pop_back();
560 ATRACE_INT("TexturePoolSize", mTexturePool.size());
561 return name;
562 }
563
564 // The pool was too small, so increase it for the future
565 ++mTexturePoolSize;
566 }
567
568 // The pool was empty, so we need to get a new texture name directly using a
569 // blocking call to the main thread
570 uint32_t name = 0;
571 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
572 return name;
573}
574
Mathias Agopian3f844832013-08-07 21:24:32 -0700575void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700576 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700577}
578
Wei Wangf9b05ee2017-07-19 20:59:39 -0700579// Do not call property_set on main thread which will be blocked by init
580// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700582 ALOGI( "SurfaceFlinger's main thread ready to run. "
583 "Initializing graphics H/W...");
584
Ana Krulec757f63a2019-01-25 10:46:18 -0800585 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900586
Steven Thomasb02664d2017-07-26 18:48:28 -0700587 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588
Dominik Laskowski83b88212018-12-11 13:34:06 -0800589 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800590
Steven Thomasb02664d2017-07-26 18:48:28 -0700591 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700592 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700593 mScheduler = getFactory().createScheduler([this](bool enabled) {
594 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
595 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800596 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
597 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
598 mPhaseOffsets->setRefreshRateType(
599 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700600
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800602 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800603 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700604 impl::EventThread::InterceptVSyncsCallback());
605 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800606 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800607 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700608 mInterceptor->saveVSyncEvent(timestamp);
609 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800610
Ana Krulec98b5b242018-08-10 15:03:23 -0700611 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700612 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
613 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700614 } else {
615 mEventThreadSource =
616 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800617 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700618 mEventThread =
619 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700620 impl::EventThread::InterceptVSyncsCallback(),
621 "appEventThread");
622 mSfEventThreadSource =
623 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800624 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700625
626 mSFEventThread =
627 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 [this](nsecs_t timestamp) {
629 mInterceptor->saveVSyncEvent(timestamp);
630 },
631 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800632 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
634 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700637 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700638 renderEngineFeature |= (useColorManagement ?
639 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700640 renderEngineFeature |= (useContextPriority ?
641 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700642
643 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700644 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700645 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700646 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700647
648 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
649 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700650 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
651 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800652 // Process any initial hotplug and resulting display changes.
653 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 const auto display = getDefaultDisplayDeviceLocked();
655 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700656 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800658
Steven Thomas050b2c82017-03-06 11:45:16 -0800659 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700660 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700661 // This callback is called from the vr flinger dispatch thread. We
662 // need to call signalTransaction(), which requires holding
663 // mStateLock when we're not on the main thread. Acquiring
664 // mStateLock from the vr flinger dispatch thread might trigger a
665 // deadlock in surface flinger (see b/66916578), so post a message
666 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700667 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700668 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
669 mVrFlingerRequestsDisplay = requestDisplay;
670 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700671 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
674 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700675 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 .value_or(0),
677 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 if (!mVrFlinger) {
679 ALOGE("Failed to start vrflinger");
680 }
681 }
682
Lloyd Pique90c115d2018-09-18 21:39:42 -0700683 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700685
Mathias Agopian92a979a2012-08-02 18:32:23 -0700686 // initialize our drawing state
687 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700688
Andy McFadden13a082e2012-08-24 10:16:42 -0700689 // set initial conditions (e.g. unblank default device)
690 initializeDisplays();
691
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700692 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700693
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700695
696 const bool presentFenceReliable =
697 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
698 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Ana Krulec7d1d6832018-12-27 11:10:09 -0800704 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800705 mScheduler->setExpiredIdleTimerCallback([this]() {
706 mPhaseOffsets->setRefreshRateType(
707 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
708 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
709 mVsyncModulator.setPhaseOffsets(early, gl, late);
710 setRefreshRateTo(60.f /* fps */);
711 });
712 mScheduler->setResetIdleTimerCallback([this]() {
713 mPhaseOffsets->setRefreshRateType(
714 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
715 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
716 mVsyncModulator.setPhaseOffsets(early, gl, late);
717 setRefreshRateTo(90.f /* fps */);
718 });
Ana Krulecb43429d2019-01-09 14:28:51 -0800719 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
720 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800721 }
722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700737 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700751 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700755 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
794 Vector<DisplayInfo>* configs) {
795 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Dominik Laskowski075d3172018-05-24 15:50:06 -0700799 const auto displayId = getPhysicalDisplayId(displayToken);
800 if (!displayId) {
801 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700802 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804 // TODO: Not sure if display density should handled by SF any longer
805 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700806 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700808 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800809 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700810 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 }
812 return density;
813 }
814 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700815 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 return getDensityFromProperty("ro.sf.lcd_density"); }
819 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700820
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700822
Steven Thomas6d8110b2017-08-31 18:24:21 -0700823 ConditionalLock _l(mStateLock,
824 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700825 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 DisplayInfo info = DisplayInfo();
827
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 float xdpi = hwConfig->getDpiX();
829 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700831 info.w = hwConfig->getWidth();
832 info.h = hwConfig->getHeight();
833 // Default display viewport to display width and height
834 info.viewportW = info.w;
835 info.viewportH = info.h;
836
Dominik Laskowski075d3172018-05-24 15:50:06 -0700837 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 // The density of the device is provided by a build property
839 float density = Density::getBuildDensity() / 160.0f;
840 if (density == 0) {
841 // the build doesn't provide a density -- this is wrong!
842 // use xdpi instead
843 ALOGE("ro.sf.lcd_density must be defined as a build property");
844 density = xdpi / 160.0f;
845 }
846 if (Density::getEmuDensity()) {
847 // if "qemu.sf.lcd_density" is specified, it overrides everything
848 xdpi = ydpi = density = Density::getEmuDensity();
849 density /= 160.0f;
850 }
851 info.density = density;
852
853 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700854 const auto display = getDefaultDisplayDeviceLocked();
855 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700856
857 // This is for screenrecord
858 const Rect viewport = display->getViewport();
859 if (viewport.isValid()) {
860 info.viewportW = uint32_t(viewport.getWidth());
861 info.viewportH = uint32_t(viewport.getHeight());
862 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 } else {
864 // TODO: where should this value come from?
865 static const int TV_DENSITY = 213;
866 info.density = TV_DENSITY / 160.0f;
867 info.orientation = 0;
868 }
869
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 info.xdpi = xdpi;
871 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800873 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874
Andy McFadden91b2ca82014-06-13 14:04:23 -0700875 // This is how far in advance a buffer must be queued for
876 // presentation at a given time. If you want a buffer to appear
877 // on the screen at time N, you must submit the buffer before
878 // (N - presentationDeadline).
879 //
880 // Normally it's one full refresh period (to give SF a chance to
881 // latch the buffer), but this can be reduced by configuring a
882 // DispSync offset. Any additional delays introduced by the hardware
883 // composer or panel must be accounted for here.
884 //
885 // We add an additional 1ms to allow for processing time and
886 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800887 info.presentationDeadline =
888 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700889
890 // All non-virtual displays are currently considered secure.
891 info.secure = true;
892
Dominik Laskowski075d3172018-05-24 15:50:06 -0700893 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700894 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800895 std::swap(info.w, info.h);
896 }
897
Michael Wright28f24d02016-07-12 13:30:53 -0700898 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 return NO_ERROR;
902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
905 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700906 return BAD_VALUE;
907 }
908
Ana Krulece588e312018-09-18 12:32:24 -0700909 if (mUseScheduler) {
910 mScheduler->getDisplayStatInfo(stats);
911 } else {
912 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
913 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
914 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return NO_ERROR;
916}
917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
919 const auto display = getDisplayDevice(displayToken);
920 if (!display) {
921 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800922 return BAD_VALUE;
923 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700926}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700927
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
929 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800930 postMessageAsync(new LambdaMessage(
931 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800932 return NO_ERROR;
933}
934
935status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
936 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800937 postMessageSync(new LambdaMessage(
938 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800939 return NO_ERROR;
940}
941
942void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
943 Vector<DisplayInfo> configs;
944 getDisplayConfigs(displayToken, &configs);
945 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
946 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
947 return;
948 }
949
950 const auto display = getDisplayDevice(displayToken);
951 if (!display) {
952 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
953 displayToken.get());
954 return;
955 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700956 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800957 ALOGW("Attempt to set active config %d for virtual display", mode);
958 return;
959 }
960 int currentDisplayPowerMode = display->getPowerMode();
961 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
962 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 return;
964 }
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800968 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700969 return;
970 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800971 if (mUseScheduler) {
972 mRefreshRateStats->setConfigMode(mode);
973 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700974
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 const auto displayId = display->getId();
976 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700979 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700980
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800982 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -0700983}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
986 Vector<ColorMode>* outColorModes) {
987 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700988 return BAD_VALUE;
989 }
990
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 const auto displayId = getPhysicalDisplayId(displayToken);
992 if (!displayId) {
993 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700994 }
995
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700997 {
998 ConditionalLock _l(mStateLock,
999 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 }
Michael Wright28f24d02016-07-12 13:30:53 -07001002 outColorModes->clear();
1003 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1004
1005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1009 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001010 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001011 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001016 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 Vector<ColorMode> modes;
1018 getDisplayColorModes(displayToken, &modes);
1019 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1020 if (mode < ColorMode::NATIVE || !exists) {
1021 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1022 decodeColorMode(mode).c_str(), mode, displayToken.get());
1023 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001024 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 const auto display = getDisplayDevice(displayToken);
1026 if (!display) {
1027 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1028 decodeColorMode(mode).c_str(), mode, displayToken.get());
1029 } else if (display->isVirtual()) {
1030 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1031 decodeColorMode(mode).c_str(), mode);
1032 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001033 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1034 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 }
1036 }));
1037
Michael Wright28f24d02016-07-12 13:30:53 -07001038 return NO_ERROR;
1039}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001040
Svetoslavd85084b2014-03-20 10:28:31 -07001041status_t SurfaceFlinger::clearAnimationFrameStats() {
1042 Mutex::Autolock _l(mStateLock);
1043 mAnimFrameTracker.clearStats();
1044 return NO_ERROR;
1045}
1046
1047status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1048 Mutex::Autolock _l(mStateLock);
1049 mAnimFrameTracker.getStats(outStats);
1050 return NO_ERROR;
1051}
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1054 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001055 Mutex::Autolock _l(mStateLock);
1056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 const auto display = getDisplayDeviceLocked(displayToken);
1058 if (!display) {
1059 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001060 return BAD_VALUE;
1061 }
1062
Peiyong Linfb069302018-04-25 14:34:31 -07001063 // At this point the DisplayDeivce should already be set up,
1064 // meaning the luminance information is already queried from
1065 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001067 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1068 capabilities.getDesiredMaxLuminance(),
1069 capabilities.getDesiredMaxAverageLuminance(),
1070 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001071
1072 return NO_ERROR;
1073}
1074
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001075status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1076 ui::PixelFormat* outFormat,
1077 ui::Dataspace* outDataspace,
1078 uint8_t* outComponentMask) const {
1079 if (!outFormat || !outDataspace || !outComponentMask) {
1080 return BAD_VALUE;
1081 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001082 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001083 if (!display || !display->getId()) {
1084 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1085 return BAD_VALUE;
1086 }
1087 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1088 outDataspace, outComponentMask);
1089}
1090
Kevin DuBois74e53772018-11-19 10:52:38 -08001091status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1092 bool enable, uint8_t componentMask,
1093 uint64_t maxFrames) const {
1094 const auto display = getDisplayDevice(displayToken);
1095 if (!display || !display->getId()) {
1096 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1097 return BAD_VALUE;
1098 }
1099
1100 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1101 componentMask, maxFrames);
1102}
1103
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001104status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1105 uint64_t maxFrames, uint64_t timestamp,
1106 DisplayedFrameStats* outStats) const {
1107 const auto display = getDisplayDevice(displayToken);
1108 if (!display || !display->getId()) {
1109 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1110 return BAD_VALUE;
1111 }
1112
1113 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1114 outStats);
1115}
1116
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001117status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1118 if (!outSupported) {
1119 return BAD_VALUE;
1120 }
1121 *outSupported = getRenderEngine().supportsProtectedContent();
1122 return NO_ERROR;
1123}
1124
Marissa Wallebc2c052019-01-16 19:16:55 -08001125status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1126 int32_t* outBufferId) {
1127 if (!outBufferId) {
1128 return BAD_VALUE;
1129 }
1130 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1131 return NO_ERROR;
1132}
1133
1134status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1135 mBufferStateLayerCache.release(token, bufferId);
1136 return NO_ERROR;
1137}
1138
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001139status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1140 bool* outIsWideColorDisplay) const {
1141 if (!displayToken || !outIsWideColorDisplay) {
1142 return BAD_VALUE;
1143 }
1144 Mutex::Autolock _l(mStateLock);
1145 const auto display = getDisplayDeviceLocked(displayToken);
1146 if (!display) {
1147 return BAD_VALUE;
1148 }
1149 *outIsWideColorDisplay = display->hasWideColorGamut();
1150 return NO_ERROR;
1151}
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001154 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 if (mInjectVSyncs == enable) {
1158 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160
Dominik Laskowski83b88212018-12-11 13:34:06 -08001161 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001162
Ana Krulec98b5b242018-08-10 15:03:23 -07001163 // TODO(akrulec): Part of the Injector should be refactored, so that it
1164 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 if (enable) {
1166 ALOGV("VSync Injections enabled");
1167 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001168 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001169 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001170 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001171 impl::EventThread::InterceptVSyncsCallback(),
1172 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001174 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 } else {
1176 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001177 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 }
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001181 }));
1182
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 return NO_ERROR;
1184}
1185
1186status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 Mutex::Autolock _l(mStateLock);
1188
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189 if (!mInjectVSyncs) {
1190 ALOGE("VSync Injections not enabled");
1191 return BAD_VALUE;
1192 }
1193 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1194 ALOGV("Injecting VSync inside SurfaceFlinger");
1195 mVSyncInjector->onInjectSyncEvent(when);
1196 }
1197 return NO_ERROR;
1198}
1199
Lloyd Pique755e3192018-01-31 16:46:15 -08001200status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1201 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001202 // Try to acquire a lock for 1s, fail gracefully
1203 const status_t err = mStateLock.timedLock(s2ns(1));
1204 const bool locked = (err == NO_ERROR);
1205 if (!locked) {
1206 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1207 return TIMED_OUT;
1208 }
1209
1210 outLayers->clear();
1211 mCurrentState.traverseInZOrder([&](Layer* layer) {
1212 outLayers->push_back(layer->getLayerDebugInfo());
1213 });
1214
1215 mStateLock.unlock();
1216 return NO_ERROR;
1217}
1218
Peiyong Linc6780972018-10-28 15:24:08 -07001219status_t SurfaceFlinger::getCompositionPreference(
1220 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1221 Dataspace* outWideColorGamutDataspace,
1222 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001223 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001224 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001225 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001226 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001227 return NO_ERROR;
1228}
1229
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001230// ----------------------------------------------------------------------------
1231
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001232sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1233 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001234 auto resyncCallback = makeResyncCallback([this] {
1235 Mutex::Autolock lock(mStateLock);
1236 return getVsyncPeriod();
1237 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001238
Ana Krulec98b5b242018-08-10 15:03:23 -07001239 if (mUseScheduler) {
1240 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001241 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001242 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001243 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001244 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001245 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001248 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001250 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001251 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001252}
1253
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255
1256void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001269 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001274 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001275 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276}
1277
1278status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001279 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001280 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001281 if (res == NO_ERROR) {
1282 msg->wait();
1283 }
1284 return res;
1285}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001287void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288 do {
1289 waitForEvent();
1290 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001291}
1292
Dominik Laskowski83b88212018-12-11 13:34:06 -08001293nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1294 const auto displayId = getInternalDisplayId();
1295 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1296 return 0;
1297 }
1298
1299 const auto config = getHwComposer().getActiveConfig(*displayId);
1300 return config ? config->getVsyncPeriod() : 0;
1301}
1302
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303void SurfaceFlinger::enableHardwareVsync() {
1304 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001305 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001306 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001307 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001308 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001309 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310}
1311
Dominik Laskowski83b88212018-12-11 13:34:06 -08001312void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313 Mutex::Autolock _l(mHWVsyncLock);
1314
Jesse Hall948fe0c2013-10-14 12:56:09 -07001315 if (makeAvailable) {
1316 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001317 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1318 if (mUseScheduler) {
1319 mScheduler->makeHWSyncAvailable(true);
1320 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001321 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001322 // Hardware vsync is not currently available, so abort the resync
1323 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001324 return;
1325 }
1326
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001328 return;
1329 }
1330
Ana Krulece588e312018-09-18 12:32:24 -07001331 if (mUseScheduler) {
1332 mScheduler->setVsyncPeriod(period);
1333 } else {
1334 mPrimaryDispSync->reset();
1335 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336
Ana Krulece588e312018-09-18 12:32:24 -07001337 if (!mPrimaryHWVsyncEnabled) {
1338 mPrimaryDispSync->beginResync();
1339 mEventControlThread->setVsyncEnabled(true);
1340 mPrimaryHWVsyncEnabled = true;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 }
1343}
1344
Jesse Hall948fe0c2013-10-14 12:56:09 -07001345void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 Mutex::Autolock _l(mHWVsyncLock);
1347 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001348 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001349 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350 mPrimaryHWVsyncEnabled = false;
1351 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001352 if (makeUnavailable) {
1353 mHWVsyncAvailable = false;
1354 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001355}
1356
Dominik Laskowski83b88212018-12-11 13:34:06 -08001357void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001358 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001359
Dan Stoza57164302017-05-08 14:03:54 -07001360 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361 const nsecs_t last = lastResyncTime.exchange(now);
1362
1363 if (now - last > kIgnoreDelay) {
1364 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365 }
1366}
1367
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001368void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1369 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001370 ATRACE_NAME("SF onVsync");
1371
Steven Thomas3cfac282017-02-06 12:29:30 -08001372 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 return;
1376 }
1377
Dominik Laskowski075d3172018-05-24 15:50:06 -07001378 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 return;
1380 }
1381
Dominik Laskowski075d3172018-05-24 15:50:06 -07001382 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 // For now, we don't do anything with external display vsyncs.
1384 return;
1385 }
1386
Ana Krulece588e312018-09-18 12:32:24 -07001387 if (mUseScheduler) {
1388 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001389 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001390 bool needsHwVsync = false;
1391 { // Scope for the lock
1392 Mutex::Autolock _l(mHWVsyncLock);
1393 if (mPrimaryHWVsyncEnabled) {
1394 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1395 }
1396 }
1397
1398 if (needsHwVsync) {
1399 enableHardwareVsync();
1400 } else {
1401 disableHardwareVsync(false);
1402 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001403 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001404}
1405
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001406void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001407 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1408 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001409}
1410
Ana Krulec7d1d6832018-12-27 11:10:09 -08001411void SurfaceFlinger::setRefreshRateTo(float newFps) {
1412 const auto displayId = getInternalDisplayId();
1413 if (!displayId || mBootStage != BootStage::FINISHED) {
1414 return;
1415 }
1416 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1417 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1418 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1419 // refresh cycle.
1420
1421 // Don't do any updating if the current fps is the same as the new one.
1422 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1423 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1424 if (currentVsyncPeriod == 0) {
1425 return;
1426 }
1427 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1428 // floating numbers.
1429 const float currentFps = 1e9 / currentVsyncPeriod;
1430 if (std::abs(currentFps - newFps) <= 1) {
1431 return;
1432 }
1433
1434 auto configs = getHwComposer().getConfigs(*displayId);
1435 for (int i = 0; i < configs.size(); i++) {
1436 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1437 if (vsyncPeriod == 0) {
1438 continue;
1439 }
1440 const float fps = 1e9 / vsyncPeriod;
1441 // TODO(b/113612090): There should be a better way at determining which config
1442 // has the right refresh rate.
1443 if (std::abs(fps - newFps) <= 1) {
1444 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1445 if (!display) return;
1446 // This is posted in async function to avoid deadlock when getDisplayDevice
1447 // requires mStateLock.
1448 setActiveConfigAsync(display, i);
1449 ATRACE_INT("FPS", newFps);
1450 }
1451 }
1452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001455 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 // Ignore events that do not have the right sequenceId.
1460 if (sequenceId != getBE().mComposerSequenceId) {
1461 return;
1462 }
1463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Only lock if we're not on the main thread. This function is normally
1465 // called on a hwbinder thread, but for the primary display it's called on
1466 // the main thread with the state lock already held, so don't attempt to
1467 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001468 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001471
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001472 if (std::this_thread::get_id() == mMainThreadId) {
1473 // Process all pending hot plug events immediately if we are on the main thread.
1474 processDisplayHotplugEventsLocked();
1475 }
1476
Lloyd Piqueba04e622017-12-14 17:11:26 -08001477 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001478}
1479
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001480void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001482 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001485 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001486}
1487
Dominik Laskowski075d3172018-05-24 15:50:06 -07001488void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001489 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001491 if (const auto displayId = getInternalDisplayId()) {
1492 getHwComposer().setVsyncEnabled(*displayId,
1493 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1494 }
Mathias Agopian86303202012-07-24 22:46:10 -07001495}
1496
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001498void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001499 if (mUseScheduler) {
1500 mScheduler->disableHardwareVsync(true);
1501 } else {
1502 disableHardwareVsync(true);
1503 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504 // Clear the drawing state so that the logic inside of
1505 // handleTransactionLocked will fire. It will determine the delta between
1506 // mCurrentState and mDrawingState and re-apply all changes when we make the
1507 // transition.
1508 mDrawingState.displays.clear();
1509 mDisplays.clear();
1510}
1511
Steven Thomas050b2c82017-03-06 11:45:16 -08001512void SurfaceFlinger::updateVrFlinger() {
1513 if (!mVrFlinger)
1514 return;
1515 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001516 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001517 return;
1518 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519
Lloyd Pique441d5042018-10-18 16:49:51 -07001520 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001521 ALOGE("Vr flinger is only supported for remote hardware composer"
1522 " service connections. Ignoring request to transition to vr"
1523 " flinger.");
1524 mVrFlingerRequestsDisplay = false;
1525 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001526 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001528 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Steven Thomas0123ac62018-07-12 11:32:34 -07001530 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001531 LOG_ALWAYS_FATAL_IF(!display);
1532 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001533 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1534 // called below. Clear the reference now so we don't accidentally use it
1535 // later.
1536 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001537
Steven Thomasb02664d2017-07-26 18:48:28 -07001538 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001540 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001541
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 // Delete the current instance before creating the new one
1544 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1545 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1546 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1547 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001548
Lloyd Pique441d5042018-10-18 16:49:51 -07001549 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001550 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001551
1552 if (vrFlingerRequestsDisplay) {
1553 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001554 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555
1556 mVisibleRegionsDirty = true;
1557 invalidateHwcGeometry();
1558
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001559 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001560 display = getDefaultDisplayDeviceLocked();
1561 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001562 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001563
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565 const nsecs_t vsyncPeriod = getVsyncPeriod();
1566 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001567
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568 // The present fences returned from vr_hwc are not an accurate
1569 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001570 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001571 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1572 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001573 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001574 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001575 !hasSyncFramework);
1576 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001577
Steven Thomasb02664d2017-07-26 18:48:28 -07001578 // Use phase of 0 since phase is not known.
1579 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001580 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001581 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001582
Dominik Laskowski83b88212018-12-11 13:34:06 -08001583 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001584
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001585 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001586 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001587}
1588
Mathias Agopian4fec8732012-06-29 14:12:52 -07001589void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001590 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001591 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001592 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001593 if (mUseScheduler) {
1594 // This call is made each time SF wakes up and creates a new frame.
1595 mScheduler->incrementFrameCounter();
1596 }
Dan Stoza50182882016-07-08 12:02:20 -07001597 bool frameMissed = !mHadClientComposition &&
1598 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 (mPreviousPresentFence->getSignalTime() ==
1600 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001601 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001602 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001603 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001604 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001605 if (mPropagateBackpressure) {
1606 signalLayerUpdate();
1607 break;
1608 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001609 }
Dan Stoza50182882016-07-08 12:02:20 -07001610
Steven Thomas050b2c82017-03-06 11:45:16 -08001611 // Now that we're going to make it to the handleMessageTransaction()
1612 // call below it's safe to call updateVrFlinger(), which will
1613 // potentially trigger a display handoff.
1614 updateVrFlinger();
1615
Dan Stoza6b9454d2014-11-07 16:00:59 -08001616 bool refreshNeeded = handleMessageTransaction();
1617 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001618 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001619 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001620 // Signal a refresh if a transaction modified the window state,
1621 // a new buffer was latched, or if HWC has requested a full
1622 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001623 signalRefresh();
1624 }
1625 break;
1626 }
1627 case MessageQueue::REFRESH: {
1628 handleMessageRefresh();
1629 break;
1630 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001631 }
1632}
1633
Dan Stoza6b9454d2014-11-07 16:00:59 -08001634bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001635 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001636
1637 // Apply any ready transactions in the queues if there are still transactions that have not been
1638 // applied, wake up during the next vsync period and check again
1639 bool transactionNeeded = false;
1640 if (!flushTransactionQueues()) {
1641 transactionNeeded = true;
1642 }
1643
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001645 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001647
1648 if (transactionNeeded) {
1649 setTransactionFlags(eTransactionNeeded);
1650 }
1651
1652 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653}
1654
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001658 mRefreshPending = false;
1659
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001660 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001661 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001662 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001663 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001664 for (const auto& [token, display] : mDisplays) {
1665 beginFrame(display);
1666 prepareFrame(display);
1667 doDebugFlashRegions(display, repaintEverything);
1668 doComposition(display, repaintEverything);
1669 }
1670
Adrian Roos1e1a1282017-11-01 19:05:31 +01001671 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001672 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673
1674 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001675 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001676
Dan Stozabfbffeb2016-07-21 14:49:33 -07001677 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001678 for (const auto& [token, displayDevice] : mDisplays) {
1679 auto display = displayDevice->getCompositionDisplay();
1680 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001682 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001683 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684
Alec Mouri86770e52018-09-24 22:40:58 +00001685 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001686 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001687 if (mHadClientComposition) {
1688 base::unique_fd flushFence(getRenderEngine().flush());
1689 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1690 getBE().flushFence = new Fence(std::move(flushFence));
1691 } else {
1692 // Cleanup for hygiene.
1693 getBE().flushFence = Fence::NO_FENCE;
1694 }
1695 }
1696
Jorim Jaggi90535212018-05-23 23:44:06 +02001697 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
David Sodman7e4ae112018-02-09 15:02:28 -08001699 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001700 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001701 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001702 compositionInfo.hwc.hwcLayer = nullptr;
1703 }
David Sodmanba340492018-08-05 21:51:33 -07001704 }
David Sodman7e4ae112018-02-09 15:02:28 -08001705
1706 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709
1710bool SurfaceFlinger::handleMessageInvalidate() {
1711 ATRACE_CALL();
1712 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713}
1714
David Sodman79bba0e2018-08-05 18:07:49 -07001715void SurfaceFlinger::calculateWorkingSet() {
1716 ATRACE_CALL();
1717 ALOGV(__FUNCTION__);
1718
David Sodman79bba0e2018-08-05 18:07:49 -07001719 // build the h/w work list
1720 if (CC_UNLIKELY(mGeometryInvalid)) {
1721 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001722 for (const auto& [token, displayDevice] : mDisplays) {
1723 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001724 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001725 if (!displayId) {
1726 continue;
1727 }
David Sodman79bba0e2018-08-05 18:07:49 -07001728
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001730 for (size_t i = 0; i < currentLayers.size(); i++) {
1731 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001732
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 if (!layer->hasHwcLayer(*displayId)) {
1734 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1735 layer->forceClientComposition(*displayId);
1736 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001737 }
1738 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739
Lloyd Pique32cbe282018-10-19 13:09:22 -07001740 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741 if (mDebugDisableHWC || mDebugRegion) {
1742 layer->forceClientComposition(*displayId);
1743 }
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
1745 }
1746 }
1747
1748 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001749 for (const auto& [token, displayDevice] : mDisplays) {
1750 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001751 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001753 continue;
1754 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001755 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001756
1757 if (mDrawingState.colorMatrixChanged) {
1758 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001759 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001760 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001761 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001762 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001763 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1764 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001765 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001766 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001767 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1768 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001769 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001770 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001771 }
1772
Peiyong Lind3788632018-09-18 16:01:31 -07001773 // TODO(b/111562338) remove when composer 2.3 is shipped.
1774 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001775 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001776 }
1777
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001778 if (layer->getRoundedCornerState().radius > 0.0f) {
1779 layer->forceClientComposition(*displayId);
1780 }
1781
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001783 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 continue;
1786 }
1787
Lloyd Pique32cbe282018-10-19 13:09:22 -07001788 const auto& displayState = display->getState();
1789 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1790 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792
Peiyong Lin13effd12018-07-24 17:01:47 -07001793 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 ColorMode colorMode;
1795 Dataspace dataSpace;
1796 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001799 }
1800 }
1801
1802 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001803
1804 for (const auto& [token, display] : mDisplays) {
1805 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001806 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001807 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808
1809 if (displayId) {
1810 if (!layer->setHwcLayer(*displayId)) {
1811 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1812 }
1813 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001814 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815
Dominik Laskowski05275f12018-11-01 15:03:24 -07001816 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001817 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1818 }
1819 }
David Sodman79bba0e2018-08-05 18:07:49 -07001820}
1821
Lloyd Pique32cbe282018-10-19 13:09:22 -07001822void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1823 bool repaintEverything) {
1824 auto display = displayDevice->getCompositionDisplay();
1825 const auto& displayState = display->getState();
1826
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827 // is debugging enabled
1828 if (CC_LIKELY(!mDebugRegion))
1829 return;
1830
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001832 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834 if (!dirtyRegion.isEmpty()) {
1835 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001836 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837
David Sodmanfa9b2af2017-12-24 13:28:59 -08001838 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001839 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001840 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001841
Lloyd Pique31cb2942018-10-19 17:23:03 -07001842 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001843 }
1844 }
1845
Lloyd Pique32cbe282018-10-19 13:09:22 -07001846 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847
1848 if (mDebugRegion > 1) {
1849 usleep(mDebugRegion * 1000);
1850 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001851
Lloyd Pique32cbe282018-10-19 13:09:22 -07001852 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001853}
1854
Adrian Roos1e1a1282017-11-01 19:05:31 +01001855void SurfaceFlinger::doTracing(const char* where) {
1856 ATRACE_CALL();
1857 ATRACE_NAME(where);
1858 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001859 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001860 }
1861}
1862
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001863void SurfaceFlinger::logLayerStats() {
1864 ATRACE_CALL();
1865 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001866 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001867 if (display->isPrimary()) {
1868 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001869 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001870 }
1871 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001872
1873 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001874 }
1875}
1876
David Sodman2b406362017-12-15 13:33:47 -08001877void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 ATRACE_CALL();
1880 ALOGV("preComposition");
1881
David Sodman2b406362017-12-15 13:33:47 -08001882 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1883
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001885 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001886 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001887 needExtraInvalidate = true;
1888 }
Robert Carr2047fae2016-11-28 14:09:09 -08001889 });
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 if (needExtraInvalidate) {
1892 signalLayerUpdate();
1893 }
1894}
1895
Ana Krulece588e312018-09-18 12:32:24 -07001896void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1897 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 // Update queue of past composite+present times and determine the
1899 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001900 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001901 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001902 while (!getBE().mCompositePresentTimes.empty()) {
1903 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 // Cached values should have been updated before calling this method,
1905 // which helps avoid duplicate syscalls.
1906 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1907 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1908 break;
1909 }
1910 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001911 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 }
1913
1914 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001915 while (getBE().mCompositePresentTimes.size() > 16) {
1916 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917 }
1918
Ana Krulece588e312018-09-18 12:32:24 -07001919 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001920}
1921
Ana Krulece588e312018-09-18 12:32:24 -07001922void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1923 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 // Integer division and modulo round toward 0 not -inf, so we need to
1925 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001926 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1927 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1928 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001929
Ana Krulec757f63a2019-01-25 10:46:18 -08001930 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001931 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001932 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001933 }
1934
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 // Snap the latency to a value that removes scheduling jitter from the
1936 // composition and present times, which often have >1ms of jitter.
1937 // Reducing jitter is important if an app attempts to extrapolate
1938 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001939 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001941 nsecs_t bias = stats.vsyncPeriod / 2;
1942 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1943 nsecs_t snappedCompositeToPresentLatency =
1944 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945
David Sodman99974d22017-11-28 12:04:33 -08001946 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001947 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1948 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001949 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950}
1951
Ady Abraham8164d482019-01-11 14:47:59 -08001952// debug patch for b/119477596 - add stack guards to catch stack
1953// corruptions and disable clang optimizations.
1954// The code below is temporary and planned to be removed once stack
1955// corruptions are found.
1956#pragma clang optimize off
1957class StackGuard {
1958public:
1959 StackGuard(const char* name, const char* func, int line) {
1960 guarders.reserve(MIN_CAPACITY);
1961 guarders.push_back({this, name, func, line});
1962 validate();
1963 }
1964 ~StackGuard() {
1965 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1966 if (i->guard == this) {
1967 guarders.erase(i);
1968 break;
1969 }
1970 }
1971 }
1972
1973 static void validate() {
1974 for (const auto& guard : guarders) {
1975 if (guard.guard->cookie != COOKIE_VALUE) {
1976 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1977 CallStack stack(LOG_TAG);
1978 abort();
1979 }
1980 }
1981 }
1982
1983private:
1984 uint64_t cookie = COOKIE_VALUE;
1985 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1986 static constexpr size_t MIN_CAPACITY = 16;
1987
1988 struct GuarderElement {
1989 StackGuard* guard;
1990 const char* name;
1991 const char* func;
1992 int line;
1993 };
1994
1995 static std::vector<GuarderElement> guarders;
1996};
1997std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1998
1999#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2000
2001#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002002void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002003{
Ady Abraham8164d482019-01-11 14:47:59 -08002004 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ATRACE_CALL();
2006 ALOGV("postComposition");
2007
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002009 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002010 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002012 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013 }
Ady Abraham8164d482019-01-11 14:47:59 -08002014 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002016 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002017 const auto displayDevice = getDefaultDisplayDeviceLocked();
2018 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002022 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2023
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002026 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2027 ->getRenderSurface()
2028 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 } else {
2031 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2032 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033
Ady Abraham8164d482019-01-11 14:47:59 -08002034 ASSERT_ON_STACK_GUARD();
2035
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002037 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2038 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002039 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002041 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042
Ana Krulece588e312018-09-18 12:32:24 -07002043 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002045 if (mUseScheduler) {
2046 mScheduler->getDisplayStatInfo(&stats);
2047 } else {
2048 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2049 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2050 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051
Ady Abraham8164d482019-01-11 14:47:59 -08002052 ASSERT_ON_STACK_GUARD();
2053
David Sodman2b406362017-12-15 13:33:47 -08002054 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 // when we started doing work for this frame, but that should be okay
2056 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002057 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002058 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002059 DEFINE_STACK_GUARD(compositorTiming);
2060
Brian Andersond0010582017-03-07 13:20:31 -08002061 {
David Sodman99974d22017-11-28 12:04:33 -08002062 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002063 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002064 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002065
2066 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002067 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068
Robert Carr2047fae2016-11-28 14:09:09 -08002069 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 bool frameLatched =
2071 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2072 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002073 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002074 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002075 recordBufferingStats(layer->getName().string(),
2076 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002077 }
Ady Abraham8164d482019-01-11 14:47:59 -08002078 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002079 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002080
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002081 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002082 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002083 if (mUseScheduler) {
2084 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002085 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002086 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002087 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2088 enableHardwareVsync();
2089 } else {
2090 disableHardwareVsync(false);
2091 }
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002093 }
2094 }
2095
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002096 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2098 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002099 if (mUseScheduler) {
2100 mScheduler->enableHardwareVsync();
2101 } else {
2102 enableHardwareVsync();
2103 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002104 }
2105 }
2106
Ady Abraham8164d482019-01-11 14:47:59 -08002107 ASSERT_ON_STACK_GUARD();
2108
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002109 if (mAnimCompositionPending) {
2110 mAnimCompositionPending = false;
2111
Brian Anderson4e606e32017-03-16 15:34:57 -07002112 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002114 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002115
2116 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002117 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002118 // The HWC doesn't support present fences, so use the refresh
2119 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002120 const nsecs_t presentTime =
2121 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002122 DEFINE_STACK_GUARD(presentTime);
2123
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002124 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126 }
2127 mAnimFrameTracker.advanceFrame();
2128 }
Dan Stozab90cf072015-03-05 11:05:59 -08002129
Ady Abraham8164d482019-01-11 14:47:59 -08002130 ASSERT_ON_STACK_GUARD();
2131
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002132 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002133 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002134 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002135 }
2136
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
2138
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002139 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002140
Ady Abraham8164d482019-01-11 14:47:59 -08002141 ASSERT_ON_STACK_GUARD();
2142
Lloyd Pique32cbe282018-10-19 13:09:22 -07002143 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2144 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002145 return;
2146 }
2147
2148 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002149 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002150 if (mHasPoweredOff) {
2151 mHasPoweredOff = false;
2152 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002153 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002155 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002157 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2158 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002159 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002160 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002161 }
David Sodman4a36e932017-11-07 14:29:47 -08002162 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002163
2164 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002165 }
David Sodman4a36e932017-11-07 14:29:47 -08002166 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002167 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002168
2169 {
2170 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002171 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002172 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002173 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002174 if (refillCount > 0) {
2175 const size_t offset = mTexturePool.size();
2176 mTexturePool.resize(mTexturePoolSize);
2177 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2178 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2179 }
Ady Abraham8164d482019-01-11 14:47:59 -08002180 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002181 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002182
Marissa Wallfda30bb2018-10-12 11:34:28 -07002183 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002184 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002185
2186 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002187}
Ady Abraham8164d482019-01-11 14:47:59 -08002188#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189
2190void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 ATRACE_CALL();
2192 ALOGV("rebuildLayerStacks");
2193
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002194 // We need to clear these out now as these may be holding on to a
2195 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2196 // also holds a reference. When the set of visible layers is recomputed,
2197 // some layers may be destroyed if the only thing keeping them alive was
2198 // that list of visible layers associated with each display. The layer
2199 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2200 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2201 for (const auto& [token, display] : mDisplays) {
2202 getBE().mCompositionInfo[token].clear();
2203 }
2204
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002206 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002207 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 mVisibleRegionsDirty = false;
2209 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002211 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002212 const auto& displayDevice = pair.second;
2213 auto display = displayDevice->getCompositionDisplay();
2214 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 Region opaqueRegion;
2216 Region dirtyRegion;
2217 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002218 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002219 const ui::Transform& tr = displayState.transform;
2220 const Rect bounds = displayState.bounds;
2221 if (displayState.isEnabled) {
2222 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002223
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002225 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002226 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002227 if (display->belongsInOutput(layer->getLayerStack(),
2228 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002229 Region drawRegion(tr.transform(
2230 layer->visibleNonTransparentRegion));
2231 drawRegion.andSelf(bounds);
2232 if (!drawRegion.isEmpty()) {
2233 layersSortedByZ.add(layer);
2234 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002235 // Clear out the HWC layer if this layer was
2236 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002237 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002238 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002239 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002240 // WM changes display->layerStack upon sleep/awake.
2241 // Here we make sure we delete the HWC layers even if
2242 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002244 }
2245
2246 // If a layer is not going to get a release fence because
2247 // it is invisible, but it is also going to release its
2248 // old buffer, add it to the list of layers needing
2249 // fences.
2250 if (hwcLayerDestroyed) {
2251 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2252 mLayersWithQueuedFrames.cend(), layer);
2253 if (found != mLayersWithQueuedFrames.cend()) {
2254 layersNeedingFences.add(layer);
2255 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002256 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002257 });
2258 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002259 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2260 displayDevice->setLayersNeedingFences(layersNeedingFences);
2261
2262 Region undefinedRegion{bounds};
2263 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2264
2265 display->editState().undefinedRegion = undefinedRegion;
2266 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002268 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002269}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002270
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002271// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002273// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002275// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276// The returned HDR data space is one of
2277// - Dataspace::UNKNOWN
2278// - Dataspace::BT2020_HLG
2279// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2281 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002282 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 *outHdrDataSpace = Dataspace::UNKNOWN;
2284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002286 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002287 case Dataspace::V0_SCRGB:
2288 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002289 case Dataspace::BT2020:
2290 case Dataspace::BT2020_ITU:
2291 case Dataspace::BT2020_LINEAR:
2292 case Dataspace::DISPLAY_BT2020:
2293 bestDataSpace = Dataspace::DISPLAY_BT2020;
2294 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002295 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002296 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298 case Dataspace::BT2020_PQ:
2299 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002302 case Dataspace::BT2020_HLG:
2303 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 // When there's mixed PQ content and HLG content, we set the HDR
2305 // data space to be BT2020_PQ and convert HLG to PQ.
2306 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2307 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002308 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 break;
2310 default:
2311 break;
2312 }
Romain Guy54f154a2017-10-24 21:40:32 +01002313 }
2314
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002316}
2317
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2320 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2322 *outMode = ColorMode::NATIVE;
2323 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002324 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002326 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002327
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002331 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2332
Peiyong Lindfde5112018-06-05 10:58:41 -07002333 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002334 const bool isHdr =
2335 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002336 if (isHdr) {
2337 bestDataSpace = hdrDataSpace;
2338 }
2339
Chia-I Wu0d711262018-05-21 15:19:35 -07002340 RenderIntent intent;
2341 switch (mDisplayColorSetting) {
2342 case DisplayColorSetting::MANAGED:
2343 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002344 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002345 break;
2346 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002347 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002348 break;
2349 default: // vendor display color setting
2350 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2351 break;
2352 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002353
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002354 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002355}
2356
Lloyd Pique32cbe282018-10-19 13:09:22 -07002357void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2358 auto display = displayDevice->getCompositionDisplay();
2359 const auto& displayState = display->getState();
2360
2361 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2362 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2363 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002364
David Sodmanfa9b2af2017-12-24 13:28:59 -08002365 // If nothing has changed (!dirty), don't recompose.
2366 // If something changed, but we don't currently have any visible layers,
2367 // and didn't when we last did a composition, then skip it this time.
2368 // The second rule does two things:
2369 // - When all layers are removed from a display, we'll emit one black
2370 // frame, then nothing more until we get new layers.
2371 // - When a display is created with a private layer stack, we won't
2372 // emit any black frames until a layer is added to the layer stack.
2373 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002374
Dominik Laskowski075d3172018-05-24 15:50:06 -07002375 const char flagPrefix[] = {'-', '+'};
2376 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002377 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2378 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2379 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2380 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002381
Lloyd Pique31cb2942018-10-19 17:23:03 -07002382 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002383
David Sodmanfa9b2af2017-12-24 13:28:59 -08002384 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002386 }
2387}
2388
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2390 auto display = displayDevice->getCompositionDisplay();
2391 const auto& displayState = display->getState();
2392
2393 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394 return;
David Sodman2b406362017-12-15 13:33:47 -08002395 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396
Lloyd Pique31cb2942018-10-19 17:23:03 -07002397 status_t result = display->getRenderSurface()->prepareFrame(
2398 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002401}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002404 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 ALOGV("doComposition");
2406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 auto display = displayDevice->getCompositionDisplay();
2408 const auto& displayState = display->getState();
2409
2410 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002416
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002418 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421}
2422
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423void SurfaceFlinger::postFrame()
2424{
2425 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 const auto display = getDefaultDisplayDeviceLocked();
2427 if (display && getHwComposer().isConnected(*display->getId())) {
2428 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2430 logFrameStats();
2431 }
2432 }
2433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002436 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 auto display = displayDevice->getCompositionDisplay();
2440 const auto& displayState = display->getState();
2441 const auto displayId = display->getId();
2442
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002444
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002446 if (displayId) {
2447 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002448 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002449 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002451 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002452
Chia-I Wu7b549592017-11-15 09:14:57 -08002453 // The layer buffer from the previous frame (if any) is released
2454 // by HWC only when the release fence from this frame (if any) is
2455 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002456 if (displayId && layer->hasHwcLayer(*displayId)) {
2457 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2458 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002459 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002460
2461 // If the layer was client composited in the previous frame, we
2462 // need to merge with the previous client target acquire fence.
2463 // Since we do not track that, always merge with the current
2464 // client target acquire fence when it is available, even though
2465 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002466 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002467 releaseFence =
2468 Fence::merge("LayerRelease", releaseFence,
2469 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002470 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002471
David Sodman15094112018-10-11 09:39:37 -07002472 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 }
Chia-I Wu83806892017-11-16 10:50:20 -08002474
2475 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002477 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002479 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002480 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002482 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002483 }
2484 }
2485
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 if (displayId) {
2487 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002488 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490}
2491
Mathias Agopian87baae12012-07-31 12:38:26 -07002492void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493{
Mathias Agopian841cde52012-03-01 15:44:37 -08002494 ATRACE_CALL();
2495
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002496 // here we keep a copy of the drawing state (that is the state that's
2497 // going to be overwritten by handleTransactionLocked()) outside of
2498 // mStateLock so that the side-effects of the State assignment
2499 // don't happen with mStateLock held (which can cause deadlocks).
2500 State drawingState(mDrawingState);
2501
Mathias Agopianca4d3602011-05-19 15:38:14 -07002502 Mutex::Autolock _l(mStateLock);
2503 const nsecs_t now = systemTime();
2504 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505
Mathias Agopianca4d3602011-05-19 15:38:14 -07002506 // Here we're guaranteed that some transaction flags are set
2507 // so we can call handleTransactionLocked() unconditionally.
2508 // We call getTransactionFlags(), which will also clear the flags,
2509 // with mStateLock held to guarantee that mCurrentState won't change
2510 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002511
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002512 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002513 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002514 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002515
Mathias Agopianca4d3602011-05-19 15:38:14 -07002516 mLastTransactionTime = systemTime() - now;
2517 mDebugInTransaction = 0;
2518 invalidateHwcGeometry();
2519 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002520}
2521
Lloyd Piqueba04e622017-12-14 17:11:26 -08002522void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2523 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 const std::optional<DisplayIdentificationInfo> info =
2525 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002526
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 continue;
2529 }
2530
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002533 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 mPhysicalDisplayTokens[info->id] = new BBinder();
2535 DisplayDeviceState state;
2536 state.displayId = info->id;
2537 state.isSecure = true; // All physical displays are currently considered secure.
2538 state.displayName = info->name;
2539 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2540 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002541 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002542 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002543 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2546 if (index >= 0) {
2547 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2548 mInterceptor->saveDisplayDeletion(state.sequenceId);
2549 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552 }
2553
2554 processDisplayChangesLocked();
2555 }
2556
2557 mPendingHotplugEvents.clear();
2558}
2559
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002560void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2561 bool connected) {
2562 if (mUseScheduler) {
2563 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2564 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2565 } else {
2566 mEventThread->onHotplugReceived(displayType, connected);
2567 mSFEventThread->onHotplugReceived(displayType, connected);
2568 }
2569}
2570
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002572 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002573 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 const sp<IGraphicBufferProducer>& producer) {
2575 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002576 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002578 creationArgs.isSecure = state.isSecure;
2579 creationArgs.displaySurface = dispSurface;
2580 creationArgs.hasWideColorGamut = false;
2581 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002582
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2584 creationArgs.isPrimary = isInternalDisplay;
2585
2586 if (useColorManagement && displayId) {
2587 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002589 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002590 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002592
Dominik Laskowski7e045462018-05-30 13:02:02 -07002593 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596 }
tangrobin6753a022018-08-10 10:58:54 +08002597 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 if (displayId) {
2600 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002603 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604
Lloyd Pique90c115d2018-09-18 21:39:42 -07002605 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002607 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609 // Make sure that composition can never be stalled by a virtual display
2610 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002611 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002612 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2614 }
2615
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 creationArgs.displayInstallOrientation =
2617 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002618
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621
Lloyd Pique90c115d2018-09-18 21:39:42 -07002622 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623
2624 if (maxFrameBufferAcquiredBuffers >= 3) {
2625 nativeWindowSurface->preallocateBuffers();
2626 }
2627
2628 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002629 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002630 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002631 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002632 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002634 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2635 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 if (!state.isVirtual()) {
2637 LOG_ALWAYS_FATAL_IF(!displayId);
2638 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002639 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002641 display->setLayerStack(state.layerStack);
2642 display->setProjection(state.orientation, state.viewport, state.frame);
2643 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646}
2647
Lloyd Pique347200f2017-12-14 17:00:15 -08002648void SurfaceFlinger::processDisplayChangesLocked() {
2649 // here we take advantage of Vector's copy-on-write semantics to
2650 // improve performance by skipping the transaction entirely when
2651 // know that the lists are identical
2652 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2653 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2654 if (!curr.isIdenticalTo(draw)) {
2655 mVisibleRegionsDirty = true;
2656 const size_t cc = curr.size();
2657 size_t dc = draw.size();
2658
2659 // find the displays that were removed
2660 // (ie: in drawing state but not in current state)
2661 // also handle displays that changed
2662 // (ie: displays that are in both lists)
2663 for (size_t i = 0; i < dc;) {
2664 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2665 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 // Save display IDs before disconnecting.
2667 const auto internalDisplayId = getInternalDisplayId();
2668 const auto externalDisplayId = getExternalDisplayId();
2669
Lloyd Pique347200f2017-12-14 17:00:15 -08002670 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002671 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002672 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002674 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002675 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002677 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002678 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 } else {
2681 // this display is in both lists. see if something changed.
2682 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2685 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2686 if (state_binder != draw_binder) {
2687 // changing the surface is like destroying and
2688 // recreating the DisplayDevice, so we just remove it
2689 // from the drawing state, so that it get re-added
2690 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002692 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002695 mDrawingState.displays.removeItemsAt(i);
2696 dc--;
2697 // at this point we must loop to the next item
2698 continue;
2699 }
2700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705 if ((state.orientation != draw[i].orientation) ||
2706 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
2709 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712 }
2713 }
2714 ++i;
2715 }
2716
2717 // find displays that were added
2718 // (ie: in current state but not in drawing state)
2719 for (size_t i = 0; i < cc; i++) {
2720 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2721 const DisplayDeviceState& state(curr[i]);
2722
Lloyd Pique542307f2018-10-19 13:24:08 -07002723 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 sp<IGraphicBufferProducer> producer;
2725 sp<IGraphicBufferProducer> bqProducer;
2726 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002727 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002730 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 // Virtual displays without a surface are dormant:
2732 // they have external state (layer stack, projection,
2733 // etc.) but no internal state (i.e. a DisplayDevice).
2734 if (state.surface != nullptr) {
2735 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 int width = 0;
2738 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2739 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2740 int height = 0;
2741 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2742 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2743 int intFormat = 0;
2744 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2745 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002746 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 displayId =
2749 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 }
2751
2752 // TODO: Plumb requested format back up to consumer
2753
2754 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 bqProducer, bqConsumer,
2757 state.displayName);
2758
2759 dispSurface = vds;
2760 producer = vds;
2761 }
2762 } else {
2763 ALOGE_IF(state.surface != nullptr,
2764 "adding a supported display, but rendering "
2765 "surface is provided (%p), ignoring it",
2766 state.surface.get());
2767
Dominik Laskowski075d3172018-05-24 15:50:06 -07002768 displayId = state.displayId;
2769 LOG_ALWAYS_FATAL_IF(!displayId);
2770 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 producer = bqProducer;
2772 }
2773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002777 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002779 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 LOG_ALWAYS_FATAL_IF(!displayId);
2781
2782 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002783 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002784 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002785 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002786 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 }
2788 }
2789 }
2790 }
2791 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002792
2793 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002794}
2795
Mathias Agopian87baae12012-07-31 12:38:26 -07002796void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002797{
Dan Stoza7dde5992015-05-22 09:51:44 -07002798 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002799 mCurrentState.traverseInZOrder([](Layer* layer) {
2800 layer->notifyAvailableFrames();
2801 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 /*
2804 * Traversal of the children
2805 * (perform the transaction for each of them if needed)
2806 */
2807
Robert Carr720e5062018-07-30 17:45:14 -07002808 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002809 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002812 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813
2814 const uint32_t flags = layer->doTransaction(0);
2815 if (flags & Layer::eVisibleRegion)
2816 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002817
2818 if (flags & Layer::eInputInfoChanged) {
2819 inputChanged = true;
2820 }
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 }
2823
2824 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002825 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 */
2827
Mathias Agopiane57f2922012-08-09 16:29:12 -07002828 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002829 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002830 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002834 // The transform hint might have changed for some layers
2835 // (either because a display has changed, or because a layer
2836 // as changed).
2837 //
2838 // Walk through all the layers in currentLayers,
2839 // and update their transform hint.
2840 //
2841 // If a layer is visible only on a single display, then that
2842 // display is used to calculate the hint, otherwise we use the
2843 // default display.
2844 //
2845 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2846 // the hint is set before we acquire a buffer from the surface texture.
2847 //
2848 // NOTE: layer transactions have taken place already, so we use their
2849 // drawing state. However, SurfaceFlinger's own transaction has not
2850 // happened yet, so we must use the current state layer list
2851 // (soon to become the drawing state list).
2852 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002854 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002855 bool first = true;
2856 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002857 // NOTE: we rely on the fact that layers are sorted by
2858 // layerStack first (so we don't have to traverse the list
2859 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002861 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002862 currentlayerStack = layerStack;
2863 // figure out if this layerstack is mirrored
2864 // (more than one display) if so, pick the default display,
2865 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 hintDisplay = nullptr;
2867 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002868 if (display->getCompositionDisplay()
2869 ->belongsInOutput(layer->getLayerStack(),
2870 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 if (hintDisplay) {
2872 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002873 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002875 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002876 }
2877 }
2878 }
2879 }
Chet Haase91d25932013-04-11 15:24:55 -07002880
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002882 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2883 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002884
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002885 // could be null when this layer is using a layerStack
2886 // that is not visible on any display. Also can occur at
2887 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002889 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002891 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002892 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 if (hintDisplay) {
2894 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002895 }
Robert Carr2047fae2016-11-28 14:09:09 -08002896
2897 first = false;
2898 });
Mathias Agopian84300952012-11-21 16:02:13 -08002899 }
2900
2901
Mathias Agopian3559b072012-08-15 13:46:03 -07002902 /*
2903 * Perform our own transaction if needed
2904 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905
2906 if (mLayersAdded) {
2907 mLayersAdded = false;
2908 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002909 mVisibleRegionsDirty = true;
2910 }
2911
2912 // some layers might have been removed, so
2913 // we need to update the regions they're exposing.
2914 if (mLayersRemoved) {
2915 mLayersRemoved = false;
2916 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002917 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002919 // this layer is not visible anymore
2920 // TODO: we could traverse the tree from front to back and
2921 // compute the actual visible region
2922 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 Region visibleReg;
2924 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002925 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002926 }
Robert Carr2047fae2016-11-28 14:09:09 -08002927 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 }
2929
2930 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002931
Vishnu Nairde19f852018-12-18 16:11:53 -08002932 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002933 updateInputWindows();
2934 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002935 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002936
Riley Andrews03414a12014-07-01 14:22:59 -07002937 updateCursorAsync();
2938}
2939
Robert Carr720e5062018-07-30 17:45:14 -07002940void SurfaceFlinger::updateInputWindows() {
2941 ATRACE_CALL();
2942
Vishnu Nairde19f852018-12-18 16:11:53 -08002943 if (mInputFlinger == nullptr) {
2944 return;
2945 }
2946
Robert Carr720e5062018-07-30 17:45:14 -07002947 Vector<InputWindowInfo> inputHandles;
2948
2949 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2950 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002951 // When calculating the screen bounds we ignore the transparent region since it may
2952 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002953 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002954 }
2955 });
2956 mInputFlinger->setInputWindows(inputHandles);
2957}
2958
chaviwfbe5d9c2018-12-26 12:23:37 -08002959void SurfaceFlinger::executeInputWindowCommands() {
2960 if (!mInputFlinger) {
2961 return;
2962 }
2963
2964 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2965 if (transferTouchFocusCommand.fromToken != nullptr &&
2966 transferTouchFocusCommand.toToken != nullptr &&
2967 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2968 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2969 transferTouchFocusCommand.toToken);
2970 }
2971 }
2972
2973 mInputWindowCommands.clear();
2974}
2975
Riley Andrews03414a12014-07-01 14:22:59 -07002976void SurfaceFlinger::updateCursorAsync()
2977{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002978 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002979 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002980 continue;
2981 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2984 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002985 }
2986 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987}
2988
chaviw61626f22018-11-15 16:26:27 -08002989void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2990 if (layer->hasReadyFrame()) {
2991 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2992 if (layer->shouldPresentNow(expectedPresentTime)) {
2993 bool ignored = false;
2994 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2995 }
2996 }
2997 layer->releasePendingBuffer(systemTime());
2998}
2999
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000void SurfaceFlinger::commitTransaction()
3001{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003002 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003003 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 for (const auto& l : mLayersPendingRemoval) {
3005 recordBufferingStats(l->getName().string(),
3006 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003007
3008 // We need to release the HWC layers when the Layer is removed
3009 // from the current state otherwise the HWC layer just continues
3010 // showing at its last configured state until we eventually
3011 // abandon the buffer queue.
3012 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003013 l->destroyHwcLayersForAllDisplays();
3014 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003015 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003016 }
3017 mLayersPendingRemoval.clear();
3018 }
3019
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003020 // If this transaction is part of a window animation then the next frame
3021 // we composite should be considered an animation as well.
3022 mAnimCompositionPending = mAnimTransactionPending;
3023
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003025 // clear the "changed" flags in current state
3026 mCurrentState.colorMatrixChanged = false;
3027
Robert Carr1f0a16a2016-10-24 16:27:39 -07003028 mDrawingState.traverseInZOrder([](Layer* layer) {
3029 layer->commitChildList();
3030 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003031 mTransactionPending = false;
3032 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003033 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034}
3035
Lloyd Pique32cbe282018-10-19 13:09:22 -07003036void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003038 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003040
Lloyd Pique32cbe282018-10-19 13:09:22 -07003041 auto display = displayDevice->getCompositionDisplay();
3042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 Region aboveOpaqueLayers;
3044 Region aboveCoveredLayers;
3045 Region dirty;
3046
Mathias Agopian87baae12012-07-31 12:38:26 -07003047 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048
Robert Carr2047fae2016-11-28 14:09:09 -08003049 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003050 // start with the whole surface at its current location
3051 const Layer::State& s(layer->getDrawingState());
3052
Jesse Hall01e29052013-02-19 16:13:35 -08003053 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003054 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003055 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003056 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003057
Mathias Agopianab028732010-03-16 16:41:46 -07003058 /*
3059 * opaqueRegion: area of a surface that is fully opaque.
3060 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003062
3063 /*
3064 * visibleRegion: area of a surface that is visible on screen
3065 * and not fully transparent. This is essentially the layer's
3066 * footprint minus the opaque regions above it.
3067 * Areas covered by a translucent surface are considered visible.
3068 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003070
3071 /*
3072 * coveredRegion: area of a surface that is covered by all
3073 * visible regions above it (which includes the translucent areas).
3074 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003076
Jesse Halla8026d22012-09-25 13:25:04 -07003077 /*
3078 * transparentRegion: area of a surface that is hinted to be completely
3079 * transparent. This is only used to tell when the layer has no visible
3080 * non-transparent regions and can be removed from the layer list. It
3081 * does not affect the visibleRegion of this layer or any layers
3082 * beneath it. The hint may not be correct if apps don't respect the
3083 * SurfaceView restrictions (which, sadly, some don't).
3084 */
3085 Region transparentRegion;
3086
Mathias Agopianab028732010-03-16 16:41:46 -07003087
3088 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003089 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003090 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003094 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003095 if (!visibleRegion.isEmpty()) {
3096 // Remove the transparent area from the visible region
3097 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003098 if (tr.preserveRects()) {
3099 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003100 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003101 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003102 // transformation too complex, can't do the
3103 // transparent region optimization.
3104 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 }
Mathias Agopianab028732010-03-16 16:41:46 -07003106 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107
Mathias Agopianab028732010-03-16 16:41:46 -07003108 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003110 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003111 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003112 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003113 // the opaque region is the layer's footprint
3114 opaqueRegion = visibleRegion;
3115 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 }
3117 }
3118
Robert Carre5f4f692018-01-12 13:12:28 -08003119 if (visibleRegion.isEmpty()) {
3120 layer->clearVisibilityRegions();
3121 return;
3122 }
3123
Mathias Agopianab028732010-03-16 16:41:46 -07003124 // Clip the covered region to the visible region
3125 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3126
3127 // Update aboveCoveredLayers for next (lower) layer
3128 aboveCoveredLayers.orSelf(visibleRegion);
3129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 // subtract the opaque region covered by the layers above us
3131 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132
3133 // compute this layer's dirty region
3134 if (layer->contentDirty) {
3135 // we need to invalidate the whole region
3136 dirty = visibleRegion;
3137 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003138 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 layer->contentDirty = false;
3140 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003141 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003142 * the exposed region consists of two components:
3143 * 1) what's VISIBLE now and was COVERED before
3144 * 2) what's EXPOSED now less what was EXPOSED before
3145 *
3146 * note that (1) is conservative, we start with the whole
3147 * visible region but only keep what used to be covered by
3148 * something -- which mean it may have been exposed.
3149 *
3150 * (2) handles areas that were not covered by anything but got
3151 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003152 */
Mathias Agopianab028732010-03-16 16:41:46 -07003153 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003154 const Region oldVisibleRegion = layer->visibleRegion;
3155 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003156 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3157 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 }
3159 dirty.subtractSelf(aboveOpaqueLayers);
3160
3161 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003162 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163
Mathias Agopianab028732010-03-16 16:41:46 -07003164 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003166
Jesse Halla8026d22012-09-25 13:25:04 -07003167 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 layer->setVisibleRegion(visibleRegion);
3169 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003170 layer->setVisibleNonTransparentRegion(
3171 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003172 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173
Mathias Agopian87baae12012-07-31 12:38:26 -07003174 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175}
3176
Chia-I Wuab0c3192017-08-01 11:29:00 -07003177void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003178 for (const auto& [token, displayDevice] : mDisplays) {
3179 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003180 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003181 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003182 }
3183 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003184}
3185
Dan Stoza6b9454d2014-11-07 16:00:59 -08003186bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003188 ALOGV("handlePageFlip");
3189
Brian Andersond6927fb2016-07-23 23:37:30 -07003190 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003193 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003194 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003195
3196 // Store the set of layers that need updates. This set must not change as
3197 // buffers are being latched, as this could result in a deadlock.
3198 // Example: Two producers share the same command stream and:
3199 // 1.) Layer 0 is latched
3200 // 2.) Layer 0 gets a new frame
3201 // 2.) Layer 1 gets a new frame
3202 // 3.) Layer 1 is latched.
3203 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3204 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003206 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003207 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003208 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3209 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003211 } else {
3212 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003213 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003214 } else {
3215 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003216 }
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
3218
Lloyd Piquef2c79392018-12-20 16:23:33 -08003219 if (!mLayersWithQueuedFrames.empty()) {
3220 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3221 // writes to Layer current state. See also b/119481871
3222 Mutex::Autolock lock(mStateLock);
3223
3224 for (auto& layer : mLayersWithQueuedFrames) {
3225 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3226 layer->useSurfaceDamage();
3227 invalidateLayerStack(layer, dirty);
3228 if (layer->isBufferLatched()) {
3229 newDataLatched = true;
3230 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003231 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003232 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003233
Alec Mouri86770e52018-09-24 22:40:58 +00003234 // Clear the renderengine fence here...
3235 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3236 // clear instead of sp::clear.
3237 getBE().flushFence = Fence::NO_FENCE;
3238
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003239 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240
Vishnu Nairde19f852018-12-18 16:11:53 -08003241 if (visibleRegions) {
3242 // Update input window info if the layer receives its first buffer.
3243 updateInputWindows();
3244 }
3245
Dan Stoza6b9454d2014-11-07 16:00:59 -08003246 // If we will need to wake up at some time in the future to deal with a
3247 // queued frame that shouldn't be displayed during this vsync period, wake
3248 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003249 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 signalLayerUpdate();
3251 }
3252
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003253 // enter boot animation on first buffer latch
3254 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3255 ALOGI("Enter boot animation");
3256 mBootStage = BootStage::BOOTANIMATION;
3257 }
3258
Dan Stoza6b9454d2014-11-07 16:00:59 -08003259 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003260 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261}
3262
Mathias Agopianad456f92011-01-13 17:53:01 -08003263void SurfaceFlinger::invalidateHwcGeometry()
3264{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003265 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003266}
3267
Lloyd Pique32cbe282018-10-19 13:09:22 -07003268void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003269 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003270 auto display = displayDevice->getCompositionDisplay();
3271
Dan Stoza71433162014-02-04 16:22:36 -08003272 // We only need to actually compose the display if:
3273 // 1) It is being handled by hardware composer, which may need this to
3274 // keep its virtual display state machine in sync, or
3275 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003276 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003277 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003278 return;
3279 }
3280
Dan Stoza9e56aa02015-11-02 13:00:03 -08003281 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003282 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003283
3284 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003285 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286}
3287
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003289 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003290
Lloyd Pique32cbe282018-10-19 13:09:22 -07003291 auto display = displayDevice->getCompositionDisplay();
3292 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003293 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003294
3295 const Region bounds(displayState.bounds);
3296 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003297 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003298 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003299
Peiyong Lind3788632018-09-18 16:01:31 -07003300 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003301 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003302
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003303 // Framebuffer will live in this scope for GPU composition.
3304 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3305
Dan Stoza9e56aa02015-11-02 13:00:03 -08003306 if (hasClientComposition) {
3307 ALOGV("hasClientComposition");
3308
Lloyd Pique31cb2942018-10-19 17:23:03 -07003309 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310
3311 if (buf == nullptr) {
3312 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3313 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003314 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003315 return false;
3316 }
3317
3318 // Bind the framebuffer in this scope.
3319 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3320 buf->getNativeBuffer());
3321
3322 if (fbo->getStatus() != NO_ERROR) {
3323 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003324 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003325 return false;
3326 }
3327
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003328 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003329 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003330 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003332 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003333 getRenderEngine().setOutputDataSpace(outputDataspace);
3334 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003335 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003336
Lloyd Pique441d5042018-10-18 16:49:51 -07003337 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003338 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003339 getHwComposer()
3340 .hasDisplayCapability(displayId,
3341 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003342
Peiyong Lind3788632018-09-18 16:01:31 -07003343 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003344 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3345 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003346 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003347 }
3348
Lloyd Pique31cb2942018-10-19 17:23:03 -07003349 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003350
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003351 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003352 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003353 // when using overlays, we assume a fully transparent framebuffer
3354 // NOTE: we could reduce how much we need to clear, for instance
3355 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003356 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003357 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003358 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003359 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003360 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003361 // we're left with the letterbox region
3362 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003363 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003364
3365 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003366 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003367
Mathias Agopianb9494d52012-04-18 02:28:45 -07003368 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003369 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003370 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003371 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003372 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003373 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003374
Lloyd Pique32cbe282018-10-19 13:09:22 -07003375 const Rect& bounds = displayState.bounds;
3376 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003377 if (scissor != bounds) {
3378 // scissor doesn't match the screen's dimensions, so we
3379 // need to clear everything outside of it and enable
3380 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003381
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003382 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003383 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003384 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003385 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003386
Mathias Agopian85d751c2012-08-29 16:59:24 -07003387 /*
3388 * and then, render the layers targeted at the framebuffer
3389 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003390
Dan Stoza9e56aa02015-11-02 13:00:03 -08003391 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003392 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003393 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003394 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003395 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003396 displayTransform.transform(layer->visibleRegion)));
3397 ALOGV("Layer: %s", layer->getName().string());
3398 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003399 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003400 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 case HWC2::Composition::Cursor:
3402 case HWC2::Composition::Device:
3403 case HWC2::Composition::Sideband:
3404 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003405 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003406 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003407 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003408 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003409 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 // never clear the very first layer since we're
3411 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003412 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003413 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003415 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003417 if (layer->hasColorTransform()) {
3418 mat4 tmpMatrix;
3419 if (applyColorMatrix) {
3420 tmpMatrix = mDrawingState.colorMatrix;
3421 }
3422 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003423 getRenderEngine().setColorTransform(tmpMatrix);
3424 } else {
3425 getRenderEngine().setColorTransform(colorMatrix);
3426 }
David Sodmanc1498e62018-09-12 14:36:26 -07003427 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003428 break;
3429 }
3430 default:
3431 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003432 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 } else {
3434 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003435 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003436 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003437 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003438
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003439 // Perform some cleanup steps if we used client composition.
3440 if (hasClientComposition) {
3441 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003442 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003443 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003444 // Clear out error flags here so that we don't wait until next
3445 // composition to log.
3446 getRenderEngine().checkErrors();
3447 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003448 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449}
3450
Chia-I Wu28e3a252018-09-07 12:05:02 -07003451void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003452 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003453 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454}
3455
Dan Stoza7d89d062015-04-30 13:29:25 -07003456status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003457 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003458 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003459 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003460 const sp<Layer>& parent,
3461 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003462{
Dan Stoza7d89d062015-04-30 13:29:25 -07003463 // add this layer to the current state list
3464 {
3465 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003467 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3468 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 return NO_MEMORY;
3470 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003471 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003472 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003473 } else if (parent == nullptr) {
3474 lbc->onRemovedFromCurrentState();
3475 } else if (parent->isRemovedFromCurrentState()) {
3476 parent->addChild(lbc);
3477 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003478 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 parent->addChild(lbc);
3480 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003481
Yiwei Zhang243b3782018-05-15 17:40:04 -07003482 if (gbc != nullptr) {
3483 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3484 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3485 mMaxGraphicBufferProducerListSize,
3486 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3487 mGraphicBufferProducerList.size(),
3488 mMaxGraphicBufferProducerListSize, mNumLayers);
3489 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003490 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003491 }
3492
Mathias Agopian96f08192010-06-02 23:28:45 -07003493 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003494 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003495
Dan Stoza7d89d062015-04-30 13:29:25 -07003496 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003497}
3498
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003499uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003500 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003501}
3502
Mathias Agopian3f844832013-08-07 21:24:32 -07003503uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003504 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505}
3506
Mathias Agopian3f844832013-08-07 21:24:32 -07003507uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003508 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003509}
3510
3511uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003512 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003513 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003514 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003516 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 }
3518 return old;
3519}
3520
Marissa Wall713b63f2018-10-17 15:42:43 -07003521bool SurfaceFlinger::flushTransactionQueues() {
3522 Mutex::Autolock _l(mStateLock);
3523 auto it = mTransactionQueues.begin();
3524 while (it != mTransactionQueues.end()) {
3525 auto& [applyToken, transactionQueue] = *it;
3526
3527 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003528 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3529 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003530 break;
3531 }
chaviw273171b2018-12-26 11:46:30 -08003532 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003533 transactionQueue.pop();
3534 }
3535
3536 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3537 }
3538 return mTransactionQueues.empty();
3539}
3540
chaviwca27f252018-02-06 16:46:39 -08003541bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3542 for (const ComposerState& state : states) {
3543 // Here we need to check that the interface we're given is indeed
3544 // one of our own. A malicious client could give us a nullptr
3545 // IInterface, or one of its own or even one of our own but a
3546 // different type. All these situations would cause us to crash.
3547 if (state.client == nullptr) {
3548 return true;
3549 }
3550
3551 sp<IBinder> binder = IInterface::asBinder(state.client);
3552 if (binder == nullptr) {
3553 return true;
3554 }
3555
3556 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3557 return true;
3558 }
3559 }
3560 return false;
3561}
3562
Marissa Wall17b4e452018-12-26 16:32:34 -08003563bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3564 const Vector<ComposerState>& states) {
3565 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3566 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3567 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3568 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3569 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3570 return false;
3571 }
3572
Marissa Wall713b63f2018-10-17 15:42:43 -07003573 for (const ComposerState& state : states) {
3574 const layer_state_t& s = state.state;
3575 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3576 continue;
3577 }
3578 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003579 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003580 }
3581 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003582 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003583}
3584
3585void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3586 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003587 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003588 const InputWindowCommands& inputWindowCommands,
3589 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003590 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003591 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003592
chaviwca27f252018-02-06 16:46:39 -08003593 if (containsAnyInvalidClientState(states)) {
3594 return;
3595 }
3596
Marissa Wall713b63f2018-10-17 15:42:43 -07003597 // If its TransactionQueue already has a pending TransactionState or if it is pending
3598 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003599 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3600 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 setTransactionFlags(eTransactionNeeded);
3602 return;
3603 }
3604
chaviw273171b2018-12-26 11:46:30 -08003605 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003606}
3607
3608void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003609 const Vector<DisplayState>& displays, uint32_t flags,
3610 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003611 uint32_t transactionFlags = 0;
3612
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003613 if (flags & eAnimation) {
3614 // For window updates that are part of an animation we must wait for
3615 // previous animation "frames" to be handled.
3616 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003617 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003618 if (CC_UNLIKELY(err != NO_ERROR)) {
3619 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003620 // caller after a few seconds.
3621 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3622 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003623 mAnimTransactionPending = false;
3624 break;
3625 }
3626 }
3627 }
3628
chaviwca27f252018-02-06 16:46:39 -08003629 for (const DisplayState& display : displays) {
3630 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003631 }
3632
Marissa Walle2ffb422018-10-12 11:33:52 -07003633 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003634 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003635 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003636 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003637 // If the state doesn't require a traversal and there are callbacks, send them now
3638 if (!(clientStateFlags & eTraversalNeeded)) {
3639 mTransactionCompletedThread.sendCallbacks();
3640 }
3641 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003642
chaviw273171b2018-12-26 11:46:30 -08003643 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3644
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003645 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3646 // anyway. This can be used as a flush mechanism for previous async transactions.
3647 // Empty animation transaction can be used to simulate back-pressure, so also force a
3648 // transaction for empty animation transactions.
3649 if (transactionFlags == 0 &&
3650 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003651 transactionFlags = eTransactionNeeded;
3652 }
3653
Mathias Agopian386aa982011-11-07 21:58:03 -08003654 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003655 if (mInterceptor->isEnabled()) {
3656 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003657 }
Irvel468051e2016-06-13 16:44:44 -07003658
Mathias Agopian386aa982011-11-07 21:58:03 -08003659 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003660 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3661 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003662 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003663
3664 // if this is a synchronous transaction, wait for it to take effect
3665 // before returning.
3666 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003667 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003668 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003669 if (flags & eAnimation) {
3670 mAnimTransactionPending = true;
3671 }
3672 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003673 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3674 if (CC_UNLIKELY(err != NO_ERROR)) {
3675 // just in case something goes wrong in SF, return to the
3676 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003677 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3678 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003679 break;
3680 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003681 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682 }
3683}
3684
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003685uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3686 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3687 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003688
Mathias Agopiane57f2922012-08-09 16:29:12 -07003689 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003690 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3691
3692 const uint32_t what = s.what;
3693 if (what & DisplayState::eSurfaceChanged) {
3694 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3695 state.surface = s.surface;
3696 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003697 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003698 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003699 if (what & DisplayState::eLayerStackChanged) {
3700 if (state.layerStack != s.layerStack) {
3701 state.layerStack = s.layerStack;
3702 flags |= eDisplayTransactionNeeded;
3703 }
3704 }
3705 if (what & DisplayState::eDisplayProjectionChanged) {
3706 if (state.orientation != s.orientation) {
3707 state.orientation = s.orientation;
3708 flags |= eDisplayTransactionNeeded;
3709 }
3710 if (state.frame != s.frame) {
3711 state.frame = s.frame;
3712 flags |= eDisplayTransactionNeeded;
3713 }
3714 if (state.viewport != s.viewport) {
3715 state.viewport = s.viewport;
3716 flags |= eDisplayTransactionNeeded;
3717 }
3718 }
3719 if (what & DisplayState::eDisplaySizeChanged) {
3720 if (state.width != s.width) {
3721 state.width = s.width;
3722 flags |= eDisplayTransactionNeeded;
3723 }
3724 if (state.height != s.height) {
3725 state.height = s.height;
3726 flags |= eDisplayTransactionNeeded;
3727 }
3728 }
3729
Mathias Agopiane57f2922012-08-09 16:29:12 -07003730 return flags;
3731}
3732
Robert Carrd4ae7f32018-06-07 16:10:57 -07003733bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3734 IPCThreadState* ipc = IPCThreadState::self();
3735 const int pid = ipc->getCallingPid();
3736 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003737 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003738 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003739 return false;
3740 }
3741 return true;
3742}
3743
chaviwca27f252018-02-06 16:46:39 -08003744uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3745 const layer_state_t& s = composerState.state;
3746 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3747
Mathias Agopian13127d82013-03-05 17:47:11 -08003748 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003749 if (layer == nullptr) {
3750 return 0;
3751 }
3752
chaviw8b3871a2017-11-01 17:41:01 -07003753 uint32_t flags = 0;
3754
Garfield Tan8a3083e2018-12-03 13:21:07 -08003755 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003756 bool geometryAppliesWithResize =
3757 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003758
3759 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3760 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003761 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003762 layer->pushPendingState();
3763 }
3764
chaviw8b3871a2017-11-01 17:41:01 -07003765 if (what & layer_state_t::ePositionChanged) {
3766 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3767 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003768 }
chaviw8b3871a2017-11-01 17:41:01 -07003769 }
3770 if (what & layer_state_t::eLayerChanged) {
3771 // NOTE: index needs to be calculated before we update the state
3772 const auto& p = layer->getParent();
3773 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003774 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003775 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003776 mCurrentState.layersSortedByZ.removeAt(idx);
3777 mCurrentState.layersSortedByZ.add(layer);
3778 // we need traversal (state changed)
3779 // AND transaction (list changed)
3780 flags |= eTransactionNeeded|eTraversalNeeded;
3781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 } else {
3783 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003784 flags |= eTransactionNeeded|eTraversalNeeded;
3785 }
3786 }
chaviw8b3871a2017-11-01 17:41:01 -07003787 }
3788 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003789 // NOTE: index needs to be calculated before we update the state
3790 const auto& p = layer->getParent();
3791 if (p == nullptr) {
3792 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3793 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3794 mCurrentState.layersSortedByZ.removeAt(idx);
3795 mCurrentState.layersSortedByZ.add(layer);
3796 // we need traversal (state changed)
3797 // AND transaction (list changed)
3798 flags |= eTransactionNeeded|eTraversalNeeded;
3799 }
3800 } else {
3801 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3802 flags |= eTransactionNeeded|eTraversalNeeded;
3803 }
chaviw8b3871a2017-11-01 17:41:01 -07003804 }
3805 }
3806 if (what & layer_state_t::eSizeChanged) {
3807 if (layer->setSize(s.w, s.h)) {
3808 flags |= eTraversalNeeded;
3809 }
3810 }
3811 if (what & layer_state_t::eAlphaChanged) {
3812 if (layer->setAlpha(s.alpha))
3813 flags |= eTraversalNeeded;
3814 }
3815 if (what & layer_state_t::eColorChanged) {
3816 if (layer->setColor(s.color))
3817 flags |= eTraversalNeeded;
3818 }
Valerie Haued54efa2019-01-11 20:03:14 -08003819 if (what & layer_state_t::eColorAlphaChanged) {
3820 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3821 }
3822 if (what & layer_state_t::eColorDataspaceChanged) {
3823 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3824 }
Peiyong Lind3788632018-09-18 16:01:31 -07003825 if (what & layer_state_t::eColorTransformChanged) {
3826 if (layer->setColorTransform(s.colorTransform)) {
3827 flags |= eTraversalNeeded;
3828 }
3829 }
chaviw8b3871a2017-11-01 17:41:01 -07003830 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003831 // TODO: b/109894387
3832 //
3833 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3834 // rotation. To see the problem observe that if we have a square parent, and a child
3835 // of the same size, then we rotate the child 45 degrees around it's center, the child
3836 // must now be cropped to a non rectangular 8 sided region.
3837 //
3838 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3839 // private API, and the WindowManager only uses rotation in one case, which is on a top
3840 // level layer in which cropping is not an issue.
3841 //
3842 // However given that abuse of rotation matrices could lead to surfaces extending outside
3843 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3844 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3845 // transformations.
3846 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003847 flags |= eTraversalNeeded;
3848 }
3849 if (what & layer_state_t::eTransparentRegionChanged) {
3850 if (layer->setTransparentRegionHint(s.transparentRegion))
3851 flags |= eTraversalNeeded;
3852 }
3853 if (what & layer_state_t::eFlagsChanged) {
3854 if (layer->setFlags(s.flags, s.mask))
3855 flags |= eTraversalNeeded;
3856 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003857 if (what & layer_state_t::eCropChanged_legacy) {
3858 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003859 flags |= eTraversalNeeded;
3860 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003861 if (what & layer_state_t::eCornerRadiusChanged) {
3862 if (layer->setCornerRadius(s.cornerRadius))
3863 flags |= eTraversalNeeded;
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 if (what & layer_state_t::eLayerStackChanged) {
3866 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3867 // We only allow setting layer stacks for top level layers,
3868 // everything else inherits layer stack from its parent.
3869 if (layer->hasParent()) {
3870 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3871 layer->getName().string());
3872 } else if (idx < 0) {
3873 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3874 "that also does not appear in the top level layer list. Something"
3875 " has gone wrong.", layer->getName().string());
3876 } else if (layer->setLayerStack(s.layerStack)) {
3877 mCurrentState.layersSortedByZ.removeAt(idx);
3878 mCurrentState.layersSortedByZ.add(layer);
3879 // we need traversal (state changed)
3880 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003881 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003882 }
3883 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003884 if (what & layer_state_t::eDeferTransaction_legacy) {
3885 if (s.barrierHandle_legacy != nullptr) {
3886 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3887 } else if (s.barrierGbp_legacy != nullptr) {
3888 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003889 if (authenticateSurfaceTextureLocked(gbp)) {
3890 const auto& otherLayer =
3891 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003892 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003893 } else {
3894 ALOGE("Attempt to defer transaction to to an"
3895 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003896 }
3897 }
chaviw8b3871a2017-11-01 17:41:01 -07003898 // We don't trigger a traversal here because if no other state is
3899 // changed, we don't want this to cause any more work
3900 }
3901 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003902 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003903 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003904 if (!hadParent) {
3905 mCurrentState.layersSortedByZ.remove(layer);
3906 }
chaviw8b3871a2017-11-01 17:41:01 -07003907 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003908 }
chaviw8b3871a2017-11-01 17:41:01 -07003909 }
3910 if (what & layer_state_t::eReparentChildren) {
3911 if (layer->reparentChildren(s.reparentHandle)) {
3912 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003913 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003914 }
chaviw8b3871a2017-11-01 17:41:01 -07003915 if (what & layer_state_t::eDetachChildren) {
3916 layer->detachChildren();
3917 }
3918 if (what & layer_state_t::eOverrideScalingModeChanged) {
3919 layer->setOverrideScalingMode(s.overrideScalingMode);
3920 // We don't trigger a traversal here because if no other state is
3921 // changed, we don't want this to cause any more work
3922 }
Marissa Wall61c58622018-07-18 10:12:20 -07003923 if (what & layer_state_t::eTransformChanged) {
3924 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3925 }
3926 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3927 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3928 flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eCropChanged) {
3931 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3932 }
Marissa Wall861616d2018-10-22 12:52:23 -07003933 if (what & layer_state_t::eFrameChanged) {
3934 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3935 }
Marissa Wall61c58622018-07-18 10:12:20 -07003936 if (what & layer_state_t::eBufferChanged) {
3937 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eAcquireFenceChanged) {
3940 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eDataspaceChanged) {
3943 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eHdrMetadataChanged) {
3946 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3949 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eApiChanged) {
3952 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eSidebandStreamChanged) {
3955 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3956 }
Robert Carr720e5062018-07-30 17:45:14 -07003957 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003958 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3959 layer->setInputInfo(s.inputInfo);
3960 flags |= eTraversalNeeded;
3961 } else {
3962 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3963 }
Robert Carr720e5062018-07-30 17:45:14 -07003964 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003965 if (what & layer_state_t::eMetadataChanged) {
3966 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3967 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003968 std::vector<sp<CallbackHandle>> callbackHandles;
3969 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3970 mTransactionCompletedThread.run();
3971 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3972 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3973 }
3974 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003975 if (what & layer_state_t::eCachedBufferChanged) {
3976 sp<GraphicBuffer> buffer =
3977 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3978 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3979 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003980 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3981 // Do not put anything that updates layer state or modifies flags after
3982 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003983 return flags;
3984}
3985
chaviw273171b2018-12-26 11:46:30 -08003986uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3987 uint32_t flags = 0;
3988 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3989 flags |= eTraversalNeeded;
3990 }
3991
3992 mInputWindowCommands.merge(inputWindowCommands);
3993 return flags;
3994}
3995
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003996status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3997 uint32_t h, PixelFormat format, uint32_t flags,
3998 LayerMetadata metadata, sp<IBinder>* handle,
3999 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004000 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004001 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004002 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004004 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004005
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 status_t result = NO_ERROR;
4007
4008 sp<Layer> layer;
4009
Cody Northropbc755282017-03-31 12:00:08 -06004010 String8 uniqueName = getUniqueLayerName(name);
4011
Mathias Agopian3165cc22012-08-08 19:42:09 -07004012 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004013 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004014 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4015 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004016
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004018 case ISurfaceComposerClient::eFXSurfaceBufferState:
4019 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4020 break;
chaviw13fdc492017-06-27 12:40:18 -07004021 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004022 // check if buffer size is set for color layer.
4023 if (w > 0 || h > 0) {
4024 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4025 int(w), int(h));
4026 return BAD_VALUE;
4027 }
4028
chaviw13fdc492017-06-27 12:40:18 -07004029 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004030 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004031 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004032 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004033 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004034 // check if buffer size is set for container layer.
4035 if (w > 0 || h > 0) {
4036 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4037 int(w), int(h));
4038 return BAD_VALUE;
4039 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004040 result = createContainerLayer(client,
4041 uniqueName, w, h, flags,
4042 handle, &layer);
4043 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 default:
4045 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004046 break;
4047 }
4048
Dan Stoza7d89d062015-04-30 13:29:25 -07004049 if (result != NO_ERROR) {
4050 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004052
Chia-I Wuab0c3192017-08-01 11:29:00 -07004053 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4054 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004055 if (metadata.has(METADATA_WINDOW_TYPE)) {
4056 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4057 if (windowType == 441731) {
4058 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4059 layer->setPrimaryDisplayOnly();
4060 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004061 }
4062
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004063 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004064
Robert Carrb89ea9d2018-12-10 13:01:14 -08004065 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4066 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4067 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004068 if (result != NO_ERROR) {
4069 return result;
4070 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004071 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004072
4073 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Cody Northropbc755282017-03-31 12:00:08 -06004077String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4078{
4079 bool matchFound = true;
4080 uint32_t dupeCounter = 0;
4081
4082 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4083 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4084
Dan Stoza436ccf32018-06-21 12:10:12 -07004085 // Grab the state lock since we're accessing mCurrentState
4086 Mutex::Autolock lock(mStateLock);
4087
Cody Northropbc755282017-03-31 12:00:08 -06004088 // Loop over layers until we're sure there is no matching name
4089 while (matchFound) {
4090 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004091 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004092 if (layer->getName() == uniqueName) {
4093 matchFound = true;
4094 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4095 }
4096 });
4097 }
4098
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004099 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4100 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004101
4102 return uniqueName;
4103}
4104
Marissa Wallfd668622018-05-10 10:21:13 -07004105status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4106 uint32_t w, uint32_t h, uint32_t flags,
4107 PixelFormat& format, sp<IBinder>* handle,
4108 sp<IGraphicBufferProducer>* gbp,
4109 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004111 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 case PIXEL_FORMAT_TRANSPARENT:
4113 case PIXEL_FORMAT_TRANSLUCENT:
4114 format = PIXEL_FORMAT_RGBA_8888;
4115 break;
4116 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004117 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 break;
4119 }
4120
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004121 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004122 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004123 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004125 *handle = layer->getHandle();
4126 *gbp = layer->getProducer();
4127 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129
Marissa Wallfd668622018-05-10 10:21:13 -07004130 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132}
4133
Marissa Wall61c58622018-07-18 10:12:20 -07004134status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4135 uint32_t w, uint32_t h, uint32_t flags,
4136 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004137 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004138 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004139 *handle = layer->getHandle();
4140 *outLayer = layer;
4141
4142 return NO_ERROR;
4143}
4144
chaviw13fdc492017-06-27 12:40:18 -07004145status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004147 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004149 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004151 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004152}
4153
Robert Carr6b3f6c52018-08-13 13:05:17 -07004154status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4155 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4156 sp<IBinder>* handle, sp<Layer>* outLayer)
4157{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004158 *outLayer =
4159 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004160 *handle = (*outLayer)->getHandle();
4161 return NO_ERROR;
4162}
4163
4164
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004165void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004166 mLayersPendingRemoval.add(layer);
4167 mLayersRemoved = true;
4168 setTransactionFlags(eTransactionNeeded);
4169}
4170
Robert Carr695d5282018-12-18 15:27:58 -08004171void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004172{
Robert Carr2e102c92018-10-23 12:11:15 -07004173 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004174 // If a layer has a parent, we allow it to out-live it's handle
4175 // with the idea that the parent holds a reference and will eventually
4176 // be cleaned up. However no one cleans up the top-level so we do so
4177 // here.
4178 if (layer->getParent() == nullptr) {
4179 mCurrentState.layersSortedByZ.remove(layer);
4180 }
4181 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004182 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004183}
4184
Mathias Agopianb60314a2012-04-10 22:09:54 -07004185// ---------------------------------------------------------------------------
4186
Andy McFadden13a082e2012-08-24 10:16:42 -07004187void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004188 const auto display = getDefaultDisplayDeviceLocked();
4189 if (!display) return;
4190
4191 const sp<IBinder> token = display->getDisplayToken().promote();
4192 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004193
Jesse Hall01e29052013-02-19 16:13:35 -08004194 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004195 Vector<ComposerState> state;
4196 Vector<DisplayState> displays;
4197 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004198 d.what = DisplayState::eDisplayProjectionChanged |
4199 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004200 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004201 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004202 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004203 d.frame.makeInvalid();
4204 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004205 d.width = 0;
4206 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004207 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004208 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004209
Dominik Laskowskie9774092018-12-11 10:04:24 -08004210 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004211
Dominik Laskowski83b88212018-12-11 13:34:06 -08004212 const nsecs_t vsyncPeriod = getVsyncPeriod();
4213 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004214
Brian Andersond0010582017-03-07 13:20:31 -08004215 // Use phase of 0 since phase is not known.
4216 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004217 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004218 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004219}
4220
4221void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004222 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004223 postMessageAsync(
4224 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004225}
4226
Dominik Laskowskie9774092018-12-11 10:04:24 -08004227void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004228 if (display->isVirtual()) {
4229 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004230 return;
4231 }
4232
Dominik Laskowski075d3172018-05-24 15:50:06 -07004233 const auto displayId = display->getId();
4234 LOG_ALWAYS_FATAL_IF(!displayId);
4235
Dominik Laskowski34157762018-10-31 13:07:19 -07004236 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237
4238 int currentMode = display->getPowerMode();
4239 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004240 return;
4241 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243 display->setPowerMode(mode);
4244
Lloyd Pique4dccc412018-01-22 17:21:36 -08004245 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004246 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004247 }
4248
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004249 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004250 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004253 if (mUseScheduler) {
4254 mScheduler->onScreenAcquired(mAppConnectionHandle);
4255 } else {
4256 mEventThread->onScreenAcquired();
4257 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004258 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004262 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004263 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004264
4265 struct sched_param param = {0};
4266 param.sched_priority = 1;
4267 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4268 ALOGW("Couldn't set SCHED_FIFO on display on");
4269 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004270 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004271 // Turn off the display
4272 struct sched_param param = {0};
4273 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4274 ALOGW("Couldn't set SCHED_OTHER on display off");
4275 }
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004278 if (mUseScheduler) {
4279 mScheduler->disableHardwareVsync(true);
4280 } else {
4281 disableHardwareVsync(true); // also cancels any in-progress resync
4282 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004283 if (mUseScheduler) {
4284 mScheduler->onScreenReleased(mAppConnectionHandle);
4285 } else {
4286 mEventThread->onScreenReleased();
4287 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004288 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004289
Dominik Laskowski075d3172018-05-24 15:50:06 -07004290 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004291 mVisibleRegionsDirty = true;
4292 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004293 } else if (mode == HWC_POWER_MODE_DOZE ||
4294 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004295 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004297 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004298 if (mUseScheduler) {
4299 mScheduler->onScreenAcquired(mAppConnectionHandle);
4300 } else {
4301 mEventThread->onScreenAcquired();
4302 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004303 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004304 }
4305 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4306 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004307 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004308 if (mUseScheduler) {
4309 mScheduler->disableHardwareVsync(true);
4310 } else {
4311 disableHardwareVsync(true); // also cancels any in-progress resync
4312 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004313 if (mUseScheduler) {
4314 mScheduler->onScreenReleased(mAppConnectionHandle);
4315 } else {
4316 mEventThread->onScreenReleased();
4317 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004318 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004319 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004320 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004321 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004323 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004324
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004325 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004326 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004327 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004328 // Update refresh rate stats.
4329 mRefreshRateStats->setPowerMode(mode);
4330 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004331 }
4332
Dominik Laskowski34157762018-10-31 13:07:19 -07004333 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004334}
4335
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004336void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004337 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 const auto display = getDisplayDevice(displayToken);
4339 if (!display) {
4340 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4341 displayToken.get());
4342 } else if (display->isVirtual()) {
4343 ALOGW("Attempt to set power mode %d for virtual display", mode);
4344 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004345 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004346 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004347 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004348}
4349
4350// ---------------------------------------------------------------------------
4351
Dominik Laskowskic2867142019-01-21 11:33:38 -08004352status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4353 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004354 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004355
Mathias Agopianbd115332013-04-18 16:41:04 -07004356 IPCThreadState* ipc = IPCThreadState::self();
4357 const int pid = ipc->getCallingPid();
4358 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004359
Mathias Agopianbd115332013-04-18 16:41:04 -07004360 if ((uid != AID_SHELL) &&
4361 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4363 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004364 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004365 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 // (this would indicate SF is stuck, but we want to be able to
4367 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004368 status_t err = mStateLock.timedLock(s2ns(1));
4369 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004370 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004371 StringAppendF(&result,
4372 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4373 "(no locks held)\n",
4374 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004375 }
4376
Dominik Laskowskic2867142019-01-21 11:33:38 -08004377 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004378
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379 static const std::unordered_map<std::string, Dumper> dumpers = {
4380 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4381 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4382 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4383 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4384 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4385 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4386 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4387 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4388 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4389 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4390 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4391 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4392 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004393 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4395 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004396
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004398
Dominik Laskowskic2867142019-01-21 11:33:38 -08004399 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4400 (it->second)(args, asProto, result);
4401 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004402 if (asProto) {
4403 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4404 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4405 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004407 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004408 }
4409
Mathias Agopian9795c422009-08-26 16:36:26 -07004410 if (locked) {
4411 mStateLock.unlock();
4412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004413 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004415 return NO_ERROR;
4416}
4417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 mCurrentState.traverseInZOrder(
4420 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004421}
4422
Dominik Laskowskic2867142019-01-21 11:33:38 -08004423void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004424 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004425
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426 if (args.size() > 1) {
4427 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004428 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004429 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004430 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004431 }
Robert Carr2047fae2016-11-28 14:09:09 -08004432 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004433 } else {
4434 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435 }
4436}
4437
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004439 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004441 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004442 }
Robert Carr2047fae2016-11-28 14:09:09 -08004443 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004444
Svetoslavd85084b2014-03-20 10:28:31 -07004445 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004446}
4447
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4449 mTimeStats->parseArgs(asProto, args, result);
4450}
4451
Jamie Gennis6547ff42013-07-16 20:12:42 -07004452// This should only be called from the main thread. Otherwise it would need
4453// the lock and should use mCurrentState rather than mDrawingState.
4454void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004455 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004456 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004457 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004458
4459 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4460}
4461
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004463 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004464
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004465 if (isLayerTripleBufferingDisabled())
4466 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4469 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4470 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4471 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4472 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4473 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004474 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004475}
4476
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004477void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004478 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004479 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004480 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004481 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004482
4483 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4484
4485 if (mUseScheduler) {
4486 mScheduler->dump(mAppConnectionHandle, result);
4487 } else {
4488 mEventThread->dump(result);
4489 }
4490}
4491
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4493 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004494 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4495 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004496 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004497 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004499 }
David Sodman4a36e932017-11-07 14:29:47 -08004500 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004501 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004502 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4504 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004505}
4506
Dan Stozae77c7662016-05-13 11:37:28 -07004507void SurfaceFlinger::recordBufferingStats(const char* layerName,
4508 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004509 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4510 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004511 for (const auto& segment : history) {
4512 if (!segment.usedThirdBuffer) {
4513 stats.twoBufferTime += segment.totalTime;
4514 }
4515 if (segment.occupancyAverage < 1.0f) {
4516 stats.doubleBufferedTime += segment.totalTime;
4517 } else if (segment.occupancyAverage < 2.0f) {
4518 stats.tripleBufferedTime += segment.totalTime;
4519 }
4520 ++stats.numSegments;
4521 stats.totalTime += segment.totalTime;
4522 }
4523}
4524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4526 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004527
4528 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4529 const size_t count = currentLayers.size();
4530 for (size_t i=0 ; i<count ; i++) {
4531 currentLayers[i]->dumpFrameEvents(result);
4532 }
4533}
4534
Yiwei Zhang5434a782018-12-05 18:06:32 -08004535void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004536 result.append("Buffering stats:\n");
4537 result.append(" [Layer name] <Active time> <Two buffer> "
4538 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004539 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004540 typedef std::tuple<std::string, float, float, float> BufferTuple;
4541 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004542 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004543 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004544 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004545 if (stats.numSegments == 0) {
4546 continue;
4547 }
4548 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4549 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4550 stats.totalTime;
4551 float doubleBufferRatio = static_cast<float>(
4552 stats.doubleBufferedTime) / stats.totalTime;
4553 float tripleBufferRatio = static_cast<float>(
4554 stats.tripleBufferedTime) / stats.totalTime;
4555 sorted.insert({activeTime, {name, twoBufferRatio,
4556 doubleBufferRatio, tripleBufferRatio}});
4557 }
4558 for (const auto& sortedPair : sorted) {
4559 float activeTime = sortedPair.first;
4560 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4562 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004563 }
4564 result.append("\n");
4565}
4566
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004568 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004569 const auto displayId = display->getId();
4570 if (!displayId) {
4571 continue;
4572 }
4573 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004574 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004575 continue;
4576 }
4577
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result,
4579 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4580 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004581 uint8_t port;
4582 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004584 result.append("no identification data\n");
4585 continue;
4586 }
4587
4588 if (!isEdid(data)) {
4589 result.append("unknown identification data: ");
4590 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 }
4593 result.append("\n");
4594 continue;
4595 }
4596
4597 const auto edid = parseEdid(data);
4598 if (!edid) {
4599 result.append("invalid EDID: ");
4600 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004602 }
4603 result.append("\n");
4604 continue;
4605 }
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004608 result.append(edid->displayName.data(), edid->displayName.length());
4609 result.append("\"\n");
4610 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004611}
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4614 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4615 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4616 StringAppendF(&result, "DisplayColorSetting: %s\n",
4617 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004618
4619 // TODO: print out if wide-color mode is active or not
4620
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004621 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004622 const auto displayId = display->getId();
4623 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004624 continue;
4625 }
4626
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004628 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004629 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004631 }
4632
Lloyd Pique32cbe282018-10-19 13:09:22 -07004633 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634 StringAppendF(&result, " Current color mode: %s (%d)\n",
4635 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004636 }
4637 result.append("\n");
4638}
4639
Yiwei Zhang5434a782018-12-05 18:06:32 -08004640void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004641 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004642 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4643 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004644 continue;
4645 }
4646
Dominik Laskowski05275f12018-11-01 15:03:24 -07004647 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4649 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004650 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 compositionInfo.dump(result, nullptr);
4652 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004653 }
4654 }
David Sodman7e4ae112018-02-09 15:02:28 -08004655}
4656
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004657LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004658 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004659 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4660 const State& state = useDrawing ? mDrawingState : mCurrentState;
4661 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004662 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004663 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004664 });
4665
4666 return layersProto;
4667}
4668
Lloyd Pique32cbe282018-10-19 13:09:22 -07004669LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004670 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004671
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004672 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004673 resolution->set_w(displayDevice.getWidth());
4674 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004675
Lloyd Pique32cbe282018-10-19 13:09:22 -07004676 auto display = displayDevice.getCompositionDisplay();
4677 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004678
Lloyd Pique32cbe282018-10-19 13:09:22 -07004679 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4680 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4681 layersProto.set_global_transform(displayState.orientation);
4682
4683 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004684 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004685 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004686 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004687 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 }
4690 });
4691
4692 return layersProto;
4693}
4694
Dominik Laskowskic2867142019-01-21 11:33:38 -08004695void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4696 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004697 Colorizer colorizer(colorize);
4698
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699 // figure out if we're stuck somewhere
4700 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4703
4704 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004705 * Dump library configuration.
4706 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707
4708 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004709 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004710 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004711 appendSfConfigString(result);
4712 appendUiConfigString(result);
4713 appendGuiConfigString(result);
4714 result.append("\n");
4715
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004716 result.append("\nDisplay identification data:\n");
4717 dumpDisplayIdentificationData(result);
4718
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004719 result.append("\nWide-Color information:\n");
4720 dumpWideColorInfo(result);
4721
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004723 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004724 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004725 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004726 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004727
Andy McFadden41d67d72014-04-25 16:58:34 -07004728 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004729 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004730 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004731 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004732 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004733
Dan Stozab90cf072015-03-05 11:05:59 -08004734 dumpStaticScreenStats(result);
4735 result.append("\n");
4736
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004738
Dan Stozae77c7662016-05-13 11:37:28 -07004739 dumpBufferingStats(result);
4740
Andy McFadden4803b742012-09-24 19:07:20 -07004741 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742 * Dump the visible layer list
4743 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004744 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4746 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4747 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004749
Chia-I Wu2f884132018-09-13 15:17:58 -07004750 {
4751 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4752 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004754 result.append("\n");
4755 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
David Sodman7e4ae112018-02-09 15:02:28 -08004757 result.append("\nFrame-Composition information:\n");
4758 dumpFrameCompositionInfo(result);
4759 result.append("\n");
4760
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004762 * Dump Display state
4763 */
4764
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004768 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004769 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004770 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004771 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004772
4773 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774 * Dump SurfaceFlinger global state
4775 */
4776
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004778 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004781 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782
Dominik Laskowski075d3172018-05-24 15:50:06 -07004783 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004784 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4785 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4787 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004788 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 StringAppendF(&result,
4790 " transaction-flags : %08x\n"
4791 " gpu_to_cpu_unsupported : %d\n",
4792 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004793
Dominik Laskowski075d3172018-05-24 15:50:06 -07004794 if (const auto displayId = getInternalDisplayId();
4795 displayId && getHwComposer().isConnected(*displayId)) {
4796 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004797 StringAppendF(&result,
4798 " refresh-rate : %f fps\n"
4799 " x-dpi : %f\n"
4800 " y-dpi : %f\n",
4801 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4802 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004803 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004804
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806
Dan Stozae22aec72016-08-01 13:20:59 -07004807 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004808 * Tracing state
4809 */
4810 mTracing.dump(result);
4811 result.append("\n");
4812
4813 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004814 * HWC layer minidump
4815 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004816 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 const auto displayId = display->getId();
4818 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004819 continue;
4820 }
4821
Yiwei Zhang5434a782018-12-05 18:06:32 -08004822 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004823 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004824 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004825 result.append("\n");
4826 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004827
4828 /*
4829 * Dump HWComposer state
4830 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004832 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004833 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004834 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004835 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004836 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
4838 /*
4839 * Dump gralloc state
4840 */
4841 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4842 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004843
4844 /*
4845 * Dump VrFlinger state if in use.
4846 */
4847 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4848 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004850 result.append("\n");
4851 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004852
4853 /**
4854 * Scheduler dump state.
4855 */
4856 if (mUseScheduler) {
4857 result.append("\nScheduler state:\n");
4858 result.append(mScheduler->doDump() + "\n");
4859 result.append(mRefreshRateStats->doDump() + "\n");
4860 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861}
4862
Dominik Laskowski075d3172018-05-24 15:50:06 -07004863const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004864 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004865 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004866 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004867 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004868 }
4869 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004870
Dominik Laskowski34157762018-10-31 13:07:19 -07004871 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004872 static const Vector<sp<Layer>> empty;
4873 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004874}
4875
Keun young Park63f165f2012-08-31 10:53:36 -07004876bool SurfaceFlinger::startDdmConnection()
4877{
4878 void* libddmconnection_dso =
4879 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4880 if (!libddmconnection_dso) {
4881 return false;
4882 }
4883 void (*DdmConnection_start)(const char* name);
4884 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004885 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004886 if (!DdmConnection_start) {
4887 dlclose(libddmconnection_dso);
4888 return false;
4889 }
4890 (*DdmConnection_start)(getServiceName());
4891 return true;
4892}
4893
Chia-I Wu28f320b2018-05-03 11:02:56 -07004894void SurfaceFlinger::updateColorMatrixLocked() {
4895 mat4 colorMatrix;
4896 if (mGlobalSaturationFactor != 1.0f) {
4897 // Rec.709 luma coefficients
4898 float3 luminance{0.213f, 0.715f, 0.072f};
4899 luminance *= 1.0f - mGlobalSaturationFactor;
4900 mat4 saturationMatrix = mat4(
4901 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4902 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4903 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4904 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4905 );
4906 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4907 } else {
4908 colorMatrix = mClientColorMatrix * mDaltonizer();
4909 }
4910
4911 if (mCurrentState.colorMatrix != colorMatrix) {
4912 mCurrentState.colorMatrix = colorMatrix;
4913 mCurrentState.colorMatrixChanged = true;
4914 setTransactionFlags(eTransactionNeeded);
4915 }
4916}
4917
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004918status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919#pragma clang diagnostic push
4920#pragma clang diagnostic error "-Wswitch-enum"
4921 switch (static_cast<ISurfaceComposerTag>(code)) {
4922 // These methods should at minimum make sure that the client requested
4923 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004924 case BOOT_FINISHED:
4925 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004926 case CREATE_DISPLAY:
4927 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004928 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case GET_ACTIVE_COLOR_MODE:
4930 case GET_ANIMATION_FRAME_STATS:
4931 case GET_HDR_CAPABILITIES:
4932 case SET_ACTIVE_CONFIG:
4933 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004934 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004935 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004936 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004937 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4938 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004939 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4940 IPCThreadState* ipc = IPCThreadState::self();
4941 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4942 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004943 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004944 }
Robert Carr1db73f62016-12-21 12:58:51 -08004945 return OK;
4946 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004948 IPCThreadState* ipc = IPCThreadState::self();
4949 const int pid = ipc->getCallingPid();
4950 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4952 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004953 return PERMISSION_DENIED;
4954 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957 // Used by apps to hook Choreographer to SurfaceFlinger.
4958 case CREATE_DISPLAY_EVENT_CONNECTION:
4959 // The following calls are currently used by clients that do not
4960 // request necessary permissions. However, they do not expose any secret
4961 // information, so it is OK to pass them.
4962 case AUTHENTICATE_SURFACE:
4963 case GET_ACTIVE_CONFIG:
4964 case GET_BUILT_IN_DISPLAY:
4965 case GET_DISPLAY_COLOR_MODES:
4966 case GET_DISPLAY_CONFIGS:
4967 case GET_DISPLAY_STATS:
4968 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4969 // Calling setTransactionState is safe, because you need to have been
4970 // granted a reference to Client* and Handle* to do anything with it.
4971 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004972 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004973 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004974 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004975 case GET_PROTECTED_CONTENT_SUPPORT:
4976 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08004977 case UNCACHE_BUFFER:
4978 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 return OK;
4980 }
4981 case CAPTURE_LAYERS:
4982 case CAPTURE_SCREEN: {
4983 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004984 IPCThreadState* ipc = IPCThreadState::self();
4985 const int pid = ipc->getCallingPid();
4986 const int uid = ipc->getCallingUid();
4987 if ((uid != AID_GRAPHICS) &&
4988 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4989 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4990 return PERMISSION_DENIED;
4991 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 return OK;
4993 }
4994 // The following codes are deprecated and should never be allowed to access SF.
4995 case CONNECT_DISPLAY_UNUSED:
4996 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4997 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4998 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004999 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005000 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001
5002 // These codes are used for the IBinder protocol to either interrogate the recipient
5003 // side of the transaction for its canonical interface descriptor or to dump its state.
5004 // We let them pass by default.
5005 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5006 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5007 code == IBinder::SYSPROPS_TRANSACTION) {
5008 return OK;
5009 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005010 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005011 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005012 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5014 return OK;
5015 }
5016 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5017 return PERMISSION_DENIED;
5018#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005019}
5020
Ana Krulec13be8ad2018-08-21 02:43:56 +00005021status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5022 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005023 status_t credentialCheck = CheckTransactCodeCredentials(code);
5024 if (credentialCheck != OK) {
5025 return credentialCheck;
5026 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005027
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5029 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005030 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005031 IPCThreadState* ipc = IPCThreadState::self();
5032 const int uid = ipc->getCallingUid();
5033 if (CC_UNLIKELY(uid != AID_SYSTEM
5034 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005035 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005036 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005037 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 return PERMISSION_DENIED;
5039 }
5040 int n;
5041 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005042 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005043 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 return NO_ERROR;
5045 case 1002: // SHOW_UPDATES
5046 n = data.readInt32();
5047 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005048 invalidateHwcGeometry();
5049 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005052 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005053 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005054 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005055 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005056 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005057 setTransactionFlags(
5058 eTransactionNeeded|
5059 eDisplayTransactionNeeded|
5060 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005061 return NO_ERROR;
5062 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005063 case 1006:{ // send empty update
5064 signalRefresh();
5065 return NO_ERROR;
5066 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005067 case 1008: // toggle use of hw composer
5068 n = data.readInt32();
5069 mDebugDisableHWC = n ? 1 : 0;
5070 invalidateHwcGeometry();
5071 repaintEverything();
5072 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005073 case 1009: // toggle use of transform hint
5074 n = data.readInt32();
5075 mDebugDisableTransformHint = n ? 1 : 0;
5076 invalidateHwcGeometry();
5077 repaintEverything();
5078 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005080 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005081 reply->writeInt32(0);
5082 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005083 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005084 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005085 return NO_ERROR;
5086 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005087 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005088 if (!display) {
5089 return NAME_NOT_FOUND;
5090 }
5091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005092 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005093 return NO_ERROR;
5094 }
5095 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005096 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005097 // daltonize
5098 n = data.readInt32();
5099 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005100 case 1:
5101 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5102 break;
5103 case 2:
5104 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5105 break;
5106 case 3:
5107 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5108 break;
5109 default:
5110 mDaltonizer.setType(ColorBlindnessType::None);
5111 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005112 }
5113 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005114 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005115 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005116 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005117 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005118
5119 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005120 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005122 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005123 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005124 // apply a color matrix
5125 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005126 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005127 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005128 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005129 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005131 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005132 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005133 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005134 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005135 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005136
5137 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5138 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005139 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005140 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5141 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5142 }
5143
Chia-I Wu28f320b2018-05-03 11:02:56 -07005144 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005145 return NO_ERROR;
5146 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005147 // This is an experimental interface
5148 // Needs to be shifted to proper binder interface when we productize
5149 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005150 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005151 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005152 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005153 return NO_ERROR;
5154 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005155 case 1017: {
5156 n = data.readInt32();
5157 mForceFullDamage = static_cast<bool>(n);
5158 return NO_ERROR;
5159 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005160 case 1018: { // Modify Choreographer's phase offset
5161 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005162 if (mUseScheduler) {
5163 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5164 } else {
5165 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5166 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005167 return NO_ERROR;
5168 }
5169 case 1019: { // Modify SurfaceFlinger's phase offset
5170 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005171 if (mUseScheduler) {
5172 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5173 } else {
5174 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5175 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005176 return NO_ERROR;
5177 }
Irvel468051e2016-06-13 16:44:44 -07005178 case 1020: { // Layer updates interceptor
5179 n = data.readInt32();
5180 if (n) {
5181 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005182 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005183 }
5184 else{
5185 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005186 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005187 }
5188 return NO_ERROR;
5189 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005190 case 1021: { // Disable HWC virtual displays
5191 n = data.readInt32();
5192 mUseHwcVirtualDisplays = !n;
5193 return NO_ERROR;
5194 }
Romain Guy0147a172017-06-01 13:53:56 -07005195 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005196 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005197 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005198
Chia-I Wu28f320b2018-05-03 11:02:56 -07005199 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005200 return NO_ERROR;
5201 }
Romain Guy54f154a2017-10-24 21:40:32 +01005202 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005203 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005204 invalidateHwcGeometry();
5205 repaintEverything();
5206 return NO_ERROR;
5207 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005208 // Deprecate, use 1030 to check whether the device is color managed.
5209 case 1024: {
5210 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005211 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005212 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005213 n = data.readInt32();
5214 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005215 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005216 mTracing.enable();
5217 doTracing("tracing.enable");
5218 reply->writeInt32(NO_ERROR);
5219 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005220 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005221 status_t err = mTracing.disable();
5222 reply->writeInt32(err);
5223 }
5224 return NO_ERROR;
5225 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005226 case 1026: { // Get layer tracing status
5227 reply->writeBool(mTracing.isEnabled());
5228 return NO_ERROR;
5229 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005230 // Is a DisplayColorSetting supported?
5231 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005232 const auto display = getDefaultDisplayDevice();
5233 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005234 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005235 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005236
5237 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5238 switch (setting) {
5239 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005240 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005241 break;
5242 case DisplayColorSetting::UNMANAGED:
5243 reply->writeBool(true);
5244 break;
5245 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005246 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005247 break;
5248 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005249 reply->writeBool(
5250 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005251 break;
5252 }
5253 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005254 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005255 // Is VrFlinger active?
5256 case 1028: {
5257 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005258 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005259 return NO_ERROR;
5260 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005261 // Is device color managed?
5262 case 1030: {
5263 reply->writeBool(useColorManagement);
5264 return NO_ERROR;
5265 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005266 // Override default composition data space
5267 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5268 // && adb shell stop zygote && adb shell start zygote
5269 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5270 // adb shell stop zygote && adb shell start zygote
5271 case 1031: {
5272 Mutex::Autolock _l(mStateLock);
5273 n = data.readInt32();
5274 if (n) {
5275 n = data.readInt32();
5276 if (n) {
5277 Dataspace dataspace = static_cast<Dataspace>(n);
5278 if (!validateCompositionDataspace(dataspace)) {
5279 return BAD_VALUE;
5280 }
5281 mDefaultCompositionDataspace = dataspace;
5282 }
5283 n = data.readInt32();
5284 if (n) {
5285 Dataspace dataspace = static_cast<Dataspace>(n);
5286 if (!validateCompositionDataspace(dataspace)) {
5287 return BAD_VALUE;
5288 }
5289 mWideColorGamutCompositionDataspace = dataspace;
5290 }
5291 } else {
5292 // restore composition data space.
5293 mDefaultCompositionDataspace = defaultCompositionDataspace;
5294 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5295 }
5296 return NO_ERROR;
5297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005298 }
5299 }
5300 return err;
5301}
5302
Steven Thomas6d8110b2017-08-31 18:24:21 -07005303void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005304 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005305 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005306}
5307
Ana Krulec7d1d6832018-12-27 11:10:09 -08005308void SurfaceFlinger::repaintEverythingForHWC() {
5309 mRepaintEverything = true;
5310 mEventQueue->invalidateForHWC();
5311}
5312
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005313// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5314class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005315public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005316 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5317 ~WindowDisconnector() {
5318 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005319 }
5320
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005321private:
5322 ANativeWindow* mWindow;
5323 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005324};
5325
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005326status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005327 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5328 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005329 uint32_t reqWidth, uint32_t reqHeight,
5330 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005331 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005332 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005334 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005335
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005336 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5337
Chia-I Wu20261cb2018-08-23 12:55:44 -07005338 sp<DisplayDevice> display;
5339 {
5340 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005341
Chia-I Wu20261cb2018-08-23 12:55:44 -07005342 display = getDisplayDeviceLocked(displayToken);
5343 if (!display) return BAD_VALUE;
5344
Chia-I Wucb023152018-08-28 12:57:23 -07005345 // set the requested width/height to the logical display viewport size
5346 // by default
5347 if (reqWidth == 0 || reqHeight == 0) {
5348 reqWidth = uint32_t(display->getViewport().width());
5349 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005350 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005351 }
5352
Peiyong Lin0e003c92018-09-17 11:09:51 -07005353 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5354 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005355
5356 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005357 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005358 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5359 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005360}
5361
5362status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005363 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5364 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005365 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005366 ATRACE_CALL();
5367
5368 class LayerRenderArea : public RenderArea {
5369 public:
Robert Carr578038f2018-03-09 12:25:24 -08005370 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005371 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5372 bool childrenOnly)
5373 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005374 mLayer(layer),
5375 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005376 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005377 mFlinger(flinger),
5378 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005379 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005380 Rect getBounds() const override {
5381 const Layer::State& layerState(mLayer->getDrawingState());
5382 return mLayer->getBufferSize(layerState);
5383 }
Marissa Wall61c58622018-07-18 10:12:20 -07005384 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005385 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005386 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005387 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005388 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005389 }
chaviwa76b2712017-09-20 12:02:26 -07005390 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005391 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005392 Rect getSourceCrop() const override {
5393 if (mCrop.isEmpty()) {
5394 return getBounds();
5395 } else {
5396 return mCrop;
5397 }
5398 }
Robert Carr578038f2018-03-09 12:25:24 -08005399 class ReparentForDrawing {
5400 public:
5401 const sp<Layer>& oldParent;
5402 const sp<Layer>& newParent;
5403
5404 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5405 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005406 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005407 }
Robert Carr15eae092018-03-23 13:43:53 -07005408 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005409 };
5410
5411 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005412 const Rect sourceCrop = getSourceCrop();
5413 // no need to check rotation because there is none
5414 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5415 sourceCrop.height() != getReqHeight();
5416
Robert Carr578038f2018-03-09 12:25:24 -08005417 if (!mChildrenOnly) {
5418 mTransform = mLayer->getTransform().inverse();
5419 drawLayers();
5420 } else {
5421 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005422 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005423 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5424 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005425
5426 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5427 drawLayers();
5428 }
5429 }
chaviwa76b2712017-09-20 12:02:26 -07005430
chaviwa76b2712017-09-20 12:02:26 -07005431 private:
chaviw7206d492017-11-10 16:16:12 -08005432 const sp<Layer> mLayer;
5433 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005434
5435 // In the "childrenOnly" case we reparent the children to a screenshot
5436 // layer which has no properties set and which does not draw.
5437 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005438 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005439 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005440
5441 SurfaceFlinger* mFlinger;
5442 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005443 };
5444
5445 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5446 auto parent = layerHandle->owner.promote();
5447
Robert Carr2e102c92018-10-23 12:11:15 -07005448 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005449 ALOGE("captureLayers called with a removed parent");
5450 return NAME_NOT_FOUND;
5451 }
5452
Robert Carr578038f2018-03-09 12:25:24 -08005453 const int uid = IPCThreadState::self()->getCallingUid();
5454 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005455 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005456 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5457 return PERMISSION_DENIED;
5458 }
5459
chaviw7206d492017-11-10 16:16:12 -08005460 Rect crop(sourceCrop);
5461 if (sourceCrop.width() <= 0) {
5462 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005463 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005464 }
5465
5466 if (sourceCrop.height() <= 0) {
5467 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005468 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005469 }
5470
5471 int32_t reqWidth = crop.width() * frameScale;
5472 int32_t reqHeight = crop.height() * frameScale;
5473
Chia-I Wu20261cb2018-08-23 12:55:44 -07005474 // really small crop or frameScale
5475 if (reqWidth <= 0) {
5476 reqWidth = 1;
5477 }
5478 if (reqHeight <= 0) {
5479 reqHeight = 1;
5480 }
5481
Peiyong Lin0e003c92018-09-17 11:09:51 -07005482 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005483
Robert Carr578038f2018-03-09 12:25:24 -08005484 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005485 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5486 if (!layer->isVisible()) {
5487 return;
Robert Carr578038f2018-03-09 12:25:24 -08005488 } else if (childrenOnly && layer == parent.get()) {
5489 return;
chaviwa76b2712017-09-20 12:02:26 -07005490 }
5491 visitor(layer);
5492 });
5493 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005494 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005495}
5496
5497status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5498 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005499 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005500 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005501 bool useIdentityTransform) {
5502 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005503
Peiyong Lin0e003c92018-09-17 11:09:51 -07005504 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005505 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5506 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005507 *outBuffer =
5508 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5509 static_cast<android_pixel_format>(reqPixelFormat), 1,
5510 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005511
5512 // This mutex protects syncFd and captureResult for communication of the return values from the
5513 // main thread back to this Binder thread
5514 std::mutex captureMutex;
5515 std::condition_variable captureCondition;
5516 std::unique_lock<std::mutex> captureLock(captureMutex);
5517 int syncFd = -1;
5518 std::optional<status_t> captureResult;
5519
Robert Carr03480e22018-01-04 16:02:06 -08005520 const int uid = IPCThreadState::self()->getCallingUid();
5521 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5522
Dominik Laskowski8c001672018-05-30 16:52:06 -07005523 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005524 // If there is a refresh pending, bug out early and tell the binder thread to try again
5525 // after the refresh.
5526 if (mRefreshPending) {
5527 ATRACE_NAME("Skipping screenshot for now");
5528 std::unique_lock<std::mutex> captureLock(captureMutex);
5529 captureResult = std::make_optional<status_t>(EAGAIN);
5530 captureCondition.notify_one();
5531 return;
5532 }
5533
5534 status_t result = NO_ERROR;
5535 int fd = -1;
5536 {
5537 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005538 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005539 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5540 useIdentityTransform, forSystem, &fd);
5541 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005542 }
5543
5544 {
5545 std::unique_lock<std::mutex> captureLock(captureMutex);
5546 syncFd = fd;
5547 captureResult = std::make_optional<status_t>(result);
5548 captureCondition.notify_one();
5549 }
5550 });
5551
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005552 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005553 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005554 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005555 while (*captureResult == EAGAIN) {
5556 captureResult.reset();
5557 result = postMessageAsync(message);
5558 if (result != NO_ERROR) {
5559 return result;
5560 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005561 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562 }
5563 result = *captureResult;
5564 }
5565
5566 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005567 sync_wait(syncFd, -1);
5568 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005569 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005570
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005571 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005572}
5573
chaviwa76b2712017-09-20 12:02:26 -07005574void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005575 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005576 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005577 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005578
Lloyd Pique144e1162017-12-20 16:44:52 -08005579 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005580
chaviwa76b2712017-09-20 12:02:26 -07005581 const auto reqWidth = renderArea.getReqWidth();
5582 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005583 const auto sourceCrop = renderArea.getSourceCrop();
5584 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005585
Peiyong Lin0e003c92018-09-17 11:09:51 -07005586 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005587 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005588
Mathias Agopian180f10d2013-04-10 22:55:41 -07005589 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005590 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005591
5592 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005593 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005594 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005595
chaviw50da5042018-04-09 13:49:37 -07005596 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005597 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005598 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005599
chaviwa76b2712017-09-20 12:02:26 -07005600 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005601 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005602 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005603 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005604 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005605}
5606
chaviwa76b2712017-09-20 12:02:26 -07005607status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5608 TraverseLayersFunction traverseLayers,
5609 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005611 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005612 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005613 ATRACE_CALL();
5614
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005615 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005616
5617 traverseLayers([&](Layer* layer) {
5618 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5619 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005620
Robert Carr03480e22018-01-04 16:02:06 -08005621 // We allow the system server to take screenshots of secure layers for
5622 // use in situations like the Screen-rotation animation and place
5623 // the impetus on WindowManager to not persist them.
5624 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005625 ALOGW("FB is protected: PERMISSION_DENIED");
5626 return PERMISSION_DENIED;
5627 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005628 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005629
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005630 // this binds the given EGLImage as a framebuffer for the
5631 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005632 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005633 if (bufferBond.getStatus() != NO_ERROR) {
5634 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005635 return INVALID_OPERATION;
5636 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005637
Dan Stozaabcda352017-06-01 14:37:39 -07005638 // this will in fact render into our dequeued buffer
5639 // via an FBO, which means we didn't have to create
5640 // an EGLSurface and therefore we're not
5641 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005642 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005643
Peiyong Linfb530cf2018-12-15 05:07:38 +00005644 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005645 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005646 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005647 }
Alec Mouri492bc572018-09-11 21:40:04 +00005648 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005649
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005650 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005651}
5652
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005653// ---------------------------------------------------------------------------
5654
Dan Stoza412903f2017-04-27 13:42:17 -07005655void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5656 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005657}
5658
Dan Stoza412903f2017-04-27 13:42:17 -07005659void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5660 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005661}
5662
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005663void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005664 const LayerVector::Visitor& visitor) {
5665 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005666 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005667 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005668 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005669 continue;
5670 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005671 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005672 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005673 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005674 return;
5675 }
chaviwa76b2712017-09-20 12:02:26 -07005676 if (!layer->isVisible()) {
5677 return;
5678 }
5679 visitor(layer);
5680 });
5681 }
5682}
5683
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005684}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005685
Lloyd Pique074e8122018-07-26 12:57:23 -07005686
Mathias Agopian3f844832013-08-07 21:24:32 -07005687#if defined(__gl_h_)
5688#error "don't include gl/gl.h in this file"
5689#endif
5690
5691#if defined(__gl2_h_)
5692#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005693#endif