blob: 945f6fa6acfe02ef8086193a6bc0927a573089d7 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700160bool isHdrColorMode(const ColorMode colorMode) {
161 switch (colorMode) {
162 case ColorMode::BT2100_PQ:
163 case ColorMode::BT2100_HLG:
164 return true;
165 case ColorMode::DISPLAY_P3:
166 case ColorMode::ADOBE_RGB:
167 case ColorMode::DCI_P3:
168 case ColorMode::BT2020:
169 case ColorMode::DISPLAY_BT2020:
170 case ColorMode::NATIVE:
171 case ColorMode::STANDARD_BT601_625:
172 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
173 case ColorMode::STANDARD_BT601_525:
174 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
175 case ColorMode::STANDARD_BT709:
176 case ColorMode::SRGB:
177 return false;
178 }
179 return false;
180}
181
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700182ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
183 switch (rotation) {
184 case ISurfaceComposer::eRotateNone:
185 return ui::Transform::ROT_0;
186 case ISurfaceComposer::eRotate90:
187 return ui::Transform::ROT_90;
188 case ISurfaceComposer::eRotate180:
189 return ui::Transform::ROT_180;
190 case ISurfaceComposer::eRotate270:
191 return ui::Transform::ROT_270;
192 }
193 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
194 return ui::Transform::ROT_0;
195}
196
Peiyong Linfca547f2018-07-09 13:03:33 -0700197#pragma clang diagnostic pop
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199class ConditionalLock {
200public:
201 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
202 if (lock) {
203 mMutex.lock();
204 }
205 }
206 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
207private:
208 Mutex& mMutex;
209 bool mLocked;
210};
Peiyong Linfca547f2018-07-09 13:03:33 -0700211
Peiyong Lin9d846a52018-11-05 13:18:20 -0800212// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
213bool validateCompositionDataspace(Dataspace dataspace) {
214 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
215}
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
225
226// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700227int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700228bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800229uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800230bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800231bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800232int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600233bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700234int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700235bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700236bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700237Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
238ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
239Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
240ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700241
Kalle Raitaa099a242017-01-11 11:17:29 -0800242std::string getHwcServiceName() {
243 char value[PROPERTY_VALUE_MAX] = {};
244 property_get("debug.sf.hwc_service_name", value, "default");
245 ALOGI("Using HWComposer service: '%s'", value);
246 return std::string(value);
247}
248
249bool useTrebleTestingOverride() {
250 char value[PROPERTY_VALUE_MAX] = {};
251 property_get("debug.sf.treble_testing_override", value, "false");
252 ALOGI("Treble testing override: '%s'", value);
253 return std::string(value) == "true";
254}
255
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
257 switch(displayColorSetting) {
258 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700261 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Enhanced");
264 default:
265 return std::string("Unknown ") +
266 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268}
269
David Sodmanbc815282017-11-05 18:57:52 -0800270SurfaceFlingerBE::SurfaceFlingerBE()
271 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800272 mFrameBuckets(),
273 mTotalTime(0),
274 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800275 mComposerSequenceId(0) {
276}
277
Lloyd Pique90c115d2018-09-18 21:39:42 -0700278SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
279 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800280 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700281 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700282 mTransactionPending(false),
283 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700284 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700285 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800287 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800289 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800290 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800291 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700293 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700294 mDebugDisableTransformHint(0),
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800295 mDebugEnableProtectedContent(false),
Mathias Agopian9795c422009-08-26 16:36:26 -0700296 mDebugInTransaction(0),
297 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700298 mForceFullDamage(false),
Nataniel Borges2b796da2019-02-15 13:32:18 -0800299 mTracing(*this),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800300 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800301 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800302 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800303 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700304 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700305 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800306 mCompositionEngine{getFactory().createCompositionEngine()} {
307 mSetInputWindowsListener = new SetInputWindowsListener(this);
308}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800309
Lloyd Pique90c115d2018-09-18 21:39:42 -0700310SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
311 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800312 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800321
Steven Thomas050b2c82017-03-06 11:45:16 -0800322 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 mDefaultCompositionDataspace =
332 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
333 mWideColorGamutCompositionDataspace =
334 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
335 defaultCompositionDataspace = mDefaultCompositionDataspace;
336 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
337 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
338 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
339 wideColorGamutCompositionPixelFormat =
340 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800343
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
345 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
346 switch (tmpPrimaryDisplayOrientation) {
347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800355 break;
356 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700357 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800358 break;
359 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700360 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800361
Sundong Ahn85131bd2019-02-18 15:51:53 +0900362 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulece5a06e02019-03-06 17:09:03 -0800396 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800397 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800398
399 int int_value = atoi(value);
400 if (int_value) {
401 mUseSmart90ForVideo = true;
402 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800403
Dan Stozaec460082018-12-17 15:35:09 -0800404 property_get("debug.sf.luma_sampling", value, "1");
405 mLumaSampling = atoi(value);
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
Ady Abraham97d04232019-03-05 19:48:12 -0800591 // set the refresh rate according to the policy
592 const auto displayId = getInternalDisplayIdLocked();
593 LOG_ALWAYS_FATAL_IF(!displayId);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800594
Alec Mouri0a1cc962019-03-14 12:33:02 -0700595 const auto& performanceRefreshRate =
Ady Abraham97d04232019-03-05 19:48:12 -0800596 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
597
Alec Mouri0a1cc962019-03-14 12:33:02 -0700598 if (performanceRefreshRate &&
599 isConfigAllowed(*displayId, performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800600 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800601 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800602 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800603 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800604 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800605}
606
Dan Stoza436ccf32018-06-21 12:10:12 -0700607uint32_t SurfaceFlinger::getNewTexture() {
608 {
609 std::lock_guard lock(mTexturePoolMutex);
610 if (!mTexturePool.empty()) {
611 uint32_t name = mTexturePool.back();
612 mTexturePool.pop_back();
613 ATRACE_INT("TexturePoolSize", mTexturePool.size());
614 return name;
615 }
616
617 // The pool was too small, so increase it for the future
618 ++mTexturePoolSize;
619 }
620
621 // The pool was empty, so we need to get a new texture name directly using a
622 // blocking call to the main thread
623 uint32_t name = 0;
624 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
625 return name;
626}
627
Mathias Agopian3f844832013-08-07 21:24:32 -0700628void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700630}
631
Wei Wangf9b05ee2017-07-19 20:59:39 -0700632// Do not call property_set on main thread which will be blocked by init
633// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700635 ALOGI( "SurfaceFlinger's main thread ready to run. "
636 "Initializing graphics H/W...");
637
Ana Krulec757f63a2019-01-25 10:46:18 -0800638 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900639
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800642 mScheduler =
643 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
644 auto resyncCallback =
645 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800646
Ana Krulecc2870422019-01-29 19:00:58 -0800647 mAppConnectionHandle =
648 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
649 resyncCallback,
650 impl::EventThread::InterceptVSyncsCallback());
651 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
652 resyncCallback, [this](nsecs_t timestamp) {
653 mInterceptor->saveVSyncEvent(timestamp);
654 });
655
656 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
657 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
658 mSfConnectionHandle.get());
659
Kevin DuBois413287f2019-02-25 08:46:47 -0800660 mRegionSamplingThread =
661 new RegionSamplingThread(*this, *mScheduler,
662 RegionSamplingThread::EnvironmentTimingTunables());
663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800672 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800675 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Mathias Agopian92a979a2012-08-02 18:32:23 -0700712 // initialize our drawing state
713 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700714
Andy McFadden13a082e2012-08-24 10:16:42 -0700715 // set initial conditions (e.g. unblank default device)
716 initializeDisplays();
717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700719
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700721
722 const bool presentFenceReliable =
723 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
724 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725
726 if (mStartPropertySetThread->Start() != NO_ERROR) {
727 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729
Ady Abraham97d04232019-03-05 19:48:12 -0800730 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800731 mScheduler->setChangeRefreshRateCallback(
732 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
733 Mutex::Autolock lock(mStateLock);
734 setRefreshRateTo(type, event);
735 });
Kevin DuBois36233132019-02-19 14:08:55 -0800736 }
Ady Abraham1902d072019-03-01 17:18:59 -0800737 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
738 getHwComposer().getConfigs(*display->getId()));
739 mRefreshRateStats =
740 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
741 mTimeStats);
Alec Mouri62c8bd12019-03-22 15:55:23 -0700742 mRefreshRateStats->setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700745}
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 Mutex::Autolock _l(mStateLock);
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750 char value[PROPERTY_VALUE_MAX];
751
752 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700754 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100756
757 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700758 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800759
760 property_get("persist.sys.sf.color_mode", value, "0");
761 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800817status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800823 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 if (!displayId) {
825 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 // TODO: Not sure if display density should handled by SF any longer
829 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700832 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800833 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836 return density;
837 }
838 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("ro.sf.lcd_density"); }
843 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800859 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800895 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800909 info.presentationDeadline =
910 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800915 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulecc2870422019-01-29 19:00:58 -0800931 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Ady Abraham447052e2019-02-13 16:07:27 -0800945void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800946 Scheduler::ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 // Lock is acquired by setRefreshRateTo.
950 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 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
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800967 // config twice. However event generation config might have changed so we need to update it
968 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800970 const Scheduler::ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
Ady Abraham9360a222019-02-27 17:05:30 -0800971 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972
973 if (!mDesiredActiveConfigChanged) {
974 // This is the first time we set the desired
975 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
976
977 // This will trigger HWC refresh without resetting the idle timer.
978 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800980 mDesiredActiveConfigChanged = true;
981 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800982}
983
984status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
985 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800986
987 std::vector<int32_t> allowedConfig;
988 allowedConfig.push_back(mode);
989
990 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991}
992
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993void SurfaceFlinger::setActiveConfigInternal() {
994 ATRACE_CALL();
995
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800997 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998
999 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1000 display->setActiveConfig(mUpcomingActiveConfig.configId);
1001
Ana Krulecc2870422019-01-29 19:00:58 -08001002 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001003 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1004 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001006 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001007 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1008 mUpcomingActiveConfig.configId);
1009 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010}
1011
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001013 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 if (mCheckPendingFence) {
1015 if (mPreviousPresentFence != Fence::NO_FENCE &&
1016 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1017 // fence has not signaled yet. wait for the next invalidate
1018 repaintEverythingForHWC();
1019 return true;
1020 }
1021
1022 // We received the present fence from the HWC, so we assume it successfully updated
1023 // the config, hence we update SF.
1024 mCheckPendingFence = false;
1025 setActiveConfigInternal();
1026 }
1027
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028 // Store the local variable to release the lock.
1029 ActiveConfigInfo desiredActiveConfig;
1030 {
1031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 if (!mDesiredActiveConfigChanged) {
1033 return false;
1034 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001035 desiredActiveConfig = mDesiredActiveConfig;
1036 }
1037
1038 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1040 // display is not valid or we are already in the requested mode
1041 // on both cases there is nothing left to do
1042 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1043 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1044 mDesiredActiveConfigChanged = false;
1045 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1046 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001047 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048
Ady Abraham838de062019-02-04 10:24:03 -08001049 // Desired active config was set, it is different than the config currently in use, however
1050 // allowed configs might have change by the time we process the refresh.
1051 // Make sure the desired config is still allowed
1052 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1053 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1054 mDesiredActiveConfig.configId = display->getActiveConfig();
1055 return false;
1056 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001057 mUpcomingActiveConfig = desiredActiveConfig;
1058 const auto displayId = display->getId();
1059 LOG_ALWAYS_FATAL_IF(!displayId);
1060
1061 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1062 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1063
1064 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065 mCheckPendingFence = true;
1066
1067 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001068}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1071 Vector<ColorMode>* outColorModes) {
1072 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001073 return BAD_VALUE;
1074 }
1075
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001077 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001078 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1079
1080 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1081 if (!displayId) {
1082 return NAME_NOT_FOUND;
1083 }
1084
Dominik Laskowski075d3172018-05-24 15:50:06 -07001085 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001086 }
Michael Wright28f24d02016-07-12 13:30:53 -07001087 outColorModes->clear();
1088 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1089
1090 return NO_ERROR;
1091}
1092
Daniel Solomon42d04562019-01-20 21:03:19 -08001093status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1094 ui::DisplayPrimaries &primaries) {
1095 if (!displayToken) {
1096 return BAD_VALUE;
1097 }
1098
1099 // Currently we only support this API for a single internal display.
1100 if (getInternalDisplayToken() != displayToken) {
1101 return BAD_VALUE;
1102 }
1103
1104 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1105 return NO_ERROR;
1106}
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1109 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001110 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001111 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001112 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001113}
1114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001116 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001117 Vector<ColorMode> modes;
1118 getDisplayColorModes(displayToken, &modes);
1119 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1120 if (mode < ColorMode::NATIVE || !exists) {
1121 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1122 decodeColorMode(mode).c_str(), mode, displayToken.get());
1123 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001124 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125 const auto display = getDisplayDevice(displayToken);
1126 if (!display) {
1127 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1128 decodeColorMode(mode).c_str(), mode, displayToken.get());
1129 } else if (display->isVirtual()) {
1130 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1131 decodeColorMode(mode).c_str(), mode);
1132 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001133 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1134 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 }
1136 }));
1137
Michael Wright28f24d02016-07-12 13:30:53 -07001138 return NO_ERROR;
1139}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001140
Svetoslavd85084b2014-03-20 10:28:31 -07001141status_t SurfaceFlinger::clearAnimationFrameStats() {
1142 Mutex::Autolock _l(mStateLock);
1143 mAnimFrameTracker.clearStats();
1144 return NO_ERROR;
1145}
1146
1147status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1148 Mutex::Autolock _l(mStateLock);
1149 mAnimFrameTracker.getStats(outStats);
1150 return NO_ERROR;
1151}
1152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001153status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1154 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001155 Mutex::Autolock _l(mStateLock);
1156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157 const auto display = getDisplayDeviceLocked(displayToken);
1158 if (!display) {
1159 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001160 return BAD_VALUE;
1161 }
1162
Peiyong Linfb069302018-04-25 14:34:31 -07001163 // At this point the DisplayDeivce should already be set up,
1164 // meaning the luminance information is already queried from
1165 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001166 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001167 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1168 capabilities.getDesiredMaxLuminance(),
1169 capabilities.getDesiredMaxAverageLuminance(),
1170 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001171
1172 return NO_ERROR;
1173}
1174
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001175status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1176 ui::PixelFormat* outFormat,
1177 ui::Dataspace* outDataspace,
1178 uint8_t* outComponentMask) const {
1179 if (!outFormat || !outDataspace || !outComponentMask) {
1180 return BAD_VALUE;
1181 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001182 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001183 if (!display || !display->getId()) {
1184 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1185 return BAD_VALUE;
1186 }
1187 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1188 outDataspace, outComponentMask);
1189}
1190
Kevin DuBois74e53772018-11-19 10:52:38 -08001191status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1192 bool enable, uint8_t componentMask,
1193 uint64_t maxFrames) const {
1194 const auto display = getDisplayDevice(displayToken);
1195 if (!display || !display->getId()) {
1196 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1197 return BAD_VALUE;
1198 }
1199
1200 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1201 componentMask, maxFrames);
1202}
1203
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001204status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1205 uint64_t maxFrames, uint64_t timestamp,
1206 DisplayedFrameStats* outStats) const {
1207 const auto display = getDisplayDevice(displayToken);
1208 if (!display || !display->getId()) {
1209 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1210 return BAD_VALUE;
1211 }
1212
1213 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1214 outStats);
1215}
1216
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001217status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1218 if (!outSupported) {
1219 return BAD_VALUE;
1220 }
1221 *outSupported = getRenderEngine().supportsProtectedContent();
1222 return NO_ERROR;
1223}
1224
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001225status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1226 bool* outIsWideColorDisplay) const {
1227 if (!displayToken || !outIsWideColorDisplay) {
1228 return BAD_VALUE;
1229 }
1230 Mutex::Autolock _l(mStateLock);
1231 const auto display = getDisplayDeviceLocked(displayToken);
1232 if (!display) {
1233 return BAD_VALUE;
1234 }
1235 *outIsWideColorDisplay = display->hasWideColorGamut();
1236 return NO_ERROR;
1237}
1238
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001239status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001240 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001242
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243 if (mInjectVSyncs == enable) {
1244 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001245 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246
Ana Krulecc2870422019-01-29 19:00:58 -08001247 auto resyncCallback =
1248 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001250 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 if (enable) {
1253 ALOGV("VSync Injections enabled");
1254 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001255 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001256 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001257 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001258 impl::EventThread::InterceptVSyncsCallback(),
1259 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 } else {
1263 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001264 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1265 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001266 }
1267
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001268 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001269 }));
1270
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001271 return NO_ERROR;
1272}
1273
1274status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 Mutex::Autolock _l(mStateLock);
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 if (!mInjectVSyncs) {
1278 ALOGE("VSync Injections not enabled");
1279 return BAD_VALUE;
1280 }
1281 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1282 ALOGV("Injecting VSync inside SurfaceFlinger");
1283 mVSyncInjector->onInjectSyncEvent(when);
1284 }
1285 return NO_ERROR;
1286}
1287
Lloyd Pique755e3192018-01-31 16:46:15 -08001288status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1289 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001290 // Try to acquire a lock for 1s, fail gracefully
1291 const status_t err = mStateLock.timedLock(s2ns(1));
1292 const bool locked = (err == NO_ERROR);
1293 if (!locked) {
1294 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1295 return TIMED_OUT;
1296 }
1297
1298 outLayers->clear();
1299 mCurrentState.traverseInZOrder([&](Layer* layer) {
1300 outLayers->push_back(layer->getLayerDebugInfo());
1301 });
1302
1303 mStateLock.unlock();
1304 return NO_ERROR;
1305}
1306
Peiyong Linc6780972018-10-28 15:24:08 -07001307status_t SurfaceFlinger::getCompositionPreference(
1308 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1309 Dataspace* outWideColorGamutDataspace,
1310 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001311 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001312 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001313 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001314 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001315 return NO_ERROR;
1316}
1317
Dan Stozaec460082018-12-17 15:35:09 -08001318status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1319 const sp<IBinder>& stopLayerHandle,
1320 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001321 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001322 return BAD_VALUE;
1323 }
1324 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001325 return NO_ERROR;
1326}
1327
Dan Stozaec460082018-12-17 15:35:09 -08001328status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001329 if (!listener) {
1330 return BAD_VALUE;
1331 }
Dan Stozaec460082018-12-17 15:35:09 -08001332 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001333 return NO_ERROR;
1334}
Dan Gittik57e63c52019-01-18 16:37:54 +00001335
1336status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1337 bool* outSupport) const {
1338 if (!displayToken || !outSupport) {
1339 return BAD_VALUE;
1340 }
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
1344 }
1345 *outSupport =
1346 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1347 return NO_ERROR;
1348}
1349
1350status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1351 float brightness) const {
1352 if (!displayToken) {
1353 return BAD_VALUE;
1354 }
1355 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1356 if (!displayId) {
1357 return NAME_NOT_FOUND;
1358 }
1359 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1360}
1361
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001362// ----------------------------------------------------------------------------
1363
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001364sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1365 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001366 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001367 Mutex::Autolock lock(mStateLock);
1368 return getVsyncPeriod();
1369 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001370
Ana Krulecc2870422019-01-29 19:00:58 -08001371 const auto& handle =
1372 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001373
Ana Krulecc2870422019-01-29 19:00:58 -08001374 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001375}
1376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001377// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001378
1379void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381}
1382
1383void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001384 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001385}
1386
1387void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001388 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001389}
1390
1391void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001392 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001393 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001394}
1395
1396status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001397 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001398 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001399}
1400
1401status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001402 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001403 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001404 if (res == NO_ERROR) {
1405 msg->wait();
1406 }
1407 return res;
1408}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001409
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001410void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001411 do {
1412 waitForEvent();
1413 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001414}
1415
Dominik Laskowski83b88212018-12-11 13:34:06 -08001416nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001417 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001418 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1419 return 0;
1420 }
1421
1422 const auto config = getHwComposer().getActiveConfig(*displayId);
1423 return config ? config->getVsyncPeriod() : 0;
1424}
1425
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001426void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1427 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001428 ATRACE_NAME("SF onVsync");
1429
Steven Thomas3cfac282017-02-06 12:29:30 -08001430 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001432 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 return;
1434 }
1435
Dominik Laskowski075d3172018-05-24 15:50:06 -07001436 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001437 return;
1438 }
1439
Dominik Laskowski075d3172018-05-24 15:50:06 -07001440 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001441 // For now, we don't do anything with external display vsyncs.
1442 return;
1443 }
1444
Ana Krulecc2870422019-01-29 19:00:58 -08001445 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001446}
1447
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001448void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001449 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1450 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001451}
1452
Ady Abraham838de062019-02-04 10:24:03 -08001453bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1454 std::lock_guard lock(mAllowedConfigsLock);
1455
1456 // if allowed configs are not set yet for this display, every config is considered allowed
1457 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1458 return true;
1459 }
1460
1461 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1462}
1463
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001464void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001465 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001466 return;
1467 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001468 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001469
Ana Krulec7d1d6832018-12-27 11:10:09 -08001470 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001471 const auto displayId = getInternalDisplayIdLocked();
1472 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001473 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001474
Alec Mouri0a1cc962019-03-14 12:33:02 -07001475 const auto& refreshRateConfig = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate);
1476 if (!refreshRateConfig) {
1477 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001478 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001479 }
Ady Abraham1902d072019-03-01 17:18:59 -08001480
Alec Mouri0a1cc962019-03-14 12:33:02 -07001481 const int desiredConfigId = refreshRateConfig->configId;
1482
Ady Abraham1902d072019-03-01 17:18:59 -08001483 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1484 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1485 return;
1486 }
1487
Alec Mouri0a1cc962019-03-14 12:33:02 -07001488 const auto display = getDisplayDeviceLocked(displayToken);
1489 if (desiredConfigId == display->getActiveConfig()) {
1490 return;
1491 }
1492
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001493 mPhaseOffsets->setRefreshRateType(refreshRate);
Ady Abraham1902d072019-03-01 17:18:59 -08001494 setDesiredActiveConfig(getInternalDisplayTokenLocked(), desiredConfigId, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495}
1496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 // Ignore events that do not have the right sequenceId.
1503 if (sequenceId != getBE().mComposerSequenceId) {
1504 return;
1505 }
1506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Only lock if we're not on the main thread. This function is normally
1508 // called on a hwbinder thread, but for the primary display it's called on
1509 // the main thread with the state lock already held, so don't attempt to
1510 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001514
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001515 if (std::this_thread::get_id() == mMainThreadId) {
1516 // Process all pending hot plug events immediately if we are on the main thread.
1517 processDisplayHotplugEventsLocked();
1518 }
1519
Lloyd Piqueba04e622017-12-14 17:11:26 -08001520 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001525 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001528 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001529}
1530
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001532 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001534 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001535 getHwComposer().setVsyncEnabled(*displayId,
1536 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1537 }
Mathias Agopian86303202012-07-24 22:46:10 -07001538}
1539
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001541void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001542 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001543 // Clear the drawing state so that the logic inside of
1544 // handleTransactionLocked will fire. It will determine the delta between
1545 // mCurrentState and mDrawingState and re-apply all changes when we make the
1546 // transition.
1547 mDrawingState.displays.clear();
1548 mDisplays.clear();
1549}
1550
Steven Thomas050b2c82017-03-06 11:45:16 -08001551void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001552 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001553 if (!mVrFlinger)
1554 return;
1555 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001557 return;
1558 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Pique441d5042018-10-18 16:49:51 -07001560 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 ALOGE("Vr flinger is only supported for remote hardware composer"
1562 " service connections. Ignoring request to transition to vr"
1563 " flinger.");
1564 mVrFlingerRequestsDisplay = false;
1565 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001566 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001571 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001572
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001573 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001574
1575 // Clear out all the output layers from the composition engine for all
1576 // displays before destroying the hardware composer interface. This ensures
1577 // any HWC layers are destroyed through that interface before it becomes
1578 // invalid.
1579 for (const auto& [token, displayDevice] : mDisplays) {
1580 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1581 compositionengine::Output::OutputLayers());
1582 }
1583
Steven Thomas0123ac62018-07-12 11:32:34 -07001584 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1585 // called below. Clear the reference now so we don't accidentally use it
1586 // later.
1587 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588
Steven Thomasb02664d2017-07-26 18:48:28 -07001589 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001594 // Delete the current instance before creating the new one
1595 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1596 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1597 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1598 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599
Lloyd Pique441d5042018-10-18 16:49:51 -07001600 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001601 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001602
1603 if (vrFlingerRequestsDisplay) {
1604 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001605 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001606
1607 mVisibleRegionsDirty = true;
1608 invalidateHwcGeometry();
1609
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001611 display = getDefaultDisplayDeviceLocked();
1612 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001613 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 const nsecs_t vsyncPeriod = getVsyncPeriod();
1617 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001618
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001619 // The present fences returned from vr_hwc are not an accurate
1620 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001621 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001622
Steven Thomasb02664d2017-07-26 18:48:28 -07001623 // Use phase of 0 since phase is not known.
1624 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001625 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001626 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001627
Ana Krulecc2870422019-01-29 19:00:58 -08001628 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001629
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001630 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632}
1633
Mathias Agopian4fec8732012-06-29 14:12:52 -07001634void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001635 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001636 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001637 case MessageQueue::INVALIDATE: {
Alec Mouricc0fc602019-02-26 21:45:19 -08001638 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
1639 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
1640 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1641 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1642 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1643 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1644 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1645 if (frameMissed) {
1646 mFrameMissedCount++;
1647 mTimeStats->incrementMissedFrames();
1648 }
1649
Alec Mouri40189b02019-03-05 15:07:54 -08001650 if (hwcFrameMissed) {
1651 mHwcFrameMissedCount++;
1652 }
1653
1654 if (gpuFrameMissed) {
1655 mGpuFrameMissedCount++;
1656 }
1657
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001658 if (mUseSmart90ForVideo) {
1659 // This call is made each time SF wakes up and creates a new frame. It is part
1660 // of video detection feature.
1661 mScheduler->updateFpsBasedOnNativeWindowApi();
1662 }
1663
Ady Abrahamb838aed2019-02-12 15:30:16 -08001664 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001665 break;
1666 }
1667
Alec Mourife3dc942019-02-12 14:19:18 -08001668 // For now, only propagate backpressure when missing a hwc frame.
1669 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001670 if (mPropagateBackpressure) {
1671 signalLayerUpdate();
1672 break;
1673 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001674 }
Dan Stoza50182882016-07-08 12:02:20 -07001675
Steven Thomas050b2c82017-03-06 11:45:16 -08001676 // Now that we're going to make it to the handleMessageTransaction()
1677 // call below it's safe to call updateVrFlinger(), which will
1678 // potentially trigger a display handoff.
1679 updateVrFlinger();
1680
Dan Stoza6b9454d2014-11-07 16:00:59 -08001681 bool refreshNeeded = handleMessageTransaction();
1682 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001683
1684 updateCursorAsync();
1685 updateInputFlinger();
1686
Dan Stoza58784442014-12-02 16:58:17 -08001687 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001688 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001689 // Signal a refresh if a transaction modified the window state,
1690 // a new buffer was latched, or if HWC has requested a full
1691 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001692 signalRefresh();
1693 }
1694 break;
1695 }
1696 case MessageQueue::REFRESH: {
1697 handleMessageRefresh();
1698 break;
1699 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001700 }
1701}
1702
Dan Stoza6b9454d2014-11-07 16:00:59 -08001703bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001704 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001705 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001706
1707 // Apply any ready transactions in the queues if there are still transactions that have not been
1708 // applied, wake up during the next vsync period and check again
1709 bool transactionNeeded = false;
1710 if (!flushTransactionQueues()) {
1711 transactionNeeded = true;
1712 }
1713
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001715 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001717
1718 if (transactionNeeded) {
1719 setTransactionFlags(eTransactionNeeded);
1720 }
1721
1722 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723}
1724
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001726 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001727
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001728 mRefreshPending = false;
1729
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001730 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001731 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001732 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001733 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001734 for (const auto& [token, display] : mDisplays) {
1735 beginFrame(display);
1736 prepareFrame(display);
1737 doDebugFlashRegions(display, repaintEverything);
1738 doComposition(display, repaintEverything);
1739 }
1740
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001741 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001742
1743 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001744 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001745
Dan Stozabfbffeb2016-07-21 14:49:33 -07001746 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001747 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001748 for (const auto& [token, displayDevice] : mDisplays) {
1749 auto display = displayDevice->getCompositionDisplay();
1750 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001751 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001752 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001753 mHadDeviceComposition =
1754 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001755 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001756
Jorim Jaggi90535212018-05-23 23:44:06 +02001757 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001758
David Sodman7e4ae112018-02-09 15:02:28 -08001759 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001761
David Sodmanfa9b2af2017-12-24 13:28:59 -08001762
1763bool SurfaceFlinger::handleMessageInvalidate() {
1764 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001765 bool refreshNeeded = handlePageFlip();
1766
Vishnu Nair4351ad52019-02-11 14:13:02 -08001767 if (mVisibleRegionsDirty) {
1768 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001769 if (mTracingEnabled) {
1770 mTracing.notify("visibleRegionsDirty");
1771 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001772 }
1773
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001774 for (auto& layer : mLayersPendingRefresh) {
1775 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001776 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001777 invalidateLayerStack(layer, visibleReg);
1778 }
1779 mLayersPendingRefresh.clear();
1780 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001781}
1782
David Sodman79bba0e2018-08-05 18:07:49 -07001783void SurfaceFlinger::calculateWorkingSet() {
1784 ATRACE_CALL();
1785 ALOGV(__FUNCTION__);
1786
David Sodman79bba0e2018-08-05 18:07:49 -07001787 // build the h/w work list
1788 if (CC_UNLIKELY(mGeometryInvalid)) {
1789 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 for (const auto& [token, displayDevice] : mDisplays) {
1791 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001792
Lloyd Piquea83776c2019-01-29 18:42:32 -08001793 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001794
Lloyd Piquea83776c2019-01-29 18:42:32 -08001795 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1796 auto& compositionState = layer->editState();
1797 compositionState.forceClientComposition = false;
1798 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1799 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001800 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801
Lloyd Piquea83776c2019-01-29 18:42:32 -08001802 // The output Z order is set here based on a simple counter.
1803 compositionState.z = zOrder++;
1804
1805 // Update the display independent composition state. This goes
1806 // to the general composition layer state structure.
1807 // TODO: Do this once per compositionengine::CompositionLayer.
1808 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1809 true);
1810
1811 // Recalculate the geometry state of the output layer.
1812 layer->updateCompositionState(true);
1813
1814 // Write the updated geometry state to the HWC
1815 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 }
1817 }
1818 }
1819
1820 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001821 for (const auto& [token, displayDevice] : mDisplays) {
1822 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001823 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001824 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001825 continue;
1826 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001827 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001828
1829 if (mDrawingState.colorMatrixChanged) {
1830 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001831 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001832 Dataspace targetDataspace = Dataspace::UNKNOWN;
1833 if (useColorManagement) {
1834 ColorMode colorMode;
1835 RenderIntent renderIntent;
1836 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1837 display->setColorMode(colorMode, targetDataspace, renderIntent);
1838 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001840 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001841 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1843 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001844 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001845 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001846 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1847 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001848 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001849 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001850 }
1851
Peiyong Lind3788632018-09-18 16:01:31 -07001852 // TODO(b/111562338) remove when composer 2.3 is shipped.
1853 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001854 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001855 }
1856
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001857 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001858 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001859 }
1860
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001861 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001862 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001863 layer->setCompositionType(displayDevice,
1864 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001865 continue;
1866 }
1867
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001869 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001870 displayDevice->getSupportedPerFrameMetadata(),
1871 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1872 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001873 }
1874 }
1875
1876 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001877
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001878 for (const auto& [token, displayDevice] : mDisplays) {
1879 auto display = displayDevice->getCompositionDisplay();
1880 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001881 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1882 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1883 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001884 }
1885 }
David Sodman79bba0e2018-08-05 18:07:49 -07001886}
1887
Lloyd Pique32cbe282018-10-19 13:09:22 -07001888void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1889 bool repaintEverything) {
1890 auto display = displayDevice->getCompositionDisplay();
1891 const auto& displayState = display->getState();
1892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893 // is debugging enabled
1894 if (CC_LIKELY(!mDebugRegion))
1895 return;
1896
Lloyd Pique32cbe282018-10-19 13:09:22 -07001897 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001898 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001899 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001900 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001901 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001902 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001903 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001905 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906 }
1907 }
1908
Lloyd Pique32cbe282018-10-19 13:09:22 -07001909 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910
1911 if (mDebugRegion > 1) {
1912 usleep(mDebugRegion * 1000);
1913 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001914
Lloyd Pique32cbe282018-10-19 13:09:22 -07001915 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001916}
1917
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001918void SurfaceFlinger::logLayerStats() {
1919 ATRACE_CALL();
1920 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001921 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001923 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001924 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001925 }
1926 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001927
1928 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001929 }
1930}
1931
David Sodman2b406362017-12-15 13:33:47 -08001932void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 ATRACE_CALL();
1935 ALOGV("preComposition");
1936
David Sodman2b406362017-12-15 13:33:47 -08001937 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1938
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001940 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001941 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001942 needExtraInvalidate = true;
1943 }
Robert Carr2047fae2016-11-28 14:09:09 -08001944 });
1945
Mathias Agopiancd60f992012-08-16 16:28:27 -07001946 if (needExtraInvalidate) {
1947 signalLayerUpdate();
1948 }
1949}
1950
Ana Krulece588e312018-09-18 12:32:24 -07001951void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1952 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 // Update queue of past composite+present times and determine the
1954 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001955 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001956 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001957 while (!getBE().mCompositePresentTimes.empty()) {
1958 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959 // Cached values should have been updated before calling this method,
1960 // which helps avoid duplicate syscalls.
1961 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1962 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1963 break;
1964 }
1965 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001966 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 }
1968
1969 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001970 while (getBE().mCompositePresentTimes.size() > 16) {
1971 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 }
1973
Ana Krulece588e312018-09-18 12:32:24 -07001974 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001975}
1976
Ana Krulece588e312018-09-18 12:32:24 -07001977void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1978 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979 // Integer division and modulo round toward 0 not -inf, so we need to
1980 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001981 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1982 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1983 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001984
Ana Krulec757f63a2019-01-25 10:46:18 -08001985 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001986 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001987 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001988 }
1989
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990 // Snap the latency to a value that removes scheduling jitter from the
1991 // composition and present times, which often have >1ms of jitter.
1992 // Reducing jitter is important if an app attempts to extrapolate
1993 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001994 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001996 nsecs_t bias = stats.vsyncPeriod / 2;
1997 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1998 nsecs_t snappedCompositeToPresentLatency =
1999 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002000
David Sodman99974d22017-11-28 12:04:33 -08002001 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002002 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2003 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002004 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002005}
2006
David Sodman2b406362017-12-15 13:33:47 -08002007void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 ATRACE_CALL();
2010 ALOGV("postComposition");
2011
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002013 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002014 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002015 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002016 }
2017
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002018 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002019 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020
David Sodman73beded2017-11-15 11:56:06 -08002021 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002023 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002025 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2026 ->getRenderSurface()
2027 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 } else {
2030 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2031 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002034 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2035 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002036 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08002037 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002038
Ana Krulece588e312018-09-18 12:32:24 -07002039 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002040 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041
David Sodman2b406362017-12-15 13:33:47 -08002042 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 // when we started doing work for this frame, but that should be okay
2044 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002045 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002046 CompositorTiming compositorTiming;
2047 {
David Sodman99974d22017-11-28 12:04:33 -08002048 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2049 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002050 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051
Robert Carr2047fae2016-11-28 14:09:09 -08002052 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002053 bool frameLatched =
2054 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2055 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002056 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002057 recordBufferingStats(layer->getName().string(),
2058 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002059 }
Robert Carr2047fae2016-11-28 14:09:09 -08002060 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002061
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002062 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002063 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002064 }
2065
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002066 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2068 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002069 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002070 }
2071 }
2072
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002073 if (mAnimCompositionPending) {
2074 mAnimCompositionPending = false;
2075
Brian Anderson4e606e32017-03-16 15:34:57 -07002076 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002077 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002078 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002079 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002080 // The HWC doesn't support present fences, so use the refresh
2081 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 const nsecs_t presentTime =
2083 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002084 mAnimFrameTracker.setActualPresentTime(presentTime);
2085 }
2086 mAnimFrameTracker.advanceFrame();
2087 }
Dan Stozab90cf072015-03-05 11:05:59 -08002088
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002089 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002090 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002091 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002092 }
2093
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002094 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002095
Lloyd Pique32cbe282018-10-19 13:09:22 -07002096 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2097 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002098 return;
2099 }
2100
2101 nsecs_t currentTime = systemTime();
2102 if (mHasPoweredOff) {
2103 mHasPoweredOff = false;
2104 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002105 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002106 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002107 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2108 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002109 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002110 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002111 }
David Sodman4a36e932017-11-07 14:29:47 -08002112 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002113 }
David Sodman4a36e932017-11-07 14:29:47 -08002114 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002115
2116 {
2117 std::lock_guard lock(mTexturePoolMutex);
2118 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2119 if (refillCount > 0) {
2120 const size_t offset = mTexturePool.size();
2121 mTexturePool.resize(mTexturePoolSize);
2122 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2123 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2124 }
2125 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002126
Marissa Wallfda30bb2018-10-12 11:34:28 -07002127 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002128 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002129
Kevin DuBois413287f2019-02-25 08:46:47 -08002130 if (mLumaSampling && mRegionSamplingThread) {
2131 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002132 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002133}
2134
Vishnu Nair4351ad52019-02-11 14:13:02 -08002135void SurfaceFlinger::computeLayerBounds() {
2136 for (const auto& pair : mDisplays) {
2137 const auto& displayDevice = pair.second;
2138 const auto display = displayDevice->getCompositionDisplay();
2139 for (const auto& layer : mDrawingState.layersSortedByZ) {
2140 // only consider the layers on the given layer stack
2141 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002142 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002143 }
2144
2145 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2146 }
2147 }
2148}
2149
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 ATRACE_CALL();
2152 ALOGV("rebuildLayerStacks");
2153
Mathias Agopiancd60f992012-08-16 16:28:27 -07002154 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002155 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002156 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002157 mVisibleRegionsDirty = false;
2158 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002159
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002160 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002161 const auto& displayDevice = pair.second;
2162 auto display = displayDevice->getCompositionDisplay();
2163 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002164 Region opaqueRegion;
2165 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002166 compositionengine::Output::OutputLayers layersSortedByZ;
2167 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002168 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002169 const ui::Transform& tr = displayState.transform;
2170 const Rect bounds = displayState.bounds;
2171 if (displayState.isEnabled) {
2172 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002173
Jeff Sharkey76488112017-02-27 14:15:18 -07002174 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002175 auto compositionLayer = layer->getCompositionLayer();
2176 if (compositionLayer == nullptr) {
2177 return;
2178 }
2179
Lloyd Pique32cbe282018-10-19 13:09:22 -07002180 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002181 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2182 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2183
Lloyd Pique07e33212018-12-18 16:33:37 -08002184 bool needsOutputLayer = false;
2185
Lloyd Piqueef36b002019-01-23 17:52:04 -08002186 if (display->belongsInOutput(layer->getLayerStack(),
2187 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002188 Region drawRegion(tr.transform(
2189 layer->visibleNonTransparentRegion));
2190 drawRegion.andSelf(bounds);
2191 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002192 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002193 }
Chia-I Wu83806892017-11-16 10:50:20 -08002194 }
2195
Lloyd Pique07e33212018-12-18 16:33:37 -08002196 if (needsOutputLayer) {
2197 layersSortedByZ.emplace_back(
2198 display->getOrCreateOutputLayer(displayId, compositionLayer,
2199 layerFE));
2200 deprecated_layersSortedByZ.add(layer);
2201
2202 auto& outputLayerState = layersSortedByZ.back()->editState();
2203 outputLayerState.visibleRegion =
2204 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2205 } else if (displayId) {
2206 // For layers that are being removed from a HWC display,
2207 // and that have queued frames, add them to a a list of
2208 // released layers so we can properly set a fence.
2209 bool hasExistingOutputLayer =
2210 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2211 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2212 mLayersWithQueuedFrames.cend(),
2213 layer) != mLayersWithQueuedFrames.cend();
2214
2215 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002216 layersNeedingFences.add(layer);
2217 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002218 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002219 });
2220 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002221
2222 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2223
2224 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002225 displayDevice->setLayersNeedingFences(layersNeedingFences);
2226
2227 Region undefinedRegion{bounds};
2228 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2229
2230 display->editState().undefinedRegion = undefinedRegion;
2231 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002232 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002233 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002234}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002235
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002236// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002237// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002238// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002239// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002240// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002241// The returned HDR data space is one of
2242// - Dataspace::UNKNOWN
2243// - Dataspace::BT2020_HLG
2244// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2246 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002247 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002248 *outHdrDataSpace = Dataspace::UNKNOWN;
2249
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002250 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002251 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252 case Dataspace::V0_SCRGB:
2253 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002254 case Dataspace::BT2020:
2255 case Dataspace::BT2020_ITU:
2256 case Dataspace::BT2020_LINEAR:
2257 case Dataspace::DISPLAY_BT2020:
2258 bestDataSpace = Dataspace::DISPLAY_BT2020;
2259 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002260 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002261 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002262 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263 case Dataspace::BT2020_PQ:
2264 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002265 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002266 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002268 case Dataspace::BT2020_HLG:
2269 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002270 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002271 // When there's mixed PQ content and HLG content, we set the HDR
2272 // data space to be BT2020_PQ and convert HLG to PQ.
2273 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2274 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002275 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276 break;
2277 default:
2278 break;
2279 }
Romain Guy54f154a2017-10-24 21:40:32 +01002280 }
2281
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002283}
2284
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2287 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2289 *outMode = ColorMode::NATIVE;
2290 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002292 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002293 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002294
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002295 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002296 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002298 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2299
Peiyong Lina3ea5592019-02-10 14:45:00 -08002300 switch (mForceColorMode) {
2301 case ColorMode::SRGB:
2302 bestDataSpace = Dataspace::V0_SRGB;
2303 break;
2304 case ColorMode::DISPLAY_P3:
2305 bestDataSpace = Dataspace::DISPLAY_P3;
2306 break;
2307 default:
2308 break;
2309 }
2310
Peiyong Lindfde5112018-06-05 10:58:41 -07002311 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002312 const bool isHdr =
2313 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002314 if (isHdr) {
2315 bestDataSpace = hdrDataSpace;
2316 }
2317
Chia-I Wu0d711262018-05-21 15:19:35 -07002318 RenderIntent intent;
2319 switch (mDisplayColorSetting) {
2320 case DisplayColorSetting::MANAGED:
2321 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002322 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002323 break;
2324 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002325 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002326 break;
2327 default: // vendor display color setting
2328 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2329 break;
2330 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002331
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002332 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002333}
2334
Lloyd Pique32cbe282018-10-19 13:09:22 -07002335void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2336 auto display = displayDevice->getCompositionDisplay();
2337 const auto& displayState = display->getState();
2338
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002339 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002340 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2341 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002342
David Sodmanfa9b2af2017-12-24 13:28:59 -08002343 // If nothing has changed (!dirty), don't recompose.
2344 // If something changed, but we don't currently have any visible layers,
2345 // and didn't when we last did a composition, then skip it this time.
2346 // The second rule does two things:
2347 // - When all layers are removed from a display, we'll emit one black
2348 // frame, then nothing more until we get new layers.
2349 // - When a display is created with a private layer stack, we won't
2350 // emit any black frames until a layer is added to the layer stack.
2351 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002352
Dominik Laskowski075d3172018-05-24 15:50:06 -07002353 const char flagPrefix[] = {'-', '+'};
2354 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002355 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2356 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2357 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2358 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002359
Lloyd Pique31cb2942018-10-19 17:23:03 -07002360 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002361
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002363 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002364 }
2365}
2366
Lloyd Pique32cbe282018-10-19 13:09:22 -07002367void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2368 auto display = displayDevice->getCompositionDisplay();
2369 const auto& displayState = display->getState();
2370
2371 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002372 return;
David Sodman2b406362017-12-15 13:33:47 -08002373 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002375 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002377 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002378}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002379
Lloyd Pique32cbe282018-10-19 13:09:22 -07002380void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002381 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 ALOGV("doComposition");
2383
Lloyd Pique32cbe282018-10-19 13:09:22 -07002384 auto display = displayDevice->getCompositionDisplay();
2385 const auto& displayState = display->getState();
2386
2387 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002389 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002390
David Sodmanfa9b2af2017-12-24 13:28:59 -08002391 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002393
Lloyd Pique32cbe282018-10-19 13:09:22 -07002394 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002395 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002396 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002398}
2399
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400void SurfaceFlinger::postFrame()
2401{
2402 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 const auto display = getDefaultDisplayDeviceLocked();
2404 if (display && getHwComposer().isConnected(*display->getId())) {
2405 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2407 logFrameStats();
2408 }
2409 }
2410}
2411
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002413 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002415
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416 auto display = displayDevice->getCompositionDisplay();
2417 const auto& displayState = display->getState();
2418 const auto displayId = display->getId();
2419
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 if (displayId) {
2424 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002425 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002426 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002427 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002428 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002429 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002430
Chia-I Wu7b549592017-11-15 09:14:57 -08002431 // The layer buffer from the previous frame (if any) is released
2432 // by HWC only when the release fence from this frame (if any) is
2433 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002434 if (layer->getState().hwc) {
2435 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002436 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002437 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2438 usedClientComposition =
2439 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002440 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002441
2442 // If the layer was client composited in the previous frame, we
2443 // need to merge with the previous client target acquire fence.
2444 // Since we do not track that, always merge with the current
2445 // client target acquire fence when it is available, even though
2446 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002447 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002448 releaseFence =
2449 Fence::merge("LayerRelease", releaseFence,
2450 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002451 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002452
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002453 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 }
Chia-I Wu83806892017-11-16 10:50:20 -08002455
2456 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002458 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002461 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002463 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002464 }
2465 }
2466
Dominik Laskowski075d3172018-05-24 15:50:06 -07002467 if (displayId) {
2468 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002469 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002470 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471}
2472
Mathias Agopian87baae12012-07-31 12:38:26 -07002473void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474{
Mathias Agopian841cde52012-03-01 15:44:37 -08002475 ATRACE_CALL();
2476
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002477 // here we keep a copy of the drawing state (that is the state that's
2478 // going to be overwritten by handleTransactionLocked()) outside of
2479 // mStateLock so that the side-effects of the State assignment
2480 // don't happen with mStateLock held (which can cause deadlocks).
2481 State drawingState(mDrawingState);
2482
Mathias Agopianca4d3602011-05-19 15:38:14 -07002483 Mutex::Autolock _l(mStateLock);
2484 const nsecs_t now = systemTime();
2485 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486
Mathias Agopianca4d3602011-05-19 15:38:14 -07002487 // Here we're guaranteed that some transaction flags are set
2488 // so we can call handleTransactionLocked() unconditionally.
2489 // We call getTransactionFlags(), which will also clear the flags,
2490 // with mStateLock held to guarantee that mCurrentState won't change
2491 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002492
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002493 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002494 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002495 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002496
Mathias Agopianca4d3602011-05-19 15:38:14 -07002497 mLastTransactionTime = systemTime() - now;
2498 mDebugInTransaction = 0;
2499 invalidateHwcGeometry();
2500 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002501}
2502
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2504 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 const std::optional<DisplayIdentificationInfo> info =
2506 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002507
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002509 continue;
2510 }
2511
Lloyd Piqueba04e622017-12-14 17:11:26 -08002512 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002514 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 mPhysicalDisplayTokens[info->id] = new BBinder();
2516 DisplayDeviceState state;
2517 state.displayId = info->id;
2518 state.isSecure = true; // All physical displays are currently considered secure.
2519 state.displayName = info->name;
2520 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2521 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002522 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002523 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002524 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002525
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2527 if (index >= 0) {
2528 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2529 mInterceptor->saveDisplayDeletion(state.sequenceId);
2530 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002531 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533 }
2534
2535 processDisplayChangesLocked();
2536 }
2537
2538 mPendingHotplugEvents.clear();
2539}
2540
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002541void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002542 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2543 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002544}
2545
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002548 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 const sp<IGraphicBufferProducer>& producer) {
2550 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002551 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002553 creationArgs.isSecure = state.isSecure;
2554 creationArgs.displaySurface = dispSurface;
2555 creationArgs.hasWideColorGamut = false;
2556 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002557
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002558 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 creationArgs.isPrimary = isInternalDisplay;
2560
2561 if (useColorManagement && displayId) {
2562 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002564 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002565 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002566 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002567
Dominik Laskowski7e045462018-05-30 13:02:02 -07002568 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002570 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571 }
tangrobin6753a022018-08-10 10:58:54 +08002572 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 if (displayId) {
2575 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002576 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002578 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579
Lloyd Pique90c115d2018-09-18 21:39:42 -07002580 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002582 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002583
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 // Make sure that composition can never be stalled by a virtual display
2585 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002586 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002587 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2589 }
2590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 creationArgs.displayInstallOrientation =
2592 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002593
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596
Lloyd Pique90c115d2018-09-18 21:39:42 -07002597 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
2599 if (maxFrameBufferAcquiredBuffers >= 3) {
2600 nativeWindowSurface->preallocateBuffers();
2601 }
2602
2603 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002604 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002605 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002607 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002609 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2610 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 if (!state.isVirtual()) {
2612 LOG_ALWAYS_FATAL_IF(!displayId);
2613 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 display->setLayerStack(state.layerStack);
2617 display->setProjection(state.orientation, state.viewport, state.frame);
2618 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621}
2622
Lloyd Pique347200f2017-12-14 17:00:15 -08002623void SurfaceFlinger::processDisplayChangesLocked() {
2624 // here we take advantage of Vector's copy-on-write semantics to
2625 // improve performance by skipping the transaction entirely when
2626 // know that the lists are identical
2627 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2628 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2629 if (!curr.isIdenticalTo(draw)) {
2630 mVisibleRegionsDirty = true;
2631 const size_t cc = curr.size();
2632 size_t dc = draw.size();
2633
2634 // find the displays that were removed
2635 // (ie: in drawing state but not in current state)
2636 // also handle displays that changed
2637 // (ie: displays that are in both lists)
2638 for (size_t i = 0; i < dc;) {
2639 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2640 if (j < 0) {
2641 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002642 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002643 // Save display ID before disconnecting.
2644 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002645 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002646
2647 if (!display->isVirtual()) {
2648 LOG_ALWAYS_FATAL_IF(!displayId);
2649 dispatchDisplayHotplugEvent(displayId->value, false);
2650 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002651 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002652
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002654 } else {
2655 // this display is in both lists. see if something changed.
2656 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002658 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2659 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2660 if (state_binder != draw_binder) {
2661 // changing the surface is like destroying and
2662 // recreating the DisplayDevice, so we just remove it
2663 // from the drawing state, so that it get re-added
2664 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002665 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002666 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002667 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 mDrawingState.displays.removeItemsAt(i);
2670 dc--;
2671 // at this point we must loop to the next item
2672 continue;
2673 }
2674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002676 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002677 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002678 }
2679 if ((state.orientation != draw[i].orientation) ||
2680 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 }
2683 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 }
2686 }
2687 }
2688 ++i;
2689 }
2690
2691 // find displays that were added
2692 // (ie: in current state but not in drawing state)
2693 for (size_t i = 0; i < cc; i++) {
2694 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2695 const DisplayDeviceState& state(curr[i]);
2696
Lloyd Pique542307f2018-10-19 13:24:08 -07002697 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 sp<IGraphicBufferProducer> producer;
2699 sp<IGraphicBufferProducer> bqProducer;
2700 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002701 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002704 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 // Virtual displays without a surface are dormant:
2706 // they have external state (layer stack, projection,
2707 // etc.) but no internal state (i.e. a DisplayDevice).
2708 if (state.surface != nullptr) {
2709 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 int width = 0;
2712 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2713 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2714 int height = 0;
2715 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2716 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2717 int intFormat = 0;
2718 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2719 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002720 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 displayId =
2723 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 }
2725
2726 // TODO: Plumb requested format back up to consumer
2727
2728 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 bqProducer, bqConsumer,
2731 state.displayName);
2732
2733 dispSurface = vds;
2734 producer = vds;
2735 }
2736 } else {
2737 ALOGE_IF(state.surface != nullptr,
2738 "adding a supported display, but rendering "
2739 "surface is provided (%p), ignoring it",
2740 state.surface.get());
2741
Dominik Laskowski075d3172018-05-24 15:50:06 -07002742 displayId = state.displayId;
2743 LOG_ALWAYS_FATAL_IF(!displayId);
2744 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 producer = bqProducer;
2746 }
2747
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002750 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002751 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002752 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002753 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002754 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002755 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 }
2757 }
2758 }
2759 }
2760 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002761
2762 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002763}
2764
Mathias Agopian87baae12012-07-31 12:38:26 -07002765void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002766{
Dan Stoza7dde5992015-05-22 09:51:44 -07002767 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002768 mCurrentState.traverseInZOrder([](Layer* layer) {
2769 layer->notifyAvailableFrames();
2770 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 /*
2773 * Traversal of the children
2774 * (perform the transaction for each of them if needed)
2775 */
2776
Mathias Agopian3559b072012-08-15 13:46:03 -07002777 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002780 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
2782 const uint32_t flags = layer->doTransaction(0);
2783 if (flags & Layer::eVisibleRegion)
2784 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002785
2786 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002787 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002788 }
Robert Carr2047fae2016-11-28 14:09:09 -08002789 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 }
2791
2792 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002793 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 */
2795
Mathias Agopiane57f2922012-08-09 16:29:12 -07002796 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002797 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002798 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002799 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002801 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002802 // The transform hint might have changed for some layers
2803 // (either because a display has changed, or because a layer
2804 // as changed).
2805 //
2806 // Walk through all the layers in currentLayers,
2807 // and update their transform hint.
2808 //
2809 // If a layer is visible only on a single display, then that
2810 // display is used to calculate the hint, otherwise we use the
2811 // default display.
2812 //
2813 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2814 // the hint is set before we acquire a buffer from the surface texture.
2815 //
2816 // NOTE: layer transactions have taken place already, so we use their
2817 // drawing state. However, SurfaceFlinger's own transaction has not
2818 // happened yet, so we must use the current state layer list
2819 // (soon to become the drawing state list).
2820 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002822 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002823 bool first = true;
2824 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002825 // NOTE: we rely on the fact that layers are sorted by
2826 // layerStack first (so we don't have to traverse the list
2827 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002829 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002830 currentlayerStack = layerStack;
2831 // figure out if this layerstack is mirrored
2832 // (more than one display) if so, pick the default display,
2833 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 hintDisplay = nullptr;
2835 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002836 if (display->getCompositionDisplay()
2837 ->belongsInOutput(layer->getLayerStack(),
2838 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 if (hintDisplay) {
2840 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002841 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002842 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002843 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002844 }
2845 }
2846 }
2847 }
Chet Haase91d25932013-04-11 15:24:55 -07002848
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002850 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2851 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002852
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002853 // could be null when this layer is using a layerStack
2854 // that is not visible on any display. Also can occur at
2855 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002856 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002857 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002858
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002860 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002861 if (hintDisplay) {
2862 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002863 }
Robert Carr2047fae2016-11-28 14:09:09 -08002864
2865 first = false;
2866 });
Mathias Agopian84300952012-11-21 16:02:13 -08002867 }
2868
2869
Mathias Agopian3559b072012-08-15 13:46:03 -07002870 /*
2871 * Perform our own transaction if needed
2872 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873
2874 if (mLayersAdded) {
2875 mLayersAdded = false;
2876 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002877 mVisibleRegionsDirty = true;
2878 }
2879
2880 // some layers might have been removed, so
2881 // we need to update the regions they're exposing.
2882 if (mLayersRemoved) {
2883 mLayersRemoved = false;
2884 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002885 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002887 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002889 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002890 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002891 }
Robert Carr2047fae2016-11-28 14:09:09 -08002892 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 }
2894
Vishnu Nairec0ab382019-02-13 15:32:56 -08002895 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002897}
2898
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002899void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002900 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002901 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002902 return;
2903 }
2904
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002905 if (mVisibleRegionsDirty || mInputInfoChanged) {
2906 mInputInfoChanged = false;
2907 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002908 } else if (mInputWindowCommands.syncInputWindows) {
2909 // If the caller requested to sync input windows, but there are no
2910 // changes to input windows, notify immediately.
2911 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002912 }
2913
2914 executeInputWindowCommands();
2915}
2916
2917void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002918 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002919
2920 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2921 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002922 // When calculating the screen bounds we ignore the transparent region since it may
2923 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002924 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002925 }
2926 });
chaviw291d88a2019-02-14 10:33:58 -08002927
2928 mInputFlinger->setInputWindows(inputHandles,
2929 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2930 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002931}
2932
Vishnu Nairec0ab382019-02-13 15:32:56 -08002933void SurfaceFlinger::commitInputWindowCommands() {
2934 mInputWindowCommands.merge(mPendingInputWindowCommands);
2935 mPendingInputWindowCommands.clear();
2936}
2937
chaviwfbe5d9c2018-12-26 12:23:37 -08002938void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002939 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2940 if (transferTouchFocusCommand.fromToken != nullptr &&
2941 transferTouchFocusCommand.toToken != nullptr &&
2942 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2943 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2944 transferTouchFocusCommand.toToken);
2945 }
2946 }
2947
2948 mInputWindowCommands.clear();
2949}
2950
Riley Andrews03414a12014-07-01 14:22:59 -07002951void SurfaceFlinger::updateCursorAsync()
2952{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002953 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002954 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002955 continue;
2956 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002958 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2959 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002960 }
2961 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002962}
2963
chaviw61626f22018-11-15 16:26:27 -08002964void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2965 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002966 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002967 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002968 }
2969 layer->releasePendingBuffer(systemTime());
2970}
2971
Mathias Agopian4fec8732012-06-29 14:12:52 -07002972void SurfaceFlinger::commitTransaction()
2973{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002974 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 for (const auto& l : mLayersPendingRemoval) {
2977 recordBufferingStats(l->getName().string(),
2978 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002979
Lloyd Pique07e33212018-12-18 16:33:37 -08002980 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002981 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002982 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002983 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002984 }
2985 mLayersPendingRemoval.clear();
2986 }
2987
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002988 // If this transaction is part of a window animation then the next frame
2989 // we composite should be considered an animation as well.
2990 mAnimCompositionPending = mAnimTransactionPending;
2991
Nataniel Borges2b796da2019-02-15 13:32:18 -08002992 withTracingLock([&]() {
2993 mDrawingState = mCurrentState;
2994 // clear the "changed" flags in current state
2995 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002996
Nataniel Borges2b796da2019-02-15 13:32:18 -08002997 mDrawingState.traverseInZOrder([](Layer* layer) { layer->commitChildList(); });
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002999
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003000 mTransactionPending = false;
3001 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003}
3004
Nataniel Borges2b796da2019-02-15 13:32:18 -08003005void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3006 if (mTracingEnabledChanged) {
3007 mTracingEnabled = mTracing.isEnabled();
3008 mTracingEnabledChanged = false;
3009 }
3010
3011 // Synchronize with Tracing thread
3012 std::unique_lock<std::mutex> lock;
3013 if (mTracingEnabled) {
3014 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3015 }
3016
3017 lockedOperation();
3018
3019 // Synchronize with Tracing thread
3020 if (mTracingEnabled) {
3021 lock.unlock();
3022 }
3023}
3024
Lloyd Pique32cbe282018-10-19 13:09:22 -07003025void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003027 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003029
Lloyd Pique32cbe282018-10-19 13:09:22 -07003030 auto display = displayDevice->getCompositionDisplay();
3031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 Region aboveOpaqueLayers;
3033 Region aboveCoveredLayers;
3034 Region dirty;
3035
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Robert Carr2047fae2016-11-28 14:09:09 -08003038 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003039 // start with the whole surface at its current location
3040 const Layer::State& s(layer->getDrawingState());
3041
Jesse Hall01e29052013-02-19 16:13:35 -08003042 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003043 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003044 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003045 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003046
Mathias Agopianab028732010-03-16 16:41:46 -07003047 /*
3048 * opaqueRegion: area of a surface that is fully opaque.
3049 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003051
3052 /*
3053 * visibleRegion: area of a surface that is visible on screen
3054 * and not fully transparent. This is essentially the layer's
3055 * footprint minus the opaque regions above it.
3056 * Areas covered by a translucent surface are considered visible.
3057 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003059
3060 /*
3061 * coveredRegion: area of a surface that is covered by all
3062 * visible regions above it (which includes the translucent areas).
3063 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003065
Jesse Halla8026d22012-09-25 13:25:04 -07003066 /*
3067 * transparentRegion: area of a surface that is hinted to be completely
3068 * transparent. This is only used to tell when the layer has no visible
3069 * non-transparent regions and can be removed from the layer list. It
3070 * does not affect the visibleRegion of this layer or any layers
3071 * beneath it. The hint may not be correct if apps don't respect the
3072 * SurfaceView restrictions (which, sadly, some don't).
3073 */
3074 Region transparentRegion;
3075
Mathias Agopianab028732010-03-16 16:41:46 -07003076
3077 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003078 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003079 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003080 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003083 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003084 if (!visibleRegion.isEmpty()) {
3085 // Remove the transparent area from the visible region
3086 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003087 if (tr.preserveRects()) {
3088 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003090 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003091 // transformation too complex, can't do the
3092 // transparent region optimization.
3093 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 }
Mathias Agopianab028732010-03-16 16:41:46 -07003095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096
Mathias Agopianab028732010-03-16 16:41:46 -07003097 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003099 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003100 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003101 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003102 // the opaque region is the layer's footprint
3103 opaqueRegion = visibleRegion;
3104 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 }
3106 }
3107
Robert Carre5f4f692018-01-12 13:12:28 -08003108 if (visibleRegion.isEmpty()) {
3109 layer->clearVisibilityRegions();
3110 return;
3111 }
3112
Mathias Agopianab028732010-03-16 16:41:46 -07003113 // Clip the covered region to the visible region
3114 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3115
3116 // Update aboveCoveredLayers for next (lower) layer
3117 aboveCoveredLayers.orSelf(visibleRegion);
3118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 // subtract the opaque region covered by the layers above us
3120 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121
3122 // compute this layer's dirty region
3123 if (layer->contentDirty) {
3124 // we need to invalidate the whole region
3125 dirty = visibleRegion;
3126 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003127 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 layer->contentDirty = false;
3129 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003130 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003131 * the exposed region consists of two components:
3132 * 1) what's VISIBLE now and was COVERED before
3133 * 2) what's EXPOSED now less what was EXPOSED before
3134 *
3135 * note that (1) is conservative, we start with the whole
3136 * visible region but only keep what used to be covered by
3137 * something -- which mean it may have been exposed.
3138 *
3139 * (2) handles areas that were not covered by anything but got
3140 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003141 */
Mathias Agopianab028732010-03-16 16:41:46 -07003142 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003143 const Region oldVisibleRegion = layer->visibleRegion;
3144 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003145 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3146 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 }
3148 dirty.subtractSelf(aboveOpaqueLayers);
3149
3150 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003151 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152
Mathias Agopianab028732010-03-16 16:41:46 -07003153 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003155
Jesse Halla8026d22012-09-25 13:25:04 -07003156 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 layer->setVisibleRegion(visibleRegion);
3158 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003159 layer->setVisibleNonTransparentRegion(
3160 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003161 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopian87baae12012-07-31 12:38:26 -07003163 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164}
3165
Chia-I Wuab0c3192017-08-01 11:29:00 -07003166void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003167 for (const auto& [token, displayDevice] : mDisplays) {
3168 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003169 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003170 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003171 }
3172 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003173}
3174
Dan Stoza6b9454d2014-11-07 16:00:59 -08003175bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003177 ALOGV("handlePageFlip");
3178
Brian Andersond6927fb2016-07-23 23:37:30 -07003179 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
Mathias Agopian4fec8732012-06-29 14:12:52 -07003181 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003182 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003183 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003184
3185 // Store the set of layers that need updates. This set must not change as
3186 // buffers are being latched, as this could result in a deadlock.
3187 // Example: Two producers share the same command stream and:
3188 // 1.) Layer 0 is latched
3189 // 2.) Layer 0 gets a new frame
3190 // 2.) Layer 1 gets a new frame
3191 // 3.) Layer 1 is latched.
3192 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3193 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003195 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003196 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003197 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003198 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003199 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003201 } else {
3202 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003203 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003204 } else {
3205 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003206 }
Robert Carr2047fae2016-11-28 14:09:09 -08003207 });
3208
Lloyd Piquef2c79392018-12-20 16:23:33 -08003209 if (!mLayersWithQueuedFrames.empty()) {
3210 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3211 // writes to Layer current state. See also b/119481871
3212 Mutex::Autolock lock(mStateLock);
3213
3214 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003215 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003216 mLayersPendingRefresh.push_back(layer);
3217 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003218 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003219 if (layer->isBufferLatched()) {
3220 newDataLatched = true;
3221 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003222 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003223 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003224
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003225 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003226
3227 // If we will need to wake up at some time in the future to deal with a
3228 // queued frame that shouldn't be displayed during this vsync period, wake
3229 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003230 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 signalLayerUpdate();
3232 }
3233
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003234 // enter boot animation on first buffer latch
3235 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3236 ALOGI("Enter boot animation");
3237 mBootStage = BootStage::BOOTANIMATION;
3238 }
3239
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003241 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopianad456f92011-01-13 17:53:01 -08003244void SurfaceFlinger::invalidateHwcGeometry()
3245{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003246 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003247}
3248
Lloyd Pique32cbe282018-10-19 13:09:22 -07003249void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003250 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003251 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003252 // We only need to actually compose the display if:
3253 // 1) It is being handled by hardware composer, which may need this to
3254 // keep its virtual display state machine in sync, or
3255 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003256 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003257 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003258 return;
3259 }
3260
Dan Stoza9e56aa02015-11-02 13:00:03 -08003261 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003262 base::unique_fd readyFence;
3263 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003264
3265 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003266 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267}
3268
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003269bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3270 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003271 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003272 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003273
Lloyd Pique32cbe282018-10-19 13:09:22 -07003274 auto display = displayDevice->getCompositionDisplay();
3275 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003276 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003277 auto& renderEngine = getRenderEngine();
3278 const bool supportProtectedContent =
3279 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003280
3281 const Region bounds(displayState.bounds);
3282 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003283 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003284 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003285
Peiyong Lind3788632018-09-18 16:01:31 -07003286 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003287 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003288
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003289 renderengine::DisplaySettings clientCompositionDisplay;
3290 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3291 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003292 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003293
Dan Stoza9e56aa02015-11-02 13:00:03 -08003294 if (hasClientComposition) {
3295 ALOGV("hasClientComposition");
3296
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003297 if (displayDevice->isPrimary() && supportProtectedContent) {
3298 bool needsProtected = false;
3299 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3300 // If the layer is a protected layer, mark protected context is needed.
3301 if (layer->isProtected()) {
3302 needsProtected = true;
3303 break;
3304 }
3305 }
3306 if (needsProtected != renderEngine.isProtected() &&
3307 renderEngine.useProtectedContext(needsProtected)) {
3308 display->getRenderSurface()->setProtected(needsProtected);
3309 }
3310 }
3311
Alec Mouri6338c9d2019-02-07 16:57:51 -08003312 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003313
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003314 if (buf == nullptr) {
3315 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3316 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003317 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003318 return false;
3319 }
3320
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003321 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3322 clientCompositionDisplay.clip = displayState.scissor;
3323 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003324 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003325
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003326 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003327 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003328 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003330 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003331 clientCompositionDisplay.outputDataspace = outputDataspace;
3332 clientCompositionDisplay.maxLuminance =
3333 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003334
Lloyd Pique441d5042018-10-18 16:49:51 -07003335 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003336 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003337 getHwComposer()
3338 .hasDisplayCapability(displayId,
3339 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003340
Peiyong Lind3788632018-09-18 16:01:31 -07003341 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003342 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3343 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003344 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003345 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003346 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003347
Mathias Agopian85d751c2012-08-29 16:59:24 -07003348 /*
3349 * and then, render the layers targeted at the framebuffer
3350 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003351
Dan Stoza9e56aa02015-11-02 13:00:03 -08003352 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003353 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003354 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003355 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003356 const Region viewportRegion(displayState.viewport);
3357 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003358 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003359 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003360 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003361 switch (layer->getCompositionType(displayDevice)) {
3362 case Hwc2::IComposerClient::Composition::CURSOR:
3363 case Hwc2::IComposerClient::Composition::DEVICE:
3364 case Hwc2::IComposerClient::Composition::SIDEBAND:
3365 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003366 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003367 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003368 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003369 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003370 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003371 // never clear the very first layer since we're
3372 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 renderengine::LayerSettings layerSettings;
3374 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003375 bool prepared =
3376 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3377 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003378
3379 if (prepared) {
3380 layerSettings.source.buffer.buffer = nullptr;
3381 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3382 layerSettings.alpha = half(0.0);
3383 layerSettings.disableBlending = true;
3384 clientCompositionLayers.push_back(layerSettings);
3385 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003386 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003387 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003388 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003389 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390 renderengine::LayerSettings layerSettings;
3391 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003392 layer->prepareClientLayer(renderArea, clip, clearRegion,
3393 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003394 if (prepared) {
3395 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003396 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003397 break;
3398 }
3399 default:
3400 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003401 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003402 } else {
3403 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003404 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003405 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003406 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003407
Alec Mouri820c7402019-01-23 13:02:39 -08003408 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003409 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003410 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003411
3412 // We boost GPU frequency here because there will be color spaces conversion
3413 // and it's expensive. We boost the GPU frequency so that GPU composition can
3414 // finish in time. We must reset GPU frequency afterwards, because high frequency
3415 // consumes extra battery.
3416 const bool expensiveRenderingExpected =
3417 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3418 if (expensiveRenderingExpected && displayId) {
3419 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3420 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003421 if (!debugRegion.isEmpty()) {
3422 Region::const_iterator it = debugRegion.begin();
3423 Region::const_iterator end = debugRegion.end();
3424 while (it != end) {
3425 const Rect& rect = *it++;
3426 renderengine::LayerSettings layerSettings;
3427 layerSettings.source.buffer.buffer = nullptr;
3428 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3429 layerSettings.geometry.boundaries = rect.toFloatRect();
3430 layerSettings.alpha = half(1.0);
3431 clientCompositionLayers.push_back(layerSettings);
3432 }
3433 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003434 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3435 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003436 if (expensiveRenderingExpected && displayId) {
3437 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3438 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003439 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003440 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441}
3442
Chia-I Wu28e3a252018-09-07 12:05:02 -07003443void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003444 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003445 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446}
3447
Dan Stoza7d89d062015-04-30 13:29:25 -07003448status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003449 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003450 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003451 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003452 const sp<Layer>& parent,
3453 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003454{
Dan Stoza7d89d062015-04-30 13:29:25 -07003455 // add this layer to the current state list
3456 {
3457 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003458 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003459 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3460 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003461 return NO_MEMORY;
3462 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003463 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003464 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003465 } else if (parent == nullptr) {
3466 lbc->onRemovedFromCurrentState();
3467 } else if (parent->isRemovedFromCurrentState()) {
3468 parent->addChild(lbc);
3469 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003470 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003471 parent->addChild(lbc);
3472 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003473
Yiwei Zhang243b3782018-05-15 17:40:04 -07003474 if (gbc != nullptr) {
3475 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3476 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3477 mMaxGraphicBufferProducerListSize,
3478 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3479 mGraphicBufferProducerList.size(),
3480 mMaxGraphicBufferProducerListSize, mNumLayers);
3481 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003482 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003483 }
3484
Mathias Agopian96f08192010-06-02 23:28:45 -07003485 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003486 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003487
Dan Stoza7d89d062015-04-30 13:29:25 -07003488 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003489}
3490
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003491uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003492 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003493}
3494
Mathias Agopian3f844832013-08-07 21:24:32 -07003495uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003496 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497}
3498
Mathias Agopian3f844832013-08-07 21:24:32 -07003499uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003500 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003501}
3502
3503uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003504 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003505 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003506 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003508 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 }
3510 return old;
3511}
3512
Marissa Wall713b63f2018-10-17 15:42:43 -07003513bool SurfaceFlinger::flushTransactionQueues() {
3514 Mutex::Autolock _l(mStateLock);
3515 auto it = mTransactionQueues.begin();
3516 while (it != mTransactionQueues.end()) {
3517 auto& [applyToken, transactionQueue] = *it;
3518
3519 while (!transactionQueue.empty()) {
Marissa Wall78b72202019-03-15 14:58:34 -07003520 const auto&
3521 [states, displays, flags, desiredPresentTime, uncacheBuffer, postTime,
3522 privileged] = transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003523 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003524 break;
3525 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003526 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003527 desiredPresentTime, uncacheBuffer, postTime, privileged,
3528 /*isMainThread*/ true);
Marissa Wall713b63f2018-10-17 15:42:43 -07003529 transactionQueue.pop();
3530 }
3531
3532 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3533 }
3534 return mTransactionQueues.empty();
3535}
3536
chaviwca27f252018-02-06 16:46:39 -08003537bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3538 for (const ComposerState& state : states) {
3539 // Here we need to check that the interface we're given is indeed
3540 // one of our own. A malicious client could give us a nullptr
3541 // IInterface, or one of its own or even one of our own but a
3542 // different type. All these situations would cause us to crash.
3543 if (state.client == nullptr) {
3544 return true;
3545 }
3546
3547 sp<IBinder> binder = IInterface::asBinder(state.client);
3548 if (binder == nullptr) {
3549 return true;
3550 }
3551
3552 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3553 return true;
3554 }
3555 }
3556 return false;
3557}
3558
Marissa Wall17b4e452018-12-26 16:32:34 -08003559bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3560 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003561 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003562 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3563 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3564 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3565 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3566 return false;
3567 }
3568
Marissa Wall713b63f2018-10-17 15:42:43 -07003569 for (const ComposerState& state : states) {
3570 const layer_state_t& s = state.state;
3571 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3572 continue;
3573 }
3574 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003575 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003576 }
3577 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003578 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003579}
3580
3581void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3582 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003583 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003584 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003585 int64_t desiredPresentTime,
3586 const cached_buffer_t& uncacheBuffer) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003587 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003588
Valerie Haubc6ddb12019-03-08 11:10:15 -08003589 const int64_t postTime = systemTime();
3590
Robert Carr14167e02019-02-13 13:50:55 -08003591 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3592
Mathias Agopian698c0872011-06-28 19:09:31 -07003593 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594
chaviwca27f252018-02-06 16:46:39 -08003595 if (containsAnyInvalidClientState(states)) {
3596 return;
3597 }
3598
Marissa Wall713b63f2018-10-17 15:42:43 -07003599 // If its TransactionQueue already has a pending TransactionState or if it is pending
3600 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003601 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003602 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall78b72202019-03-15 14:58:34 -07003603 uncacheBuffer, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003604 setTransactionFlags(eTransactionNeeded);
3605 return;
3606 }
3607
Valerie Haubc6ddb12019-03-08 11:10:15 -08003608 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall78b72202019-03-15 14:58:34 -07003609 uncacheBuffer, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003610}
3611
3612void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003613 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003614 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003615 const int64_t desiredPresentTime,
3616 const cached_buffer_t& uncacheBuffer,
3617 const int64_t postTime, bool privileged,
3618 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003619 uint32_t transactionFlags = 0;
3620
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003621 if (flags & eAnimation) {
3622 // For window updates that are part of an animation we must wait for
3623 // previous animation "frames" to be handled.
3624 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003625 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003626 if (CC_UNLIKELY(err != NO_ERROR)) {
3627 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003628 // caller after a few seconds.
3629 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3630 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003631 mAnimTransactionPending = false;
3632 break;
3633 }
3634 }
3635 }
3636
chaviwca27f252018-02-06 16:46:39 -08003637 for (const DisplayState& display : displays) {
3638 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003639 }
3640
Marissa Walle2ffb422018-10-12 11:33:52 -07003641 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003642 for (const ComposerState& state : states) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003643 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged);
chaviwca27f252018-02-06 16:46:39 -08003644 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003645 // If the state doesn't require a traversal and there are callbacks, send them now
3646 if (!(clientStateFlags & eTraversalNeeded)) {
3647 mTransactionCompletedThread.sendCallbacks();
3648 }
3649 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003650
chaviw273171b2018-12-26 11:46:30 -08003651 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3652
Marissa Wall78b72202019-03-15 14:58:34 -07003653 if (uncacheBuffer.token) {
3654 BufferStateLayerCache::getInstance().erase(uncacheBuffer.token, uncacheBuffer.cacheId);
3655 }
3656
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003657 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3658 // anyway. This can be used as a flush mechanism for previous async transactions.
3659 // Empty animation transaction can be used to simulate back-pressure, so also force a
3660 // transaction for empty animation transactions.
3661 if (transactionFlags == 0 &&
3662 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003663 transactionFlags = eTransactionNeeded;
3664 }
3665
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003667 if (mInterceptor->isEnabled()) {
3668 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003669 }
Irvel468051e2016-06-13 16:44:44 -07003670
Mathias Agopian386aa982011-11-07 21:58:03 -08003671 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003672 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3673 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003674 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003675
3676 // if this is a synchronous transaction, wait for it to take effect
3677 // before returning.
3678 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003681 if (flags & eAnimation) {
3682 mAnimTransactionPending = true;
3683 }
chaviw95ef3c42019-02-14 10:55:09 -08003684
3685 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
Valerie Hau0779ded2019-03-19 12:43:04 -07003686
3687 // applyTransactionState can be called by either the main SF thread or by
3688 // another process through setTransactionState. While a given process may wish
3689 // to wait on synchronous transactions, the main SF thread should never
3690 // be blocked. Therefore, we only wait if isMainThread is false.
3691 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003692 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3693 if (CC_UNLIKELY(err != NO_ERROR)) {
3694 // just in case something goes wrong in SF, return to the
3695 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003696 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3697 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003698 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003699 break;
3700 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003702 }
3703}
3704
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003705uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3706 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3707 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003708
Mathias Agopiane57f2922012-08-09 16:29:12 -07003709 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003710 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3711
3712 const uint32_t what = s.what;
3713 if (what & DisplayState::eSurfaceChanged) {
3714 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3715 state.surface = s.surface;
3716 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003717 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003719 if (what & DisplayState::eLayerStackChanged) {
3720 if (state.layerStack != s.layerStack) {
3721 state.layerStack = s.layerStack;
3722 flags |= eDisplayTransactionNeeded;
3723 }
3724 }
3725 if (what & DisplayState::eDisplayProjectionChanged) {
3726 if (state.orientation != s.orientation) {
3727 state.orientation = s.orientation;
3728 flags |= eDisplayTransactionNeeded;
3729 }
3730 if (state.frame != s.frame) {
3731 state.frame = s.frame;
3732 flags |= eDisplayTransactionNeeded;
3733 }
3734 if (state.viewport != s.viewport) {
3735 state.viewport = s.viewport;
3736 flags |= eDisplayTransactionNeeded;
3737 }
3738 }
3739 if (what & DisplayState::eDisplaySizeChanged) {
3740 if (state.width != s.width) {
3741 state.width = s.width;
3742 flags |= eDisplayTransactionNeeded;
3743 }
3744 if (state.height != s.height) {
3745 state.height = s.height;
3746 flags |= eDisplayTransactionNeeded;
3747 }
3748 }
3749
Mathias Agopiane57f2922012-08-09 16:29:12 -07003750 return flags;
3751}
3752
Robert Carr14167e02019-02-13 13:50:55 -08003753bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003754 IPCThreadState* ipc = IPCThreadState::self();
3755 const int pid = ipc->getCallingPid();
3756 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003757 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003758 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003759 return false;
3760 }
3761 return true;
3762}
3763
Robert Carr14167e02019-02-13 13:50:55 -08003764uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003765 int64_t desiredPresentTime, int64_t postTime,
3766 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003767 const layer_state_t& s = composerState.state;
3768 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3769
Mathias Agopian13127d82013-03-05 17:47:11 -08003770 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003771 if (layer == nullptr) {
3772 return 0;
3773 }
3774
chaviw8b3871a2017-11-01 17:41:01 -07003775 uint32_t flags = 0;
3776
Garfield Tan8a3083e2018-12-03 13:21:07 -08003777 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003778 bool geometryAppliesWithResize =
3779 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003780
3781 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3782 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003783 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003784 layer->pushPendingState();
3785 }
3786
chaviw8b3871a2017-11-01 17:41:01 -07003787 if (what & layer_state_t::ePositionChanged) {
3788 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3789 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003790 }
chaviw8b3871a2017-11-01 17:41:01 -07003791 }
3792 if (what & layer_state_t::eLayerChanged) {
3793 // NOTE: index needs to be calculated before we update the state
3794 const auto& p = layer->getParent();
3795 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003796 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003797 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003798 mCurrentState.layersSortedByZ.removeAt(idx);
3799 mCurrentState.layersSortedByZ.add(layer);
3800 // we need traversal (state changed)
3801 // AND transaction (list changed)
3802 flags |= eTransactionNeeded|eTraversalNeeded;
3803 }
chaviw8b3871a2017-11-01 17:41:01 -07003804 } else {
3805 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003806 flags |= eTransactionNeeded|eTraversalNeeded;
3807 }
3808 }
chaviw8b3871a2017-11-01 17:41:01 -07003809 }
3810 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003811 // NOTE: index needs to be calculated before we update the state
3812 const auto& p = layer->getParent();
3813 if (p == nullptr) {
3814 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3815 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3816 mCurrentState.layersSortedByZ.removeAt(idx);
3817 mCurrentState.layersSortedByZ.add(layer);
3818 // we need traversal (state changed)
3819 // AND transaction (list changed)
3820 flags |= eTransactionNeeded|eTraversalNeeded;
3821 }
3822 } else {
3823 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3824 flags |= eTransactionNeeded|eTraversalNeeded;
3825 }
chaviw8b3871a2017-11-01 17:41:01 -07003826 }
3827 }
3828 if (what & layer_state_t::eSizeChanged) {
3829 if (layer->setSize(s.w, s.h)) {
3830 flags |= eTraversalNeeded;
3831 }
3832 }
3833 if (what & layer_state_t::eAlphaChanged) {
3834 if (layer->setAlpha(s.alpha))
3835 flags |= eTraversalNeeded;
3836 }
3837 if (what & layer_state_t::eColorChanged) {
3838 if (layer->setColor(s.color))
3839 flags |= eTraversalNeeded;
3840 }
Peiyong Lind3788632018-09-18 16:01:31 -07003841 if (what & layer_state_t::eColorTransformChanged) {
3842 if (layer->setColorTransform(s.colorTransform)) {
3843 flags |= eTraversalNeeded;
3844 }
3845 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003846 if (what & layer_state_t::eBackgroundColorChanged) {
3847 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3848 flags |= eTraversalNeeded;
3849 }
3850 }
chaviw8b3871a2017-11-01 17:41:01 -07003851 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003852 // TODO: b/109894387
3853 //
3854 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3855 // rotation. To see the problem observe that if we have a square parent, and a child
3856 // of the same size, then we rotate the child 45 degrees around it's center, the child
3857 // must now be cropped to a non rectangular 8 sided region.
3858 //
3859 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3860 // private API, and the WindowManager only uses rotation in one case, which is on a top
3861 // level layer in which cropping is not an issue.
3862 //
3863 // However given that abuse of rotation matrices could lead to surfaces extending outside
3864 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3865 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3866 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003867 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003868 flags |= eTraversalNeeded;
3869 }
3870 if (what & layer_state_t::eTransparentRegionChanged) {
3871 if (layer->setTransparentRegionHint(s.transparentRegion))
3872 flags |= eTraversalNeeded;
3873 }
3874 if (what & layer_state_t::eFlagsChanged) {
3875 if (layer->setFlags(s.flags, s.mask))
3876 flags |= eTraversalNeeded;
3877 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003878 if (what & layer_state_t::eCropChanged_legacy) {
3879 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003880 flags |= eTraversalNeeded;
3881 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003882 if (what & layer_state_t::eCornerRadiusChanged) {
3883 if (layer->setCornerRadius(s.cornerRadius))
3884 flags |= eTraversalNeeded;
3885 }
chaviw8b3871a2017-11-01 17:41:01 -07003886 if (what & layer_state_t::eLayerStackChanged) {
3887 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3888 // We only allow setting layer stacks for top level layers,
3889 // everything else inherits layer stack from its parent.
3890 if (layer->hasParent()) {
3891 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3892 layer->getName().string());
3893 } else if (idx < 0) {
3894 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3895 "that also does not appear in the top level layer list. Something"
3896 " has gone wrong.", layer->getName().string());
3897 } else if (layer->setLayerStack(s.layerStack)) {
3898 mCurrentState.layersSortedByZ.removeAt(idx);
3899 mCurrentState.layersSortedByZ.add(layer);
3900 // we need traversal (state changed)
3901 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003902 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003903 }
3904 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003905 if (what & layer_state_t::eDeferTransaction_legacy) {
3906 if (s.barrierHandle_legacy != nullptr) {
3907 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3908 } else if (s.barrierGbp_legacy != nullptr) {
3909 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (authenticateSurfaceTextureLocked(gbp)) {
3911 const auto& otherLayer =
3912 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003913 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003914 } else {
3915 ALOGE("Attempt to defer transaction to to an"
3916 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003917 }
3918 }
chaviw8b3871a2017-11-01 17:41:01 -07003919 // We don't trigger a traversal here because if no other state is
3920 // changed, we don't want this to cause any more work
3921 }
3922 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003923 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003924 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003925 if (!hadParent) {
3926 mCurrentState.layersSortedByZ.remove(layer);
3927 }
chaviw8b3871a2017-11-01 17:41:01 -07003928 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003929 }
chaviw8b3871a2017-11-01 17:41:01 -07003930 }
3931 if (what & layer_state_t::eReparentChildren) {
3932 if (layer->reparentChildren(s.reparentHandle)) {
3933 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003934 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003935 }
chaviw8b3871a2017-11-01 17:41:01 -07003936 if (what & layer_state_t::eDetachChildren) {
3937 layer->detachChildren();
3938 }
3939 if (what & layer_state_t::eOverrideScalingModeChanged) {
3940 layer->setOverrideScalingMode(s.overrideScalingMode);
3941 // We don't trigger a traversal here because if no other state is
3942 // changed, we don't want this to cause any more work
3943 }
Marissa Wall61c58622018-07-18 10:12:20 -07003944 if (what & layer_state_t::eTransformChanged) {
3945 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3946 }
3947 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3948 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3949 flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eCropChanged) {
3952 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3953 }
Marissa Wall861616d2018-10-22 12:52:23 -07003954 if (what & layer_state_t::eFrameChanged) {
3955 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3956 }
Marissa Wall61c58622018-07-18 10:12:20 -07003957 if (what & layer_state_t::eAcquireFenceChanged) {
3958 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eDataspaceChanged) {
3961 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eHdrMetadataChanged) {
3964 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3965 }
3966 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3967 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3968 }
3969 if (what & layer_state_t::eApiChanged) {
3970 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3971 }
3972 if (what & layer_state_t::eSidebandStreamChanged) {
3973 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3974 }
Robert Carr720e5062018-07-30 17:45:14 -07003975 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003976 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003977 layer->setInputInfo(s.inputInfo);
3978 flags |= eTraversalNeeded;
3979 } else {
3980 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3981 }
Robert Carr720e5062018-07-30 17:45:14 -07003982 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003983 if (what & layer_state_t::eMetadataChanged) {
3984 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3985 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003986 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3987 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3988 flags |= eTraversalNeeded;
3989 }
3990 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003991 std::vector<sp<CallbackHandle>> callbackHandles;
3992 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3993 mTransactionCompletedThread.run();
3994 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3995 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3996 }
3997 }
Marissa Wall78b72202019-03-15 14:58:34 -07003998 bool bufferChanged = what & layer_state_t::eBufferChanged;
3999 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4000 sp<GraphicBuffer> buffer;
4001 if (bufferChanged && cacheIdChanged) {
4002 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.cacheId,
Marissa Wall73411622019-01-25 10:45:41 -08004003 s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004004 buffer = s.buffer;
4005 } else if (cacheIdChanged) {
4006 buffer = BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4007 s.cachedBuffer.cacheId);
4008 } else if (bufferChanged) {
4009 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004010 }
Marissa Wall78b72202019-03-15 14:58:34 -07004011 if (buffer) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004012 if (layer->setBuffer(buffer)) {
4013 flags |= eTraversalNeeded;
4014 layer->setPostTime(postTime);
4015 layer->setDesiredPresentTime(desiredPresentTime);
4016 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004017 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004018 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4019 // Do not put anything that updates layer state or modifies flags after
4020 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004021 return flags;
4022}
4023
chaviw273171b2018-12-26 11:46:30 -08004024uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4025 uint32_t flags = 0;
4026 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4027 flags |= eTraversalNeeded;
4028 }
4029
chaviwa911b102019-02-14 10:18:33 -08004030 if (inputWindowCommands.syncInputWindows) {
4031 flags |= eTraversalNeeded;
4032 }
4033
Vishnu Nairec0ab382019-02-13 15:32:56 -08004034 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004035 return flags;
4036}
4037
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004038status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4039 uint32_t h, PixelFormat format, uint32_t flags,
4040 LayerMetadata metadata, sp<IBinder>* handle,
4041 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004042 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004043 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004044 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004045 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004046 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004047
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004048 status_t result = NO_ERROR;
4049
4050 sp<Layer> layer;
4051
Cody Northropbc755282017-03-31 12:00:08 -06004052 String8 uniqueName = getUniqueLayerName(name);
4053
Evan Roskya1f1e152019-01-24 16:17:46 -08004054 bool primaryDisplayOnly = false;
4055
4056 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4057 // TODO b/64227542
4058 if (metadata.has(METADATA_WINDOW_TYPE)) {
4059 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4060 if (windowType == 441731) {
4061 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4062 primaryDisplayOnly = true;
4063 }
4064 }
4065
Mathias Agopian3165cc22012-08-08 19:42:09 -07004066 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004067 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004068 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4069 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004072 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004073 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4074 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004075 break;
chaviw13fdc492017-06-27 12:40:18 -07004076 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004077 // check if buffer size is set for color layer.
4078 if (w > 0 || h > 0) {
4079 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4080 int(w), int(h));
4081 return BAD_VALUE;
4082 }
4083
Evan Roskya1f1e152019-01-24 16:17:46 -08004084 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4085 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004086 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004087 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004088 // check if buffer size is set for container layer.
4089 if (w > 0 || h > 0) {
4090 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4091 int(w), int(h));
4092 return BAD_VALUE;
4093 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004094 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4095 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004096 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004097 default:
4098 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 break;
4100 }
4101
Dan Stoza7d89d062015-04-30 13:29:25 -07004102 if (result != NO_ERROR) {
4103 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004105
Evan Roskya1f1e152019-01-24 16:17:46 -08004106 if (primaryDisplayOnly) {
4107 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004108 }
4109
Robert Carrb89ea9d2018-12-10 13:01:14 -08004110 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4111 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4112 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004113 if (result != NO_ERROR) {
4114 return result;
4115 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004116 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004117
4118 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004119 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120}
4121
Cody Northropbc755282017-03-31 12:00:08 -06004122String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4123{
4124 bool matchFound = true;
4125 uint32_t dupeCounter = 0;
4126
4127 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4128 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4129
Dan Stoza436ccf32018-06-21 12:10:12 -07004130 // Grab the state lock since we're accessing mCurrentState
4131 Mutex::Autolock lock(mStateLock);
4132
Cody Northropbc755282017-03-31 12:00:08 -06004133 // Loop over layers until we're sure there is no matching name
4134 while (matchFound) {
4135 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004136 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004137 if (layer->getName() == uniqueName) {
4138 matchFound = true;
4139 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4140 }
4141 });
4142 }
4143
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004144 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4145 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004146
4147 return uniqueName;
4148}
4149
Marissa Wallfd668622018-05-10 10:21:13 -07004150status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4151 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004152 LayerMetadata metadata, PixelFormat& format,
4153 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004154 sp<IGraphicBufferProducer>* gbp,
4155 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004157 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158 case PIXEL_FORMAT_TRANSPARENT:
4159 case PIXEL_FORMAT_TRANSLUCENT:
4160 format = PIXEL_FORMAT_RGBA_8888;
4161 break;
4162 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004163 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164 break;
4165 }
4166
Evan Roskya1f1e152019-01-24 16:17:46 -08004167 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4168 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004169 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004170 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004171 *handle = layer->getHandle();
4172 *gbp = layer->getProducer();
4173 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004175
Marissa Wallfd668622018-05-10 10:21:13 -07004176 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004177 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004178}
4179
Marissa Wall61c58622018-07-18 10:12:20 -07004180status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4181 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004182 LayerMetadata metadata, sp<IBinder>* handle,
4183 sp<Layer>* outLayer) {
4184 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4185 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004186 *handle = layer->getHandle();
4187 *outLayer = layer;
4188
4189 return NO_ERROR;
4190}
4191
Evan Roskya1f1e152019-01-24 16:17:46 -08004192status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4193 uint32_t h, uint32_t flags, LayerMetadata metadata,
4194 sp<IBinder>* handle, sp<Layer>* outLayer) {
4195 *outLayer = getFactory().createColorLayer(
4196 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004197 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004199}
4200
Evan Roskya1f1e152019-01-24 16:17:46 -08004201status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4202 uint32_t w, uint32_t h, uint32_t flags,
4203 LayerMetadata metadata, sp<IBinder>* handle,
4204 sp<Layer>* outLayer) {
4205 *outLayer = getFactory().createContainerLayer(
4206 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004207 *handle = (*outLayer)->getHandle();
4208 return NO_ERROR;
4209}
4210
4211
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004212void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004213 mLayersPendingRemoval.add(layer);
4214 mLayersRemoved = true;
4215 setTransactionFlags(eTransactionNeeded);
4216}
4217
Robert Carr695d5282018-12-18 15:27:58 -08004218void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004219{
Robert Carr2e102c92018-10-23 12:11:15 -07004220 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004221 // If a layer has a parent, we allow it to out-live it's handle
4222 // with the idea that the parent holds a reference and will eventually
4223 // be cleaned up. However no one cleans up the top-level so we do so
4224 // here.
4225 if (layer->getParent() == nullptr) {
4226 mCurrentState.layersSortedByZ.remove(layer);
4227 }
4228 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004229 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004230}
4231
Mathias Agopianb60314a2012-04-10 22:09:54 -07004232// ---------------------------------------------------------------------------
4233
Andy McFadden13a082e2012-08-24 10:16:42 -07004234void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004235 const auto display = getDefaultDisplayDeviceLocked();
4236 if (!display) return;
4237
4238 const sp<IBinder> token = display->getDisplayToken().promote();
4239 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004240
Jesse Hall01e29052013-02-19 16:13:35 -08004241 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004242 Vector<ComposerState> state;
4243 Vector<DisplayState> displays;
4244 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004245 d.what = DisplayState::eDisplayProjectionChanged |
4246 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004247 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004248 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004249 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004250 d.frame.makeInvalid();
4251 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004252 d.width = 0;
4253 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004254 displays.add(d);
Marissa Wall78b72202019-03-15 14:58:34 -07004255 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004256
Dominik Laskowskie9774092018-12-11 10:04:24 -08004257 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004258
Dominik Laskowski83b88212018-12-11 13:34:06 -08004259 const nsecs_t vsyncPeriod = getVsyncPeriod();
4260 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004261
Brian Andersond0010582017-03-07 13:20:31 -08004262 // Use phase of 0 since phase is not known.
4263 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004264 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004265 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004266}
4267
4268void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004269 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004270 postMessageAsync(
4271 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004272}
4273
Dominik Laskowskie9774092018-12-11 10:04:24 -08004274void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275 if (display->isVirtual()) {
4276 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004277 return;
4278 }
4279
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280 const auto displayId = display->getId();
4281 LOG_ALWAYS_FATAL_IF(!displayId);
4282
Dominik Laskowski34157762018-10-31 13:07:19 -07004283 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004284
4285 int currentMode = display->getPowerMode();
4286 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004287 return;
4288 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 display->setPowerMode(mode);
4291
Lloyd Pique4dccc412018-01-22 17:21:36 -08004292 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004293 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004294 }
4295
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004296 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004297 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004300 mScheduler->onScreenAcquired(mAppConnectionHandle);
4301 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004305 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004306 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004307
4308 struct sched_param param = {0};
4309 param.sched_priority = 1;
4310 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4311 ALOGW("Couldn't set SCHED_FIFO on display on");
4312 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004313 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004314 // Turn off the display
4315 struct sched_param param = {0};
4316 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4317 ALOGW("Couldn't set SCHED_OTHER on display off");
4318 }
4319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004321 mScheduler->disableHardwareVsync(true);
4322 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004323 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004324
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004326 mVisibleRegionsDirty = true;
4327 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004328 } else if (mode == HWC_POWER_MODE_DOZE ||
4329 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004330 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004331 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004332 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004333 mScheduler->onScreenAcquired(mAppConnectionHandle);
4334 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004335 }
4336 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4337 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004339 mScheduler->disableHardwareVsync(true);
4340 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004341 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004342 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004343 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004344 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004345 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004346 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004347
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004348 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004349 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004350 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004351 // Update refresh rate stats.
4352 mRefreshRateStats->setPowerMode(mode);
4353 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004354 }
4355
Dominik Laskowski34157762018-10-31 13:07:19 -07004356 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004357}
4358
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004359void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004360 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004361 const auto display = getDisplayDevice(displayToken);
4362 if (!display) {
4363 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4364 displayToken.get());
4365 } else if (display->isVirtual()) {
4366 ALOGW("Attempt to set power mode %d for virtual display", mode);
4367 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004368 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004369 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004370 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004371}
4372
4373// ---------------------------------------------------------------------------
4374
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4376 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004378
Mathias Agopianbd115332013-04-18 16:41:04 -07004379 IPCThreadState* ipc = IPCThreadState::self();
4380 const int pid = ipc->getCallingPid();
4381 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004382
Mathias Agopianbd115332013-04-18 16:41:04 -07004383 if ((uid != AID_SHELL) &&
4384 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4386 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004387 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004388 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004389 // (this would indicate SF is stuck, but we want to be able to
4390 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004391 status_t err = mStateLock.timedLock(s2ns(1));
4392 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004393 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result,
4395 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4396 "(no locks held)\n",
4397 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004398 }
4399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004401
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402 static const std::unordered_map<std::string, Dumper> dumpers = {
4403 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4404 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4405 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004406 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004407 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004408 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4410 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004411 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4412 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4413 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4414 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4415 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4416 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004417 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4419 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004420
Dominik Laskowskic2867142019-01-21 11:33:38 -08004421 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004422
Dominik Laskowskic2867142019-01-21 11:33:38 -08004423 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4424 (it->second)(args, asProto, result);
4425 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004426 if (asProto) {
4427 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4428 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4429 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004430 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004431 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004432 }
4433
Mathias Agopian9795c422009-08-26 16:36:26 -07004434 if (locked) {
4435 mStateLock.unlock();
4436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004438 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004439 return NO_ERROR;
4440}
4441
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004442status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4443 if (asProto && mTracing.isEnabled()) {
4444 mTracing.writeToFileAsync();
4445 }
4446
4447 return doDump(fd, DumpArgs(), asProto);
4448}
4449
Dominik Laskowskic2867142019-01-21 11:33:38 -08004450void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451 mCurrentState.traverseInZOrder(
4452 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453}
4454
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004456 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458 if (args.size() > 1) {
4459 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004460 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004461 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004462 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463 }
Robert Carr2047fae2016-11-28 14:09:09 -08004464 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004465 } else {
4466 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 }
4468}
4469
Dominik Laskowskic2867142019-01-21 11:33:38 -08004470void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004471 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004472 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004473 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004474 }
Robert Carr2047fae2016-11-28 14:09:09 -08004475 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004476
Svetoslavd85084b2014-03-20 10:28:31 -07004477 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478}
4479
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4481 mTimeStats->parseArgs(asProto, args, result);
4482}
4483
Jamie Gennis6547ff42013-07-16 20:12:42 -07004484// This should only be called from the main thread. Otherwise it would need
4485// the lock and should use mCurrentState rather than mDrawingState.
4486void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004488 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490
4491 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004496
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 if (isLayerTripleBufferingDisabled())
4498 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4501 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4502 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4503 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4504 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4505 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004507}
4508
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004509void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004510 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004511 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004512 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004513 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004514
Ady Abraham97d04232019-03-05 19:48:12 -08004515 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004516 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4517 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004518 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004519}
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4522 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004523 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4524 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004525 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004526 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004528 }
David Sodman4a36e932017-11-07 14:29:47 -08004529 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004530 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004531 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4533 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004534}
4535
Dan Stozae77c7662016-05-13 11:37:28 -07004536void SurfaceFlinger::recordBufferingStats(const char* layerName,
4537 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004538 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4539 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004540 for (const auto& segment : history) {
4541 if (!segment.usedThirdBuffer) {
4542 stats.twoBufferTime += segment.totalTime;
4543 }
4544 if (segment.occupancyAverage < 1.0f) {
4545 stats.doubleBufferedTime += segment.totalTime;
4546 } else if (segment.occupancyAverage < 2.0f) {
4547 stats.tripleBufferedTime += segment.totalTime;
4548 }
4549 ++stats.numSegments;
4550 stats.totalTime += segment.totalTime;
4551 }
4552}
4553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4555 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004556
4557 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4558 const size_t count = currentLayers.size();
4559 for (size_t i=0 ; i<count ; i++) {
4560 currentLayers[i]->dumpFrameEvents(result);
4561 }
4562}
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004565 result.append("Buffering stats:\n");
4566 result.append(" [Layer name] <Active time> <Two buffer> "
4567 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004568 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004569 typedef std::tuple<std::string, float, float, float> BufferTuple;
4570 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004571 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004572 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004573 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004574 if (stats.numSegments == 0) {
4575 continue;
4576 }
4577 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4578 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4579 stats.totalTime;
4580 float doubleBufferRatio = static_cast<float>(
4581 stats.doubleBufferedTime) / stats.totalTime;
4582 float tripleBufferRatio = static_cast<float>(
4583 stats.tripleBufferedTime) / stats.totalTime;
4584 sorted.insert({activeTime, {name, twoBufferRatio,
4585 doubleBufferRatio, tripleBufferRatio}});
4586 }
4587 for (const auto& sortedPair : sorted) {
4588 float activeTime = sortedPair.first;
4589 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4591 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004592 }
4593 result.append("\n");
4594}
4595
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004597 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004598 const auto displayId = display->getId();
4599 if (!displayId) {
4600 continue;
4601 }
4602 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004603 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 continue;
4605 }
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result,
4608 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4609 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004610 uint8_t port;
4611 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004612 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004613 result.append("no identification data\n");
4614 continue;
4615 }
4616
4617 if (!isEdid(data)) {
4618 result.append("unknown identification data: ");
4619 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 }
4622 result.append("\n");
4623 continue;
4624 }
4625
4626 const auto edid = parseEdid(data);
4627 if (!edid) {
4628 result.append("invalid EDID: ");
4629 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004631 }
4632 result.append("\n");
4633 continue;
4634 }
4635
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004637 result.append(edid->displayName.data(), edid->displayName.length());
4638 result.append("\"\n");
4639 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640}
4641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4643 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4644 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4645 StringAppendF(&result, "DisplayColorSetting: %s\n",
4646 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004647
4648 // TODO: print out if wide-color mode is active or not
4649
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004650 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004651 const auto displayId = display->getId();
4652 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 continue;
4654 }
4655
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004657 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004658 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004660 }
4661
Lloyd Pique32cbe282018-10-19 13:09:22 -07004662 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, " Current color mode: %s (%d)\n",
4664 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004665 }
4666 result.append("\n");
4667}
4668
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004669LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4670 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004671 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004672 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4673 const State& state = useDrawing ? mDrawingState : mCurrentState;
4674 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004675 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004676 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004677 });
4678
4679 return layersProto;
4680}
4681
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004682LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4683 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004684 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004685
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004686 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004687 resolution->set_w(displayDevice->getWidth());
4688 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004690 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004691 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004692
Lloyd Pique32cbe282018-10-19 13:09:22 -07004693 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4694 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4695 layersProto.set_global_transform(displayState.orientation);
4696
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004697 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004698 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004699 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004700 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004702 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004703 }
4704 });
4705
4706 return layersProto;
4707}
4708
Dominik Laskowskic2867142019-01-21 11:33:38 -08004709void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4710 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 Colorizer colorizer(colorize);
4712
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713 // figure out if we're stuck somewhere
4714 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4717
4718 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004719 * Dump library configuration.
4720 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721
4722 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004723 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004724 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004725 appendSfConfigString(result);
4726 appendUiConfigString(result);
4727 appendGuiConfigString(result);
4728 result.append("\n");
4729
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004730 result.append("\nDisplay identification data:\n");
4731 dumpDisplayIdentificationData(result);
4732
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004733 result.append("\nWide-Color information:\n");
4734 dumpWideColorInfo(result);
4735
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004737 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004739 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004740 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004741
Andy McFadden41d67d72014-04-25 16:58:34 -07004742 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004743 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004744 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004745 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004746 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004747
Dan Stozab90cf072015-03-05 11:05:59 -08004748 dumpStaticScreenStats(result);
4749 result.append("\n");
4750
Alec Mouri40189b02019-03-05 15:07:54 -08004751 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4752 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4753 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004754
Dan Stozae77c7662016-05-13 11:37:28 -07004755 dumpBufferingStats(result);
4756
Andy McFadden4803b742012-09-24 19:07:20 -07004757 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758 * Dump the visible layer list
4759 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004760 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4762 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4763 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004764 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004765
Chia-I Wu2f884132018-09-13 15:17:58 -07004766 {
4767 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4768 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004770 result.append("\n");
4771 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772
Lloyd Pique207def92019-02-28 16:09:52 -08004773 {
4774 StringAppendF(&result, "Composition layers\n");
4775 mDrawingState.traverseInZOrder([&](Layer* layer) {
4776 auto compositionLayer = layer->getCompositionLayer();
4777 if (compositionLayer) compositionLayer->dump(result);
4778 });
4779 }
4780
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004782 * Dump Display state
4783 */
4784
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004788 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004789 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004790 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004791 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004792
4793 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794 * Dump SurfaceFlinger global state
4795 */
4796
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004797 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004798 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004799 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004800
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004801 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802
Dominik Laskowski075d3172018-05-24 15:50:06 -07004803 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004804 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4805 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4807 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004808 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result,
4810 " transaction-flags : %08x\n"
4811 " gpu_to_cpu_unsupported : %d\n",
4812 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004813
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004814 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815 displayId && getHwComposer().isConnected(*displayId)) {
4816 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result,
4818 " refresh-rate : %f fps\n"
4819 " x-dpi : %f\n"
4820 " y-dpi : %f\n",
4821 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4822 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004823 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004824
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004826
Dan Stozae22aec72016-08-01 13:20:59 -07004827 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004828 * Tracing state
4829 */
4830 mTracing.dump(result);
4831 result.append("\n");
4832
4833 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004834 * HWC layer minidump
4835 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004836 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837 const auto displayId = display->getId();
4838 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004839 continue;
4840 }
4841
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004843 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004844 const sp<DisplayDevice> displayDevice = display;
4845 mCurrentState.traverseInZOrder(
4846 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004847 result.append("\n");
4848 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
4850 /*
4851 * Dump HWComposer state
4852 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004853 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004854 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004855 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004856 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004858 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004859
4860 /*
4861 * Dump gralloc state
4862 */
4863 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4864 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004865
4866 /*
4867 * Dump VrFlinger state if in use.
4868 */
4869 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4870 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004872 result.append("\n");
4873 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004874
4875 /**
4876 * Scheduler dump state.
4877 */
Ana Krulecc2870422019-01-29 19:00:58 -08004878 result.append("\nScheduler state:\n");
4879 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004880 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004881 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004882}
4883
Dominik Laskowski075d3172018-05-24 15:50:06 -07004884const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004885 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004886 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004887 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004888 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004889 }
4890 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004891
Dominik Laskowski34157762018-10-31 13:07:19 -07004892 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004893 static const Vector<sp<Layer>> empty;
4894 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004895}
4896
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897void SurfaceFlinger::updateColorMatrixLocked() {
4898 mat4 colorMatrix;
4899 if (mGlobalSaturationFactor != 1.0f) {
4900 // Rec.709 luma coefficients
4901 float3 luminance{0.213f, 0.715f, 0.072f};
4902 luminance *= 1.0f - mGlobalSaturationFactor;
4903 mat4 saturationMatrix = mat4(
4904 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4905 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4906 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4907 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4908 );
4909 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4910 } else {
4911 colorMatrix = mClientColorMatrix * mDaltonizer();
4912 }
4913
4914 if (mCurrentState.colorMatrix != colorMatrix) {
4915 mCurrentState.colorMatrix = colorMatrix;
4916 mCurrentState.colorMatrixChanged = true;
4917 setTransactionFlags(eTransactionNeeded);
4918 }
4919}
4920
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004921status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922#pragma clang diagnostic push
4923#pragma clang diagnostic error "-Wswitch-enum"
4924 switch (static_cast<ISurfaceComposerTag>(code)) {
4925 // These methods should at minimum make sure that the client requested
4926 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004927 case BOOT_FINISHED:
4928 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case CREATE_DISPLAY:
4930 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004931 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004932 case GET_ANIMATION_FRAME_STATS:
4933 case GET_HDR_CAPABILITIES:
4934 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004935 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004936 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004938 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004939 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004940 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004941 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4942 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004943 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4944 IPCThreadState* ipc = IPCThreadState::self();
4945 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4946 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004947 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 }
Robert Carr1db73f62016-12-21 12:58:51 -08004949 return OK;
4950 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004952 IPCThreadState* ipc = IPCThreadState::self();
4953 const int pid = ipc->getCallingPid();
4954 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4956 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004957 return PERMISSION_DENIED;
4958 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004960 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004961 // Used by apps to hook Choreographer to SurfaceFlinger.
4962 case CREATE_DISPLAY_EVENT_CONNECTION:
4963 // The following calls are currently used by clients that do not
4964 // request necessary permissions. However, they do not expose any secret
4965 // information, so it is OK to pass them.
4966 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004967 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004968 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004969 case GET_PHYSICAL_DISPLAY_IDS:
4970 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004972 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004973 case GET_DISPLAY_CONFIGS:
4974 case GET_DISPLAY_STATS:
4975 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4976 // Calling setTransactionState is safe, because you need to have been
4977 // granted a reference to Client* and Handle* to do anything with it.
4978 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004979 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004980 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004981 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004982 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004983 case IS_WIDE_COLOR_DISPLAY:
4984 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4985 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004986 return OK;
4987 }
4988 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004989 case CAPTURE_SCREEN:
4990 case ADD_REGION_SAMPLING_LISTENER:
4991 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004993 IPCThreadState* ipc = IPCThreadState::self();
4994 const int pid = ipc->getCallingPid();
4995 const int uid = ipc->getCallingUid();
4996 if ((uid != AID_GRAPHICS) &&
4997 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4998 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4999 return PERMISSION_DENIED;
5000 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 return OK;
5002 }
5003 // The following codes are deprecated and should never be allowed to access SF.
5004 case CONNECT_DISPLAY_UNUSED:
5005 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5006 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5007 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010
5011 // These codes are used for the IBinder protocol to either interrogate the recipient
5012 // side of the transaction for its canonical interface descriptor or to dump its state.
5013 // We let them pass by default.
5014 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5015 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5016 code == IBinder::SYSPROPS_TRANSACTION) {
5017 return OK;
5018 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005019 // Numbers from 1000 to 1033 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 // in onTransact verifies that the user is root, and has access to use SF.
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005021 if (code >= 1000 && code <= 1033) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5023 return OK;
5024 }
5025 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5026 return PERMISSION_DENIED;
5027#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005028}
5029
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5031 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005032 status_t credentialCheck = CheckTransactCodeCredentials(code);
5033 if (credentialCheck != OK) {
5034 return credentialCheck;
5035 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5038 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005039 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005040 IPCThreadState* ipc = IPCThreadState::self();
5041 const int uid = ipc->getCallingUid();
5042 if (CC_UNLIKELY(uid != AID_SYSTEM
5043 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005044 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005045 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005046 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 return PERMISSION_DENIED;
5048 }
5049 int n;
5050 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005051 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005052 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 return NO_ERROR;
5054 case 1002: // SHOW_UPDATES
5055 n = data.readInt32();
5056 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005057 invalidateHwcGeometry();
5058 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005061 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005062 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005064 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005065 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005066 setTransactionFlags(
5067 eTransactionNeeded|
5068 eDisplayTransactionNeeded|
5069 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005070 return NO_ERROR;
5071 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005072 case 1006:{ // send empty update
5073 signalRefresh();
5074 return NO_ERROR;
5075 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005076 case 1008: // toggle use of hw composer
5077 n = data.readInt32();
5078 mDebugDisableHWC = n ? 1 : 0;
5079 invalidateHwcGeometry();
5080 repaintEverything();
5081 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005082 case 1009: // toggle use of transform hint
5083 n = data.readInt32();
5084 mDebugDisableTransformHint = n ? 1 : 0;
5085 invalidateHwcGeometry();
5086 repaintEverything();
5087 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005088 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005089 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 reply->writeInt32(0);
5091 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005092 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005093 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 return NO_ERROR;
5095 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005096 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005097 if (!display) {
5098 return NAME_NOT_FOUND;
5099 }
5100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005101 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005102 return NO_ERROR;
5103 }
5104 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005105 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005106 // daltonize
5107 n = data.readInt32();
5108 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005109 case 1:
5110 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5111 break;
5112 case 2:
5113 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5114 break;
5115 case 3:
5116 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5117 break;
5118 default:
5119 mDaltonizer.setType(ColorBlindnessType::None);
5120 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005121 }
5122 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005123 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005124 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005125 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005126 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127
5128 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005129 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005131 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005132 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005133 // apply a color matrix
5134 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005135 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005136 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005137 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005138 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005139 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005140 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005141 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005142 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005143 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005144 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005145
5146 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5147 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005148 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005149 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5150 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5151 }
5152
Chia-I Wu28f320b2018-05-03 11:02:56 -07005153 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005154 return NO_ERROR;
5155 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005156 // This is an experimental interface
5157 // Needs to be shifted to proper binder interface when we productize
5158 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005159 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005160 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005161 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005162 return NO_ERROR;
5163 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005164 case 1017: {
5165 n = data.readInt32();
5166 mForceFullDamage = static_cast<bool>(n);
5167 return NO_ERROR;
5168 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005169 case 1018: { // Modify Choreographer's phase offset
5170 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005171 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005172 return NO_ERROR;
5173 }
5174 case 1019: { // Modify SurfaceFlinger's phase offset
5175 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005176 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005177 return NO_ERROR;
5178 }
Irvel468051e2016-06-13 16:44:44 -07005179 case 1020: { // Layer updates interceptor
5180 n = data.readInt32();
5181 if (n) {
5182 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005183 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005184 }
5185 else{
5186 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005187 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005188 }
5189 return NO_ERROR;
5190 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005191 case 1021: { // Disable HWC virtual displays
5192 n = data.readInt32();
5193 mUseHwcVirtualDisplays = !n;
5194 return NO_ERROR;
5195 }
Romain Guy0147a172017-06-01 13:53:56 -07005196 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005197 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005198 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005199
Chia-I Wu28f320b2018-05-03 11:02:56 -07005200 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005201 return NO_ERROR;
5202 }
Romain Guy54f154a2017-10-24 21:40:32 +01005203 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005204 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005205 invalidateHwcGeometry();
5206 repaintEverything();
5207 return NO_ERROR;
5208 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005209 // Deprecate, use 1030 to check whether the device is color managed.
5210 case 1024: {
5211 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005212 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005213 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005214 n = data.readInt32();
5215 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005216 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005217 Mutex::Autolock lock(mStateLock);
5218 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005219 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005220 reply->writeInt32(NO_ERROR);
5221 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005222 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005223 bool writeFile = false;
5224 {
5225 Mutex::Autolock lock(mStateLock);
5226 mTracingEnabledChanged = true;
5227 writeFile = mTracing.disable();
5228 }
5229
5230 if (writeFile) {
5231 reply->writeInt32(mTracing.writeToFile());
5232 } else {
5233 reply->writeInt32(NO_ERROR);
5234 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005235 }
5236 return NO_ERROR;
5237 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005238 case 1026: { // Get layer tracing status
5239 reply->writeBool(mTracing.isEnabled());
5240 return NO_ERROR;
5241 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005242 // Is a DisplayColorSetting supported?
5243 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 const auto display = getDefaultDisplayDevice();
5245 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005246 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005247 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005248
5249 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5250 switch (setting) {
5251 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005252 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005253 break;
5254 case DisplayColorSetting::UNMANAGED:
5255 reply->writeBool(true);
5256 break;
5257 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005258 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005259 break;
5260 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261 reply->writeBool(
5262 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005263 break;
5264 }
5265 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005266 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005267 // Is VrFlinger active?
5268 case 1028: {
5269 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005270 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005271 return NO_ERROR;
5272 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005273 // Set buffer size for SF tracing (value in KB)
5274 case 1029: {
5275 n = data.readInt32();
5276 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5277 ALOGW("Invalid buffer size: %d KB", n);
5278 reply->writeInt32(BAD_VALUE);
5279 return BAD_VALUE;
5280 }
5281
5282 ALOGD("Updating trace buffer to %d KB", n);
5283 mTracing.setBufferSize(n * 1024);
5284 reply->writeInt32(NO_ERROR);
5285 return NO_ERROR;
5286 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005287 // Is device color managed?
5288 case 1030: {
5289 reply->writeBool(useColorManagement);
5290 return NO_ERROR;
5291 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005292 // Override default composition data space
5293 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5294 // && adb shell stop zygote && adb shell start zygote
5295 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5296 // adb shell stop zygote && adb shell start zygote
5297 case 1031: {
5298 Mutex::Autolock _l(mStateLock);
5299 n = data.readInt32();
5300 if (n) {
5301 n = data.readInt32();
5302 if (n) {
5303 Dataspace dataspace = static_cast<Dataspace>(n);
5304 if (!validateCompositionDataspace(dataspace)) {
5305 return BAD_VALUE;
5306 }
5307 mDefaultCompositionDataspace = dataspace;
5308 }
5309 n = data.readInt32();
5310 if (n) {
5311 Dataspace dataspace = static_cast<Dataspace>(n);
5312 if (!validateCompositionDataspace(dataspace)) {
5313 return BAD_VALUE;
5314 }
5315 mWideColorGamutCompositionDataspace = dataspace;
5316 }
5317 } else {
5318 // restore composition data space.
5319 mDefaultCompositionDataspace = defaultCompositionDataspace;
5320 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5321 }
5322 return NO_ERROR;
5323 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005324 case 1032: {
5325 n = data.readInt32();
5326 mDebugEnableProtectedContent = n;
5327 return NO_ERROR;
5328 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005329 // Set trace flags
5330 case 1033: {
5331 n = data.readUint32();
5332 ALOGD("Updating trace flags to 0x%x", n);
5333 mTracing.setTraceFlags(n);
5334 reply->writeInt32(NO_ERROR);
5335 return NO_ERROR;
5336 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005337 }
5338 }
5339 return err;
5340}
5341
Steven Thomas6d8110b2017-08-31 18:24:21 -07005342void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005343 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005344 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005345}
5346
Ana Krulec7d1d6832018-12-27 11:10:09 -08005347void SurfaceFlinger::repaintEverythingForHWC() {
5348 mRepaintEverything = true;
5349 mEventQueue->invalidateForHWC();
5350}
5351
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005352// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5353class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005354public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5356 ~WindowDisconnector() {
5357 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005358 }
5359
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360private:
5361 ANativeWindow* mWindow;
5362 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005363};
5364
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005365status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005366 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5367 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005368 uint32_t reqWidth, uint32_t reqHeight,
5369 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005370 ISurfaceComposer::Rotation rotation,
5371 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005374 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005375
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005376 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5377
Chia-I Wu20261cb2018-08-23 12:55:44 -07005378 sp<DisplayDevice> display;
5379 {
5380 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005381
Chia-I Wu20261cb2018-08-23 12:55:44 -07005382 display = getDisplayDeviceLocked(displayToken);
5383 if (!display) return BAD_VALUE;
5384
Chia-I Wucb023152018-08-28 12:57:23 -07005385 // set the requested width/height to the logical display viewport size
5386 // by default
5387 if (reqWidth == 0 || reqHeight == 0) {
5388 reqWidth = uint32_t(display->getViewport().width());
5389 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005390 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005391 }
5392
Peiyong Lin0e003c92018-09-17 11:09:51 -07005393 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005394 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005395
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005396 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5397 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005398 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5399 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005400}
5401
5402status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005403 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5404 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005405 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005406 ATRACE_CALL();
5407
5408 class LayerRenderArea : public RenderArea {
5409 public:
Robert Carr578038f2018-03-09 12:25:24 -08005410 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005411 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5412 bool childrenOnly)
5413 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005414 mLayer(layer),
5415 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005416 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005417 mFlinger(flinger),
5418 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005419 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005420 Rect getBounds() const override {
5421 const Layer::State& layerState(mLayer->getDrawingState());
5422 return mLayer->getBufferSize(layerState);
5423 }
Marissa Wall61c58622018-07-18 10:12:20 -07005424 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005425 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005426 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005427 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005429 }
chaviwa76b2712017-09-20 12:02:26 -07005430 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005431 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005432 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005433 Rect getSourceCrop() const override {
5434 if (mCrop.isEmpty()) {
5435 return getBounds();
5436 } else {
5437 return mCrop;
5438 }
5439 }
Robert Carr578038f2018-03-09 12:25:24 -08005440 class ReparentForDrawing {
5441 public:
5442 const sp<Layer>& oldParent;
5443 const sp<Layer>& newParent;
5444
Vishnu Nair4351ad52019-02-11 14:13:02 -08005445 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5446 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005447 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005448 // Compute and cache the bounds for the new parent layer.
5449 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005450 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005451 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005452 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005453 };
5454
5455 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005456 const Rect sourceCrop = getSourceCrop();
5457 // no need to check rotation because there is none
5458 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5459 sourceCrop.height() != getReqHeight();
5460
Robert Carr578038f2018-03-09 12:25:24 -08005461 if (!mChildrenOnly) {
5462 mTransform = mLayer->getTransform().inverse();
5463 drawLayers();
5464 } else {
5465 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005466 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005467 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005468 bounds.getWidth(), bounds.getHeight(), 0,
5469 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005470
Vishnu Nair4351ad52019-02-11 14:13:02 -08005471 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005472 drawLayers();
5473 }
5474 }
chaviwa76b2712017-09-20 12:02:26 -07005475
chaviwa76b2712017-09-20 12:02:26 -07005476 private:
chaviw7206d492017-11-10 16:16:12 -08005477 const sp<Layer> mLayer;
5478 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005479
5480 // In the "childrenOnly" case we reparent the children to a screenshot
5481 // layer which has no properties set and which does not draw.
5482 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005483 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005484 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005485
5486 SurfaceFlinger* mFlinger;
5487 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005488 };
5489
5490 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5491 auto parent = layerHandle->owner.promote();
5492
Robert Carr2e102c92018-10-23 12:11:15 -07005493 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005494 ALOGE("captureLayers called with a removed parent");
5495 return NAME_NOT_FOUND;
5496 }
5497
Robert Carr578038f2018-03-09 12:25:24 -08005498 const int uid = IPCThreadState::self()->getCallingUid();
5499 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005500 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005501 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5502 return PERMISSION_DENIED;
5503 }
5504
chaviw7206d492017-11-10 16:16:12 -08005505 Rect crop(sourceCrop);
5506 if (sourceCrop.width() <= 0) {
5507 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005508 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005509 }
5510
5511 if (sourceCrop.height() <= 0) {
5512 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005513 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005514 }
5515
5516 int32_t reqWidth = crop.width() * frameScale;
5517 int32_t reqHeight = crop.height() * frameScale;
5518
Chia-I Wu20261cb2018-08-23 12:55:44 -07005519 // really small crop or frameScale
5520 if (reqWidth <= 0) {
5521 reqWidth = 1;
5522 }
5523 if (reqHeight <= 0) {
5524 reqHeight = 1;
5525 }
5526
Peiyong Lin0e003c92018-09-17 11:09:51 -07005527 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005528
Robert Carr578038f2018-03-09 12:25:24 -08005529 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005530 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5531 if (!layer->isVisible()) {
5532 return;
Robert Carr578038f2018-03-09 12:25:24 -08005533 } else if (childrenOnly && layer == parent.get()) {
5534 return;
chaviwa76b2712017-09-20 12:02:26 -07005535 }
5536 visitor(layer);
5537 });
5538 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005539 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005540}
5541
5542status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5543 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005544 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005545 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005546 bool useIdentityTransform) {
5547 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005548
Peiyong Lin0e003c92018-09-17 11:09:51 -07005549 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005550 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5551 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005552 *outBuffer =
5553 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5554 static_cast<android_pixel_format>(reqPixelFormat), 1,
5555 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005556
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005557 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005558}
5559
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005560status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5561 TraverseLayersFunction traverseLayers,
5562 const sp<GraphicBuffer>& buffer,
5563 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005564 // This mutex protects syncFd and captureResult for communication of the return values from the
5565 // main thread back to this Binder thread
5566 std::mutex captureMutex;
5567 std::condition_variable captureCondition;
5568 std::unique_lock<std::mutex> captureLock(captureMutex);
5569 int syncFd = -1;
5570 std::optional<status_t> captureResult;
5571
Robert Carr03480e22018-01-04 16:02:06 -08005572 const int uid = IPCThreadState::self()->getCallingUid();
5573 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5574
Dominik Laskowski8c001672018-05-30 16:52:06 -07005575 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005576 // If there is a refresh pending, bug out early and tell the binder thread to try again
5577 // after the refresh.
5578 if (mRefreshPending) {
5579 ATRACE_NAME("Skipping screenshot for now");
5580 std::unique_lock<std::mutex> captureLock(captureMutex);
5581 captureResult = std::make_optional<status_t>(EAGAIN);
5582 captureCondition.notify_one();
5583 return;
5584 }
5585
5586 status_t result = NO_ERROR;
5587 int fd = -1;
5588 {
5589 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005590 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005591 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005592 useIdentityTransform, forSystem, &fd);
5593 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 }
5595
5596 {
5597 std::unique_lock<std::mutex> captureLock(captureMutex);
5598 syncFd = fd;
5599 captureResult = std::make_optional<status_t>(result);
5600 captureCondition.notify_one();
5601 }
5602 });
5603
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005604 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005606 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005607 while (*captureResult == EAGAIN) {
5608 captureResult.reset();
5609 result = postMessageAsync(message);
5610 if (result != NO_ERROR) {
5611 return result;
5612 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005613 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614 }
5615 result = *captureResult;
5616 }
5617
5618 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 sync_wait(syncFd, -1);
5620 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005621 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005622
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005623 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005624}
5625
chaviwa76b2712017-09-20 12:02:26 -07005626void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005627 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005628 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5629 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005630 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005631
chaviwa76b2712017-09-20 12:02:26 -07005632 const auto reqWidth = renderArea.getReqWidth();
5633 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005634 const auto sourceCrop = renderArea.getSourceCrop();
5635 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005636
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 renderengine::DisplaySettings clientCompositionDisplay;
5638 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005639
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005640 // assume that bounds are never offset, and that they are the same as the
5641 // buffer bounds.
5642 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5643 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005644 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005645 mat4 rotMatrix;
5646 // Displacement for repositioning the clipping rectangle after rotating it
5647 // with the rotation hint.
5648 int displacementX = 0;
5649 int displacementY = 0;
5650 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5651 switch (rotation) {
5652 case ui::Transform::ROT_90:
5653 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5654 displacementX = reqWidth;
5655 break;
5656 case ui::Transform::ROT_180:
5657 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5658 displacementX = reqWidth;
5659 displacementY = reqHeight;
5660 break;
5661 case ui::Transform::ROT_270:
5662 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5663 displacementY = reqHeight;
5664 break;
5665 default:
5666 break;
5667 }
5668 // We need to transform the clipping window into the right spot.
5669 // First, rotate the clipping rectangle by the rotation hint to get the
5670 // right orientation
5671 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5672 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5673 const vec4 rotClipTL = rotMatrix * clipTL;
5674 const vec4 rotClipBR = rotMatrix * clipBR;
5675 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5676 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5677 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5678 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5679
5680 // Now reposition the clipping rectangle with the displacement vector
5681 // computed above.
5682 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5683
5684 clientCompositionDisplay.clip =
5685 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5686 newClipRight + displacementX, newClipBottom + displacementY);
5687
5688 // We need to perform the same transformation in layer space, so propagate
5689 // it to the global transform.
5690 mat4 clipTransform = displacementMat * rotMatrix;
5691 clientCompositionDisplay.globalTransform *= clipTransform;
5692 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5693 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005694
chaviw50da5042018-04-09 13:49:37 -07005695 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005696
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005697 renderengine::LayerSettings fillLayer;
5698 fillLayer.source.buffer.buffer = nullptr;
5699 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5700 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5701 fillLayer.alpha = half(alpha);
5702 clientCompositionLayers.push_back(fillLayer);
5703
5704 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005705 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005706 renderengine::LayerSettings layerSettings;
5707 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005708 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005709 if (prepared) {
5710 clientCompositionLayers.push_back(layerSettings);
5711 }
chaviwa76b2712017-09-20 12:02:26 -07005712 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713
5714 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005715 // Use an empty fence for the buffer fence, since we just created the buffer so
5716 // there is no need for synchronization with the GPU.
5717 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005718 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005719 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005720 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005721 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722
5723 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005724}
5725
chaviwa76b2712017-09-20 12:02:26 -07005726status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5727 TraverseLayersFunction traverseLayers,
5728 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005729 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005730 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005731 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005732 ATRACE_CALL();
5733
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005734 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005735
5736 traverseLayers([&](Layer* layer) {
5737 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5738 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005739
Robert Carr03480e22018-01-04 16:02:06 -08005740 // We allow the system server to take screenshots of secure layers for
5741 // use in situations like the Screen-rotation animation and place
5742 // the impetus on WindowManager to not persist them.
5743 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005744 ALOGW("FB is protected: PERMISSION_DENIED");
5745 return PERMISSION_DENIED;
5746 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005748 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005749}
5750
chaviw95ef3c42019-02-14 10:55:09 -08005751void SurfaceFlinger::setInputWindowsFinished() {
5752 Mutex::Autolock _l(mStateLock);
5753
5754 mPendingSyncInputWindows = false;
5755 mTransactionCV.broadcast();
5756}
chaviw5f21a5e2019-02-14 10:00:34 -08005757
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005758// ---------------------------------------------------------------------------
5759
Dan Stoza412903f2017-04-27 13:42:17 -07005760void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5761 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005762}
5763
Dan Stoza412903f2017-04-27 13:42:17 -07005764void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5765 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005766}
5767
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005768void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005769 const LayerVector::Visitor& visitor) {
5770 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005771 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005772 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005773 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005774 continue;
5775 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005776 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005777 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005778 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005779 return;
5780 }
chaviwa76b2712017-09-20 12:02:26 -07005781 if (!layer->isVisible()) {
5782 return;
5783 }
5784 visitor(layer);
5785 });
5786 }
5787}
5788
Ady Abraham838de062019-02-04 10:24:03 -08005789void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5790 const android::sp<android::IBinder>& displayToken,
5791 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5792 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5793 if (!displayId) {
5794 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5795 return;
5796 }
5797
5798 ALOGV("Updating allowed configs");
5799 {
5800 std::lock_guard lock(mAllowedConfigsLock);
5801 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5802 }
5803
5804 // make sure that the current config is still allowed
5805 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5806 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005807 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
Alec Mouri0a1cc962019-03-14 12:33:02 -07005808 if (config && isConfigAllowed(*displayId, config->configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005809 // TODO: we switch to the first allowed config. In the future
5810 // we may want to enhance this logic to pick a similar config
5811 // to the current one
Alec Mouri0a1cc962019-03-14 12:33:02 -07005812 ALOGV("Old config is not allowed - switching to config %d", config->configId);
5813 setDesiredActiveConfig(displayToken, config->configId,
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005814 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005815 break;
5816 }
5817 }
5818 }
Ady Abraham97d04232019-03-05 19:48:12 -08005819
5820 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5821 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5822 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
Alec Mouri0a1cc962019-03-14 12:33:02 -07005823 const auto& performanceRefreshRate =
Ady Abraham97d04232019-03-05 19:48:12 -08005824 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
Alec Mouri0a1cc962019-03-14 12:33:02 -07005825 if (performanceRefreshRate &&
5826 isConfigAllowed(*displayId, performanceRefreshRate->configId)) {
Ady Abraham97d04232019-03-05 19:48:12 -08005827 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5828 }
5829 }
Ady Abraham838de062019-02-04 10:24:03 -08005830}
5831
5832status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5833 const std::vector<int32_t>& allowedConfigs) {
5834 ATRACE_CALL();
5835
5836 if (!displayToken) {
5837 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5838 return BAD_VALUE;
5839 }
5840
5841 if (!allowedConfigs.size()) {
5842 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5843 return BAD_VALUE;
5844 }
5845
5846 {
5847 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5848 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5849 if (!displayId) {
5850 ALOGE("setAllowedDisplayConfigs: display not found");
5851 return NAME_NOT_FOUND;
5852 }
5853 }
5854
5855 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5856 for (int config : allowedConfigs) {
5857 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5858 allowedDisplayConfigsBuilder.addConfig(config);
5859 }
5860 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5861 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5862 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5863 }));
5864 return NO_ERROR;
5865}
5866
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005867status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5868 std::vector<int32_t>* outAllowedConfigs) {
5869 ATRACE_CALL();
5870
5871 if (!displayToken) {
5872 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5873 return BAD_VALUE;
5874 }
5875
5876 if (!outAllowedConfigs) {
5877 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5878 return BAD_VALUE;
5879 }
5880
5881 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5882 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5883 if (!displayId) {
5884 ALOGE("getAllowedDisplayConfigs: display not found");
5885 return NAME_NOT_FOUND;
5886 }
5887
5888 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5889 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5890 if (allowedConfigIterator != mAllowedConfigs.end()) {
5891 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5892 }
5893
5894 return NO_ERROR;
5895}
5896
chaviw291d88a2019-02-14 10:33:58 -08005897// ----------------------------------------------------------------------------
5898
5899void SetInputWindowsListener::onSetInputWindowsFinished() {
5900 mFlinger->setInputWindowsFinished();
5901}
5902
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005903}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005904
Lloyd Pique074e8122018-07-26 12:57:23 -07005905
Mathias Agopian3f844832013-08-07 21:24:32 -07005906#if defined(__gl_h_)
5907#error "don't include gl/gl.h in this file"
5908#endif
5909
5910#if defined(__gl2_h_)
5911#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005912#endif