blob: 6ee64e0cdea0534b29dd93c14d81690ba8301908 [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
Ady Abraham97d04232019-03-05 19:48:12 -0800595 const auto performanceRefreshRate =
596 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
597
598 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800599 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800600 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800601 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800602 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800603 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800604}
605
Dan Stoza436ccf32018-06-21 12:10:12 -0700606uint32_t SurfaceFlinger::getNewTexture() {
607 {
608 std::lock_guard lock(mTexturePoolMutex);
609 if (!mTexturePool.empty()) {
610 uint32_t name = mTexturePool.back();
611 mTexturePool.pop_back();
612 ATRACE_INT("TexturePoolSize", mTexturePool.size());
613 return name;
614 }
615
616 // The pool was too small, so increase it for the future
617 ++mTexturePoolSize;
618 }
619
620 // The pool was empty, so we need to get a new texture name directly using a
621 // blocking call to the main thread
622 uint32_t name = 0;
623 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
624 return name;
625}
626
Mathias Agopian3f844832013-08-07 21:24:32 -0700627void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700629}
630
Wei Wangf9b05ee2017-07-19 20:59:39 -0700631// Do not call property_set on main thread which will be blocked by init
632// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700634 ALOGI( "SurfaceFlinger's main thread ready to run. "
635 "Initializing graphics H/W...");
636
Ana Krulec757f63a2019-01-25 10:46:18 -0800637 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900638
Steven Thomasb02664d2017-07-26 18:48:28 -0700639 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800641 mScheduler =
642 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
643 auto resyncCallback =
644 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800645
Ana Krulecc2870422019-01-29 19:00:58 -0800646 mAppConnectionHandle =
647 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
648 resyncCallback,
649 impl::EventThread::InterceptVSyncsCallback());
650 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
651 resyncCallback, [this](nsecs_t timestamp) {
652 mInterceptor->saveVSyncEvent(timestamp);
653 });
654
655 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
656 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
657 mSfConnectionHandle.get());
658
Kevin DuBois413287f2019-02-25 08:46:47 -0800659 mRegionSamplingThread =
660 new RegionSamplingThread(*this, *mScheduler,
661 RegionSamplingThread::EnvironmentTimingTunables());
662
Steven Thomasb02664d2017-07-26 18:48:28 -0700663 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700664 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700665 renderEngineFeature |= (useColorManagement ?
666 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700667 renderEngineFeature |= (useContextPriority ?
668 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700669
670 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800671 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800674 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Mathias Agopian92a979a2012-08-02 18:32:23 -0700711 // initialize our drawing state
712 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700713
Andy McFadden13a082e2012-08-24 10:16:42 -0700714 // set initial conditions (e.g. unblank default device)
715 initializeDisplays();
716
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700717 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700718
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700720
721 const bool presentFenceReliable =
722 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
723 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700724
725 if (mStartPropertySetThread->Start() != NO_ERROR) {
726 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728
Ady Abraham97d04232019-03-05 19:48:12 -0800729 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800730 mScheduler->setChangeRefreshRateCallback(
731 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
732 Mutex::Autolock lock(mStateLock);
733 setRefreshRateTo(type, event);
734 });
Kevin DuBois36233132019-02-19 14:08:55 -0800735 }
Ady Abraham1902d072019-03-01 17:18:59 -0800736 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
737 getHwComposer().getConfigs(*display->getId()));
738 mRefreshRateStats =
739 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
740 mTimeStats);
Alec Mouri62c8bd12019-03-22 15:55:23 -0700741 mRefreshRateStats->setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700744}
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 Mutex::Autolock _l(mStateLock);
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749 char value[PROPERTY_VALUE_MAX];
750
751 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100755
756 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700757 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800758
759 property_get("persist.sys.sf.color_mode", value, "0");
760 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700761}
762
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Start boot animation service by setting a property mailbox
765 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700768 if (mStartPropertySetThread->join() != NO_ERROR) {
769 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800770 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700774 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
Mathias Agopian875d8e12013-06-07 15:35:48 -0700777size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700778 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700779}
780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800781// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800782
Jamie Gennis582270d2011-08-17 18:19:00 -0700783bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800785 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800786 return authenticateSurfaceTextureLocked(bufferProducer);
787}
788
789bool SurfaceFlinger::authenticateSurfaceTextureLocked(
790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800791 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800792 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800793}
794
Brian Anderson6b376712017-04-04 10:51:39 -0700795status_t SurfaceFlinger::getSupportedFrameTimestamps(
796 std::vector<FrameEvent>* outSupported) const {
797 *outSupported = {
798 FrameEvent::REQUESTED_PRESENT,
799 FrameEvent::ACQUIRE,
800 FrameEvent::LATCH,
801 FrameEvent::FIRST_REFRESH_START,
802 FrameEvent::LAST_REFRESH_START,
803 FrameEvent::GPU_COMPOSITION_DONE,
804 FrameEvent::DEQUEUE_READY,
805 FrameEvent::RELEASE,
806 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700807 ConditionalLock _l(mStateLock,
808 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700809 if (!getHwComposer().hasCapability(
810 HWC2::Capability::PresentFenceIsNotReliable)) {
811 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
812 }
813 return NO_ERROR;
814}
815
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800816status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
817 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700818 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 return BAD_VALUE;
820 }
821
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800822 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700823 if (!displayId) {
824 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700825 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 // TODO: Not sure if display density should handled by SF any longer
828 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700831 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700833 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835 return density;
836 }
837 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 return getDensityFromProperty("ro.sf.lcd_density"); }
842 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Dominik Laskowski075d3172018-05-24 15:50:06 -0700846 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 DisplayInfo info = DisplayInfo();
848
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849 float xdpi = hwConfig->getDpiX();
850 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700851
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700852 info.w = hwConfig->getWidth();
853 info.h = hwConfig->getHeight();
854 // Default display viewport to display width and height
855 info.viewportW = info.w;
856 info.viewportH = info.h;
857
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800858 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 // The density of the device is provided by a build property
860 float density = Density::getBuildDensity() / 160.0f;
861 if (density == 0) {
862 // the build doesn't provide a density -- this is wrong!
863 // use xdpi instead
864 ALOGE("ro.sf.lcd_density must be defined as a build property");
865 density = xdpi / 160.0f;
866 }
867 if (Density::getEmuDensity()) {
868 // if "qemu.sf.lcd_density" is specified, it overrides everything
869 xdpi = ydpi = density = Density::getEmuDensity();
870 density /= 160.0f;
871 }
872 info.density = density;
873
874 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875 const auto display = getDefaultDisplayDeviceLocked();
876 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700877
878 // This is for screenrecord
879 const Rect viewport = display->getViewport();
880 if (viewport.isValid()) {
881 info.viewportW = uint32_t(viewport.getWidth());
882 info.viewportH = uint32_t(viewport.getHeight());
883 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 } else {
885 // TODO: where should this value come from?
886 static const int TV_DENSITY = 213;
887 info.density = TV_DENSITY / 160.0f;
888 info.orientation = 0;
889 }
890
Dan Stoza7f7da322014-05-02 15:26:25 -0700891 info.xdpi = xdpi;
892 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800894 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895
Andy McFadden91b2ca82014-06-13 14:04:23 -0700896 // This is how far in advance a buffer must be queued for
897 // presentation at a given time. If you want a buffer to appear
898 // on the screen at time N, you must submit the buffer before
899 // (N - presentationDeadline).
900 //
901 // Normally it's one full refresh period (to give SF a chance to
902 // latch the buffer), but this can be reduced by configuring a
903 // DispSync offset. Any additional delays introduced by the hardware
904 // composer or panel must be accounted for here.
905 //
906 // We add an additional 1ms to allow for processing time and
907 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800908 info.presentationDeadline =
909 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700910
911 // All non-virtual displays are currently considered secure.
912 info.secure = true;
913
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800914 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700915 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800916 std::swap(info.w, info.h);
917 }
918
Michael Wright28f24d02016-07-12 13:30:53 -0700919 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700920 }
921
Dan Stoza7f7da322014-05-02 15:26:25 -0700922 return NO_ERROR;
923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
926 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700927 return BAD_VALUE;
928 }
929
Ana Krulecc2870422019-01-29 19:00:58 -0800930 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700931 return NO_ERROR;
932}
933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
935 const auto display = getDisplayDevice(displayToken);
936 if (!display) {
937 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800938 return BAD_VALUE;
939 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700942}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700943
Ady Abraham447052e2019-02-13 16:07:27 -0800944void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800945 Scheduler::ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948 // Lock is acquired by setRefreshRateTo.
949 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950 if (!display) {
951 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
952 displayToken.get());
953 return;
954 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700955 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800956 ALOGW("Attempt to set active config %d for virtual display", mode);
957 return;
958 }
959 int currentDisplayPowerMode = display->getPowerMode();
960 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
961 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700962 return;
963 }
964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800966 // config twice. However event generation config might have changed so we need to update it
967 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800969 const Scheduler::ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
Ady Abraham9360a222019-02-27 17:05:30 -0800970 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800971
972 if (!mDesiredActiveConfigChanged) {
973 // This is the first time we set the desired
974 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
975
976 // This will trigger HWC refresh without resetting the idle timer.
977 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979 mDesiredActiveConfigChanged = true;
980 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981}
982
983status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
984 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800985
986 std::vector<int32_t> allowedConfig;
987 allowedConfig.push_back(mode);
988
989 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990}
991
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992void SurfaceFlinger::setActiveConfigInternal() {
993 ATRACE_CALL();
994
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800996 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997
998 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
999 display->setActiveConfig(mUpcomingActiveConfig.configId);
1000
Ana Krulecc2870422019-01-29 19:00:58 -08001001 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001002 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1003 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001004 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001005 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001006 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1007 mUpcomingActiveConfig.configId);
1008 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001009}
1010
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001012 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 if (mCheckPendingFence) {
1014 if (mPreviousPresentFence != Fence::NO_FENCE &&
1015 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1016 // fence has not signaled yet. wait for the next invalidate
1017 repaintEverythingForHWC();
1018 return true;
1019 }
1020
1021 // We received the present fence from the HWC, so we assume it successfully updated
1022 // the config, hence we update SF.
1023 mCheckPendingFence = false;
1024 setActiveConfigInternal();
1025 }
1026
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 // Store the local variable to release the lock.
1028 ActiveConfigInfo desiredActiveConfig;
1029 {
1030 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 if (!mDesiredActiveConfigChanged) {
1032 return false;
1033 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 desiredActiveConfig = mDesiredActiveConfig;
1035 }
1036
1037 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1039 // display is not valid or we are already in the requested mode
1040 // on both cases there is nothing left to do
1041 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1042 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1043 mDesiredActiveConfigChanged = false;
1044 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1045 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047
Ady Abraham838de062019-02-04 10:24:03 -08001048 // Desired active config was set, it is different than the config currently in use, however
1049 // allowed configs might have change by the time we process the refresh.
1050 // Make sure the desired config is still allowed
1051 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1052 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1053 mDesiredActiveConfig.configId = display->getActiveConfig();
1054 return false;
1055 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 mUpcomingActiveConfig = desiredActiveConfig;
1057 const auto displayId = display->getId();
1058 LOG_ALWAYS_FATAL_IF(!displayId);
1059
1060 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1061 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1062
1063 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064 mCheckPendingFence = true;
1065
1066 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001067}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1070 Vector<ColorMode>* outColorModes) {
1071 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001072 return BAD_VALUE;
1073 }
1074
Peiyong Lina52f0292018-03-14 17:26:31 -07001075 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001076 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001077 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1078
1079 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1080 if (!displayId) {
1081 return NAME_NOT_FOUND;
1082 }
1083
Dominik Laskowski075d3172018-05-24 15:50:06 -07001084 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001085 }
Michael Wright28f24d02016-07-12 13:30:53 -07001086 outColorModes->clear();
1087 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1088
1089 return NO_ERROR;
1090}
1091
Daniel Solomon42d04562019-01-20 21:03:19 -08001092status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1093 ui::DisplayPrimaries &primaries) {
1094 if (!displayToken) {
1095 return BAD_VALUE;
1096 }
1097
1098 // Currently we only support this API for a single internal display.
1099 if (getInternalDisplayToken() != displayToken) {
1100 return BAD_VALUE;
1101 }
1102
1103 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1104 return NO_ERROR;
1105}
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1108 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001109 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001110 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001111 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001112}
1113
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001115 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 Vector<ColorMode> modes;
1117 getDisplayColorModes(displayToken, &modes);
1118 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1119 if (mode < ColorMode::NATIVE || !exists) {
1120 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1121 decodeColorMode(mode).c_str(), mode, displayToken.get());
1122 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001123 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124 const auto display = getDisplayDevice(displayToken);
1125 if (!display) {
1126 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1127 decodeColorMode(mode).c_str(), mode, displayToken.get());
1128 } else if (display->isVirtual()) {
1129 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1130 decodeColorMode(mode).c_str(), mode);
1131 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001132 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1133 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001134 }
1135 }));
1136
Michael Wright28f24d02016-07-12 13:30:53 -07001137 return NO_ERROR;
1138}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001139
Svetoslavd85084b2014-03-20 10:28:31 -07001140status_t SurfaceFlinger::clearAnimationFrameStats() {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.clearStats();
1143 return NO_ERROR;
1144}
1145
1146status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1147 Mutex::Autolock _l(mStateLock);
1148 mAnimFrameTracker.getStats(outStats);
1149 return NO_ERROR;
1150}
1151
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001152status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1153 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001154 Mutex::Autolock _l(mStateLock);
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const auto display = getDisplayDeviceLocked(displayToken);
1157 if (!display) {
1158 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001159 return BAD_VALUE;
1160 }
1161
Peiyong Linfb069302018-04-25 14:34:31 -07001162 // At this point the DisplayDeivce should already be set up,
1163 // meaning the luminance information is already queried from
1164 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001166 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1167 capabilities.getDesiredMaxLuminance(),
1168 capabilities.getDesiredMaxAverageLuminance(),
1169 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001170
1171 return NO_ERROR;
1172}
1173
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001174status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1175 ui::PixelFormat* outFormat,
1176 ui::Dataspace* outDataspace,
1177 uint8_t* outComponentMask) const {
1178 if (!outFormat || !outDataspace || !outComponentMask) {
1179 return BAD_VALUE;
1180 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001181 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001182 if (!display || !display->getId()) {
1183 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1184 return BAD_VALUE;
1185 }
1186 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1187 outDataspace, outComponentMask);
1188}
1189
Kevin DuBois74e53772018-11-19 10:52:38 -08001190status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1191 bool enable, uint8_t componentMask,
1192 uint64_t maxFrames) const {
1193 const auto display = getDisplayDevice(displayToken);
1194 if (!display || !display->getId()) {
1195 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1196 return BAD_VALUE;
1197 }
1198
1199 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1200 componentMask, maxFrames);
1201}
1202
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001203status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1204 uint64_t maxFrames, uint64_t timestamp,
1205 DisplayedFrameStats* outStats) const {
1206 const auto display = getDisplayDevice(displayToken);
1207 if (!display || !display->getId()) {
1208 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1209 return BAD_VALUE;
1210 }
1211
1212 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1213 outStats);
1214}
1215
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001216status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1217 if (!outSupported) {
1218 return BAD_VALUE;
1219 }
1220 *outSupported = getRenderEngine().supportsProtectedContent();
1221 return NO_ERROR;
1222}
1223
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001224status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1225 bool* outIsWideColorDisplay) const {
1226 if (!displayToken || !outIsWideColorDisplay) {
1227 return BAD_VALUE;
1228 }
1229 Mutex::Autolock _l(mStateLock);
1230 const auto display = getDisplayDeviceLocked(displayToken);
1231 if (!display) {
1232 return BAD_VALUE;
1233 }
1234 *outIsWideColorDisplay = display->hasWideColorGamut();
1235 return NO_ERROR;
1236}
1237
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001239 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001240 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001241
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 if (mInjectVSyncs == enable) {
1243 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001245
Ana Krulecc2870422019-01-29 19:00:58 -08001246 auto resyncCallback =
1247 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001249 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001250 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001251 if (enable) {
1252 ALOGV("VSync Injections enabled");
1253 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001254 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001255 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001257 impl::EventThread::InterceptVSyncsCallback(),
1258 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001260 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001261 } else {
1262 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001263 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1264 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 }
1266
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001267 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001268 }));
1269
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001270 return NO_ERROR;
1271}
1272
1273status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 Mutex::Autolock _l(mStateLock);
1275
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276 if (!mInjectVSyncs) {
1277 ALOGE("VSync Injections not enabled");
1278 return BAD_VALUE;
1279 }
1280 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1281 ALOGV("Injecting VSync inside SurfaceFlinger");
1282 mVSyncInjector->onInjectSyncEvent(when);
1283 }
1284 return NO_ERROR;
1285}
1286
Lloyd Pique755e3192018-01-31 16:46:15 -08001287status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1288 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001289 // Try to acquire a lock for 1s, fail gracefully
1290 const status_t err = mStateLock.timedLock(s2ns(1));
1291 const bool locked = (err == NO_ERROR);
1292 if (!locked) {
1293 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1294 return TIMED_OUT;
1295 }
1296
1297 outLayers->clear();
1298 mCurrentState.traverseInZOrder([&](Layer* layer) {
1299 outLayers->push_back(layer->getLayerDebugInfo());
1300 });
1301
1302 mStateLock.unlock();
1303 return NO_ERROR;
1304}
1305
Peiyong Linc6780972018-10-28 15:24:08 -07001306status_t SurfaceFlinger::getCompositionPreference(
1307 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1308 Dataspace* outWideColorGamutDataspace,
1309 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001310 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001311 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001312 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001313 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001314 return NO_ERROR;
1315}
1316
Dan Stozaec460082018-12-17 15:35:09 -08001317status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1318 const sp<IBinder>& stopLayerHandle,
1319 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001320 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001321 return BAD_VALUE;
1322 }
1323 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001324 return NO_ERROR;
1325}
1326
Dan Stozaec460082018-12-17 15:35:09 -08001327status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001328 if (!listener) {
1329 return BAD_VALUE;
1330 }
Dan Stozaec460082018-12-17 15:35:09 -08001331 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001332 return NO_ERROR;
1333}
Dan Gittik57e63c52019-01-18 16:37:54 +00001334
1335status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1336 bool* outSupport) const {
1337 if (!displayToken || !outSupport) {
1338 return BAD_VALUE;
1339 }
1340 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1341 if (!displayId) {
1342 return NAME_NOT_FOUND;
1343 }
1344 *outSupport =
1345 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1346 return NO_ERROR;
1347}
1348
1349status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1350 float brightness) const {
1351 if (!displayToken) {
1352 return BAD_VALUE;
1353 }
1354 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1355 if (!displayId) {
1356 return NAME_NOT_FOUND;
1357 }
1358 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1359}
1360
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001361// ----------------------------------------------------------------------------
1362
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001363sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1364 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001365 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001366 Mutex::Autolock lock(mStateLock);
1367 return getVsyncPeriod();
1368 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001369
Ana Krulecc2870422019-01-29 19:00:58 -08001370 const auto& handle =
1371 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001372
Ana Krulecc2870422019-01-29 19:00:58 -08001373 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001374}
1375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001376// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377
1378void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001379 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380}
1381
1382void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001383 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001384}
1385
1386void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001387 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388}
1389
1390void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001391 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001392 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001393}
1394
1395status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001396 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001397 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398}
1399
1400status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001401 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001402 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001403 if (res == NO_ERROR) {
1404 msg->wait();
1405 }
1406 return res;
1407}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001408
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001409void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001410 do {
1411 waitForEvent();
1412 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001413}
1414
Dominik Laskowski83b88212018-12-11 13:34:06 -08001415nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001416 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001417 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1418 return 0;
1419 }
1420
1421 const auto config = getHwComposer().getActiveConfig(*displayId);
1422 return config ? config->getVsyncPeriod() : 0;
1423}
1424
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001425void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1426 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001427 ATRACE_NAME("SF onVsync");
1428
Steven Thomas3cfac282017-02-06 12:29:30 -08001429 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001431 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 return;
1433 }
1434
Dominik Laskowski075d3172018-05-24 15:50:06 -07001435 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001436 return;
1437 }
1438
Dominik Laskowski075d3172018-05-24 15:50:06 -07001439 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001440 // For now, we don't do anything with external display vsyncs.
1441 return;
1442 }
1443
Ana Krulecc2870422019-01-29 19:00:58 -08001444 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001445}
1446
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001447void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001448 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1449 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001450}
1451
Ady Abraham838de062019-02-04 10:24:03 -08001452bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1453 std::lock_guard lock(mAllowedConfigsLock);
1454
1455 // if allowed configs are not set yet for this display, every config is considered allowed
1456 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1457 return true;
1458 }
1459
1460 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1461}
1462
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001463void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001464 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001465 return;
1466 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001467 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001468
Ana Krulec7d1d6832018-12-27 11:10:09 -08001469 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001470 const auto displayId = getInternalDisplayIdLocked();
1471 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001472 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001473
Ady Abraham1902d072019-03-01 17:18:59 -08001474 auto desiredConfigId = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate).configId;
1475 const auto display = getDisplayDeviceLocked(displayToken);
1476 if (desiredConfigId == display->getActiveConfig()) {
1477 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001478 }
Ady Abraham1902d072019-03-01 17:18:59 -08001479
1480 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1481 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1482 return;
1483 }
1484
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001485 mPhaseOffsets->setRefreshRateType(refreshRate);
Ady Abraham1902d072019-03-01 17:18:59 -08001486 setDesiredActiveConfig(getInternalDisplayTokenLocked(), desiredConfigId, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001487}
1488
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001489void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001490 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001491 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001492 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001493
Lloyd Piqueba04e622017-12-14 17:11:26 -08001494 // Ignore events that do not have the right sequenceId.
1495 if (sequenceId != getBE().mComposerSequenceId) {
1496 return;
1497 }
1498
Steven Thomasb02664d2017-07-26 18:48:28 -07001499 // Only lock if we're not on the main thread. This function is normally
1500 // called on a hwbinder thread, but for the primary display it's called on
1501 // the main thread with the state lock already held, so don't attempt to
1502 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001503 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001504
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001505 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001506
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001507 if (std::this_thread::get_id() == mMainThreadId) {
1508 // Process all pending hot plug events immediately if we are on the main thread.
1509 processDisplayHotplugEventsLocked();
1510 }
1511
Lloyd Piqueba04e622017-12-14 17:11:26 -08001512 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001513}
1514
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001515void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001516 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001517 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001519 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001520 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001521}
1522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001523void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001524 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001526 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001527 getHwComposer().setVsyncEnabled(*displayId,
1528 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1529 }
Mathias Agopian86303202012-07-24 22:46:10 -07001530}
1531
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001532// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001533void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001534 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001535 // Clear the drawing state so that the logic inside of
1536 // handleTransactionLocked will fire. It will determine the delta between
1537 // mCurrentState and mDrawingState and re-apply all changes when we make the
1538 // transition.
1539 mDrawingState.displays.clear();
1540 mDisplays.clear();
1541}
1542
Steven Thomas050b2c82017-03-06 11:45:16 -08001543void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001544 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001545 if (!mVrFlinger)
1546 return;
1547 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001548 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001549 return;
1550 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551
Lloyd Pique441d5042018-10-18 16:49:51 -07001552 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 ALOGE("Vr flinger is only supported for remote hardware composer"
1554 " service connections. Ignoring request to transition to vr"
1555 " flinger.");
1556 mVrFlingerRequestsDisplay = false;
1557 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001558 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001559
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001561
Steven Thomas0123ac62018-07-12 11:32:34 -07001562 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001563 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001564
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001565 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001566
1567 // Clear out all the output layers from the composition engine for all
1568 // displays before destroying the hardware composer interface. This ensures
1569 // any HWC layers are destroyed through that interface before it becomes
1570 // invalid.
1571 for (const auto& [token, displayDevice] : mDisplays) {
1572 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1573 compositionengine::Output::OutputLayers());
1574 }
1575
Steven Thomas0123ac62018-07-12 11:32:34 -07001576 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1577 // called below. Clear the reference now so we don't accidentally use it
1578 // later.
1579 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001580
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001583 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 // Delete the current instance before creating the new one
1587 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1588 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1589 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1590 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591
Lloyd Pique441d5042018-10-18 16:49:51 -07001592 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001593 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001594
1595 if (vrFlingerRequestsDisplay) {
1596 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001598
1599 mVisibleRegionsDirty = true;
1600 invalidateHwcGeometry();
1601
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001602 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001603 display = getDefaultDisplayDeviceLocked();
1604 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001605 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001606
Steven Thomasb02664d2017-07-26 18:48:28 -07001607 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001608 const nsecs_t vsyncPeriod = getVsyncPeriod();
1609 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001611 // The present fences returned from vr_hwc are not an accurate
1612 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001613 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Use phase of 0 since phase is not known.
1616 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001617 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001618 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001619
Ana Krulecc2870422019-01-29 19:00:58 -08001620 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001621
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001622 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001623 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001624}
1625
Mathias Agopian4fec8732012-06-29 14:12:52 -07001626void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001627 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001628 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 case MessageQueue::INVALIDATE: {
Alec Mouricc0fc602019-02-26 21:45:19 -08001630 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
1631 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
1632 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1633 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1634 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1635 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1636 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1637 if (frameMissed) {
1638 mFrameMissedCount++;
1639 mTimeStats->incrementMissedFrames();
1640 }
1641
Alec Mouri40189b02019-03-05 15:07:54 -08001642 if (hwcFrameMissed) {
1643 mHwcFrameMissedCount++;
1644 }
1645
1646 if (gpuFrameMissed) {
1647 mGpuFrameMissedCount++;
1648 }
1649
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001650 if (mUseSmart90ForVideo) {
1651 // This call is made each time SF wakes up and creates a new frame. It is part
1652 // of video detection feature.
1653 mScheduler->updateFpsBasedOnNativeWindowApi();
1654 }
1655
Ady Abrahamb838aed2019-02-12 15:30:16 -08001656 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001657 break;
1658 }
1659
Alec Mourife3dc942019-02-12 14:19:18 -08001660 // For now, only propagate backpressure when missing a hwc frame.
1661 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001662 if (mPropagateBackpressure) {
1663 signalLayerUpdate();
1664 break;
1665 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001666 }
Dan Stoza50182882016-07-08 12:02:20 -07001667
Steven Thomas050b2c82017-03-06 11:45:16 -08001668 // Now that we're going to make it to the handleMessageTransaction()
1669 // call below it's safe to call updateVrFlinger(), which will
1670 // potentially trigger a display handoff.
1671 updateVrFlinger();
1672
Dan Stoza6b9454d2014-11-07 16:00:59 -08001673 bool refreshNeeded = handleMessageTransaction();
1674 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001675
1676 updateCursorAsync();
1677 updateInputFlinger();
1678
Dan Stoza58784442014-12-02 16:58:17 -08001679 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001680 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001681 // Signal a refresh if a transaction modified the window state,
1682 // a new buffer was latched, or if HWC has requested a full
1683 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001684 signalRefresh();
1685 }
1686 break;
1687 }
1688 case MessageQueue::REFRESH: {
1689 handleMessageRefresh();
1690 break;
1691 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001692 }
1693}
1694
Dan Stoza6b9454d2014-11-07 16:00:59 -08001695bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001696 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001697 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001698
1699 // Apply any ready transactions in the queues if there are still transactions that have not been
1700 // applied, wake up during the next vsync period and check again
1701 bool transactionNeeded = false;
1702 if (!flushTransactionQueues()) {
1703 transactionNeeded = true;
1704 }
1705
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001707 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001709
1710 if (transactionNeeded) {
1711 setTransactionFlags(eTransactionNeeded);
1712 }
1713
1714 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715}
1716
Mathias Agopian4fec8732012-06-29 14:12:52 -07001717void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001719
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001720 mRefreshPending = false;
1721
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001722 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001723 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001724 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001725 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001726 for (const auto& [token, display] : mDisplays) {
1727 beginFrame(display);
1728 prepareFrame(display);
1729 doDebugFlashRegions(display, repaintEverything);
1730 doComposition(display, repaintEverything);
1731 }
1732
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001733 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001734
1735 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001736 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001737
Dan Stozabfbffeb2016-07-21 14:49:33 -07001738 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001739 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001740 for (const auto& [token, displayDevice] : mDisplays) {
1741 auto display = displayDevice->getCompositionDisplay();
1742 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001743 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001744 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001745 mHadDeviceComposition =
1746 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001747 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001748
Jorim Jaggi90535212018-05-23 23:44:06 +02001749 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001750
David Sodman7e4ae112018-02-09 15:02:28 -08001751 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001753
David Sodmanfa9b2af2017-12-24 13:28:59 -08001754
1755bool SurfaceFlinger::handleMessageInvalidate() {
1756 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001757 bool refreshNeeded = handlePageFlip();
1758
Vishnu Nair4351ad52019-02-11 14:13:02 -08001759 if (mVisibleRegionsDirty) {
1760 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001761 if (mTracingEnabled) {
1762 mTracing.notify("visibleRegionsDirty");
1763 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001764 }
1765
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001766 for (auto& layer : mLayersPendingRefresh) {
1767 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001768 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001769 invalidateLayerStack(layer, visibleReg);
1770 }
1771 mLayersPendingRefresh.clear();
1772 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773}
1774
David Sodman79bba0e2018-08-05 18:07:49 -07001775void SurfaceFlinger::calculateWorkingSet() {
1776 ATRACE_CALL();
1777 ALOGV(__FUNCTION__);
1778
David Sodman79bba0e2018-08-05 18:07:49 -07001779 // build the h/w work list
1780 if (CC_UNLIKELY(mGeometryInvalid)) {
1781 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 for (const auto& [token, displayDevice] : mDisplays) {
1783 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001784
Lloyd Piquea83776c2019-01-29 18:42:32 -08001785 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001786
Lloyd Piquea83776c2019-01-29 18:42:32 -08001787 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1788 auto& compositionState = layer->editState();
1789 compositionState.forceClientComposition = false;
1790 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1791 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001792 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001793
Lloyd Piquea83776c2019-01-29 18:42:32 -08001794 // The output Z order is set here based on a simple counter.
1795 compositionState.z = zOrder++;
1796
1797 // Update the display independent composition state. This goes
1798 // to the general composition layer state structure.
1799 // TODO: Do this once per compositionengine::CompositionLayer.
1800 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1801 true);
1802
1803 // Recalculate the geometry state of the output layer.
1804 layer->updateCompositionState(true);
1805
1806 // Write the updated geometry state to the HWC
1807 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 }
1809 }
1810 }
1811
1812 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 for (const auto& [token, displayDevice] : mDisplays) {
1814 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001815 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001816 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001817 continue;
1818 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001819 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001820
1821 if (mDrawingState.colorMatrixChanged) {
1822 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001823 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001824 Dataspace targetDataspace = Dataspace::UNKNOWN;
1825 if (useColorManagement) {
1826 ColorMode colorMode;
1827 RenderIntent renderIntent;
1828 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1829 display->setColorMode(colorMode, targetDataspace, renderIntent);
1830 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001832 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001833 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001834 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1835 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001836 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001837 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001838 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1839 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001840 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001841 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 }
1843
Peiyong Lind3788632018-09-18 16:01:31 -07001844 // TODO(b/111562338) remove when composer 2.3 is shipped.
1845 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001846 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001847 }
1848
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001849 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001850 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001851 }
1852
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001853 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001854 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001855 layer->setCompositionType(displayDevice,
1856 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001857 continue;
1858 }
1859
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001861 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001862 displayDevice->getSupportedPerFrameMetadata(),
1863 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1864 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001865 }
1866 }
1867
1868 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001869
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001870 for (const auto& [token, displayDevice] : mDisplays) {
1871 auto display = displayDevice->getCompositionDisplay();
1872 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001873 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1874 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1875 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001876 }
1877 }
David Sodman79bba0e2018-08-05 18:07:49 -07001878}
1879
Lloyd Pique32cbe282018-10-19 13:09:22 -07001880void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1881 bool repaintEverything) {
1882 auto display = displayDevice->getCompositionDisplay();
1883 const auto& displayState = display->getState();
1884
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885 // is debugging enabled
1886 if (CC_LIKELY(!mDebugRegion))
1887 return;
1888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001890 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001891 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001892 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001893 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001894 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001895 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001897 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 }
1899 }
1900
Lloyd Pique32cbe282018-10-19 13:09:22 -07001901 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001902
1903 if (mDebugRegion > 1) {
1904 usleep(mDebugRegion * 1000);
1905 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001906
Lloyd Pique32cbe282018-10-19 13:09:22 -07001907 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001908}
1909
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001910void SurfaceFlinger::logLayerStats() {
1911 ATRACE_CALL();
1912 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001913 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001915 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001916 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917 }
1918 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001919
1920 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001921 }
1922}
1923
David Sodman2b406362017-12-15 13:33:47 -08001924void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 ATRACE_CALL();
1927 ALOGV("preComposition");
1928
David Sodman2b406362017-12-15 13:33:47 -08001929 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1930
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001932 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001933 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 needExtraInvalidate = true;
1935 }
Robert Carr2047fae2016-11-28 14:09:09 -08001936 });
1937
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 if (needExtraInvalidate) {
1939 signalLayerUpdate();
1940 }
1941}
1942
Ana Krulece588e312018-09-18 12:32:24 -07001943void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1944 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945 // Update queue of past composite+present times and determine the
1946 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001947 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001949 while (!getBE().mCompositePresentTimes.empty()) {
1950 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951 // Cached values should have been updated before calling this method,
1952 // which helps avoid duplicate syscalls.
1953 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1954 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1955 break;
1956 }
1957 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001958 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959 }
1960
1961 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001962 while (getBE().mCompositePresentTimes.size() > 16) {
1963 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964 }
1965
Ana Krulece588e312018-09-18 12:32:24 -07001966 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001967}
1968
Ana Krulece588e312018-09-18 12:32:24 -07001969void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1970 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971 // Integer division and modulo round toward 0 not -inf, so we need to
1972 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001973 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1974 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1975 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976
Ana Krulec757f63a2019-01-25 10:46:18 -08001977 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001978 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001979 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001980 }
1981
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001982 // Snap the latency to a value that removes scheduling jitter from the
1983 // composition and present times, which often have >1ms of jitter.
1984 // Reducing jitter is important if an app attempts to extrapolate
1985 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001986 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001987 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001988 nsecs_t bias = stats.vsyncPeriod / 2;
1989 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1990 nsecs_t snappedCompositeToPresentLatency =
1991 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001992
David Sodman99974d22017-11-28 12:04:33 -08001993 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001994 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1995 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001996 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001997}
1998
David Sodman2b406362017-12-15 13:33:47 -08001999void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 ATRACE_CALL();
2002 ALOGV("postComposition");
2003
Brian Anderson3546a3f2016-07-14 11:51:14 -07002004 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002005 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002006 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002007 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 }
2009
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002010 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002011 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012
David Sodman73beded2017-11-15 11:56:06 -08002013 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002014 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002015 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002017 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2018 ->getRenderSurface()
2019 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 } else {
2022 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2023 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024
David Sodman73beded2017-11-15 11:56:06 -08002025 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002026 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2027 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002028 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030
Ana Krulece588e312018-09-18 12:32:24 -07002031 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002032 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033
David Sodman2b406362017-12-15 13:33:47 -08002034 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002035 // when we started doing work for this frame, but that should be okay
2036 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002037 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002038 CompositorTiming compositorTiming;
2039 {
David Sodman99974d22017-11-28 12:04:33 -08002040 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2041 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002042 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043
Robert Carr2047fae2016-11-28 14:09:09 -08002044 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002045 bool frameLatched =
2046 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2047 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002048 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002049 recordBufferingStats(layer->getName().string(),
2050 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002051 }
Robert Carr2047fae2016-11-28 14:09:09 -08002052 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002053
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002054 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002055 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002056 }
2057
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002058 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002059 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2060 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002061 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002062 }
2063 }
2064
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002065 if (mAnimCompositionPending) {
2066 mAnimCompositionPending = false;
2067
Brian Anderson4e606e32017-03-16 15:34:57 -07002068 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002069 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002070 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002071 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002072 // The HWC doesn't support present fences, so use the refresh
2073 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002074 const nsecs_t presentTime =
2075 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002076 mAnimFrameTracker.setActualPresentTime(presentTime);
2077 }
2078 mAnimFrameTracker.advanceFrame();
2079 }
Dan Stozab90cf072015-03-05 11:05:59 -08002080
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002081 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002082 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002083 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002084 }
2085
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002086 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002087
Lloyd Pique32cbe282018-10-19 13:09:22 -07002088 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2089 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002090 return;
2091 }
2092
2093 nsecs_t currentTime = systemTime();
2094 if (mHasPoweredOff) {
2095 mHasPoweredOff = false;
2096 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002097 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002098 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002099 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2100 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002101 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002102 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002103 }
David Sodman4a36e932017-11-07 14:29:47 -08002104 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002105 }
David Sodman4a36e932017-11-07 14:29:47 -08002106 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002107
2108 {
2109 std::lock_guard lock(mTexturePoolMutex);
2110 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2111 if (refillCount > 0) {
2112 const size_t offset = mTexturePool.size();
2113 mTexturePool.resize(mTexturePoolSize);
2114 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2115 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2116 }
2117 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002118
Marissa Wallfda30bb2018-10-12 11:34:28 -07002119 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002120 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002121
Kevin DuBois413287f2019-02-25 08:46:47 -08002122 if (mLumaSampling && mRegionSamplingThread) {
2123 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002124 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125}
2126
Vishnu Nair4351ad52019-02-11 14:13:02 -08002127void SurfaceFlinger::computeLayerBounds() {
2128 for (const auto& pair : mDisplays) {
2129 const auto& displayDevice = pair.second;
2130 const auto display = displayDevice->getCompositionDisplay();
2131 for (const auto& layer : mDrawingState.layersSortedByZ) {
2132 // only consider the layers on the given layer stack
2133 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002134 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002135 }
2136
2137 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2138 }
2139 }
2140}
2141
Mathias Agopiancd60f992012-08-16 16:28:27 -07002142void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 ATRACE_CALL();
2144 ALOGV("rebuildLayerStacks");
2145
Mathias Agopiancd60f992012-08-16 16:28:27 -07002146 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002147 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002148 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002149 mVisibleRegionsDirty = false;
2150 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002151
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002152 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 const auto& displayDevice = pair.second;
2154 auto display = displayDevice->getCompositionDisplay();
2155 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002156 Region opaqueRegion;
2157 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002158 compositionengine::Output::OutputLayers layersSortedByZ;
2159 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002160 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002161 const ui::Transform& tr = displayState.transform;
2162 const Rect bounds = displayState.bounds;
2163 if (displayState.isEnabled) {
2164 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002165
Jeff Sharkey76488112017-02-27 14:15:18 -07002166 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002167 auto compositionLayer = layer->getCompositionLayer();
2168 if (compositionLayer == nullptr) {
2169 return;
2170 }
2171
Lloyd Pique32cbe282018-10-19 13:09:22 -07002172 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002173 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2174 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2175
Lloyd Pique07e33212018-12-18 16:33:37 -08002176 bool needsOutputLayer = false;
2177
Lloyd Piqueef36b002019-01-23 17:52:04 -08002178 if (display->belongsInOutput(layer->getLayerStack(),
2179 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002180 Region drawRegion(tr.transform(
2181 layer->visibleNonTransparentRegion));
2182 drawRegion.andSelf(bounds);
2183 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002184 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002185 }
Chia-I Wu83806892017-11-16 10:50:20 -08002186 }
2187
Lloyd Pique07e33212018-12-18 16:33:37 -08002188 if (needsOutputLayer) {
2189 layersSortedByZ.emplace_back(
2190 display->getOrCreateOutputLayer(displayId, compositionLayer,
2191 layerFE));
2192 deprecated_layersSortedByZ.add(layer);
2193
2194 auto& outputLayerState = layersSortedByZ.back()->editState();
2195 outputLayerState.visibleRegion =
2196 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2197 } else if (displayId) {
2198 // For layers that are being removed from a HWC display,
2199 // and that have queued frames, add them to a a list of
2200 // released layers so we can properly set a fence.
2201 bool hasExistingOutputLayer =
2202 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2203 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2204 mLayersWithQueuedFrames.cend(),
2205 layer) != mLayersWithQueuedFrames.cend();
2206
2207 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002208 layersNeedingFences.add(layer);
2209 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 });
2212 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002213
2214 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2215
2216 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002217 displayDevice->setLayersNeedingFences(layersNeedingFences);
2218
2219 Region undefinedRegion{bounds};
2220 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2221
2222 display->editState().undefinedRegion = undefinedRegion;
2223 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002224 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002225 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002226}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002227
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002228// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002229// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002230// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002231// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002232// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002233// The returned HDR data space is one of
2234// - Dataspace::UNKNOWN
2235// - Dataspace::BT2020_HLG
2236// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2238 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002239 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002240 *outHdrDataSpace = Dataspace::UNKNOWN;
2241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002242 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002243 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002244 case Dataspace::V0_SCRGB:
2245 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002246 case Dataspace::BT2020:
2247 case Dataspace::BT2020_ITU:
2248 case Dataspace::BT2020_LINEAR:
2249 case Dataspace::DISPLAY_BT2020:
2250 bestDataSpace = Dataspace::DISPLAY_BT2020;
2251 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002252 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002253 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002254 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 case Dataspace::BT2020_PQ:
2256 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002257 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002258 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002260 case Dataspace::BT2020_HLG:
2261 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002262 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263 // When there's mixed PQ content and HLG content, we set the HDR
2264 // data space to be BT2020_PQ and convert HLG to PQ.
2265 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2266 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002267 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 break;
2269 default:
2270 break;
2271 }
Romain Guy54f154a2017-10-24 21:40:32 +01002272 }
2273
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002275}
2276
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002278void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2279 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2281 *outMode = ColorMode::NATIVE;
2282 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002285 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002286
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002290 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2291
Peiyong Lina3ea5592019-02-10 14:45:00 -08002292 switch (mForceColorMode) {
2293 case ColorMode::SRGB:
2294 bestDataSpace = Dataspace::V0_SRGB;
2295 break;
2296 case ColorMode::DISPLAY_P3:
2297 bestDataSpace = Dataspace::DISPLAY_P3;
2298 break;
2299 default:
2300 break;
2301 }
2302
Peiyong Lindfde5112018-06-05 10:58:41 -07002303 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002304 const bool isHdr =
2305 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002306 if (isHdr) {
2307 bestDataSpace = hdrDataSpace;
2308 }
2309
Chia-I Wu0d711262018-05-21 15:19:35 -07002310 RenderIntent intent;
2311 switch (mDisplayColorSetting) {
2312 case DisplayColorSetting::MANAGED:
2313 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002314 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002315 break;
2316 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002317 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002318 break;
2319 default: // vendor display color setting
2320 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2321 break;
2322 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002323
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002324 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002325}
2326
Lloyd Pique32cbe282018-10-19 13:09:22 -07002327void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2328 auto display = displayDevice->getCompositionDisplay();
2329 const auto& displayState = display->getState();
2330
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002331 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002332 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2333 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002334
David Sodmanfa9b2af2017-12-24 13:28:59 -08002335 // If nothing has changed (!dirty), don't recompose.
2336 // If something changed, but we don't currently have any visible layers,
2337 // and didn't when we last did a composition, then skip it this time.
2338 // The second rule does two things:
2339 // - When all layers are removed from a display, we'll emit one black
2340 // frame, then nothing more until we get new layers.
2341 // - When a display is created with a private layer stack, we won't
2342 // emit any black frames until a layer is added to the layer stack.
2343 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002344
Dominik Laskowski075d3172018-05-24 15:50:06 -07002345 const char flagPrefix[] = {'-', '+'};
2346 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002347 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2348 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2349 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2350 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002351
Lloyd Pique31cb2942018-10-19 17:23:03 -07002352 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002353
David Sodmanfa9b2af2017-12-24 13:28:59 -08002354 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002355 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002356 }
2357}
2358
Lloyd Pique32cbe282018-10-19 13:09:22 -07002359void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2360 auto display = displayDevice->getCompositionDisplay();
2361 const auto& displayState = display->getState();
2362
2363 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002364 return;
David Sodman2b406362017-12-15 13:33:47 -08002365 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002367 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002369 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002370}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002371
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002373 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374 ALOGV("doComposition");
2375
Lloyd Pique32cbe282018-10-19 13:09:22 -07002376 auto display = displayDevice->getCompositionDisplay();
2377 const auto& displayState = display->getState();
2378
2379 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002381 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002382
David Sodmanfa9b2af2017-12-24 13:28:59 -08002383 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002384 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002385
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002387 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002388 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002390}
2391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392void SurfaceFlinger::postFrame()
2393{
2394 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 const auto display = getDefaultDisplayDeviceLocked();
2396 if (display && getHwComposer().isConnected(*display->getId())) {
2397 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2399 logFrameStats();
2400 }
2401 }
2402}
2403
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002405 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002407
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408 auto display = displayDevice->getCompositionDisplay();
2409 const auto& displayState = display->getState();
2410 const auto displayId = display->getId();
2411
David Sodmanfa9b2af2017-12-24 13:28:59 -08002412 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002413
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 if (displayId) {
2416 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002417 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002418 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002419 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002420 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002421 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002422
Chia-I Wu7b549592017-11-15 09:14:57 -08002423 // The layer buffer from the previous frame (if any) is released
2424 // by HWC only when the release fence from this frame (if any) is
2425 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002426 if (layer->getState().hwc) {
2427 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002428 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002429 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2430 usedClientComposition =
2431 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002432 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002433
2434 // If the layer was client composited in the previous frame, we
2435 // need to merge with the previous client target acquire fence.
2436 // Since we do not track that, always merge with the current
2437 // client target acquire fence when it is available, even though
2438 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002439 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002440 releaseFence =
2441 Fence::merge("LayerRelease", releaseFence,
2442 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002443 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002444
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002445 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 }
Chia-I Wu83806892017-11-16 10:50:20 -08002447
2448 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002450 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002453 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002455 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002456 }
2457 }
2458
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 if (displayId) {
2460 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002461 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002462 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463}
2464
Mathias Agopian87baae12012-07-31 12:38:26 -07002465void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466{
Mathias Agopian841cde52012-03-01 15:44:37 -08002467 ATRACE_CALL();
2468
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002469 // here we keep a copy of the drawing state (that is the state that's
2470 // going to be overwritten by handleTransactionLocked()) outside of
2471 // mStateLock so that the side-effects of the State assignment
2472 // don't happen with mStateLock held (which can cause deadlocks).
2473 State drawingState(mDrawingState);
2474
Mathias Agopianca4d3602011-05-19 15:38:14 -07002475 Mutex::Autolock _l(mStateLock);
2476 const nsecs_t now = systemTime();
2477 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478
Mathias Agopianca4d3602011-05-19 15:38:14 -07002479 // Here we're guaranteed that some transaction flags are set
2480 // so we can call handleTransactionLocked() unconditionally.
2481 // We call getTransactionFlags(), which will also clear the flags,
2482 // with mStateLock held to guarantee that mCurrentState won't change
2483 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002484
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002485 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002486 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002487 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002488
Mathias Agopianca4d3602011-05-19 15:38:14 -07002489 mLastTransactionTime = systemTime() - now;
2490 mDebugInTransaction = 0;
2491 invalidateHwcGeometry();
2492 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002493}
2494
Lloyd Piqueba04e622017-12-14 17:11:26 -08002495void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2496 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 const std::optional<DisplayIdentificationInfo> info =
2498 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002499
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002501 continue;
2502 }
2503
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002506 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 mPhysicalDisplayTokens[info->id] = new BBinder();
2508 DisplayDeviceState state;
2509 state.displayId = info->id;
2510 state.isSecure = true; // All physical displays are currently considered secure.
2511 state.displayName = info->name;
2512 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2513 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002514 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002515 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002516 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002517
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2519 if (index >= 0) {
2520 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2521 mInterceptor->saveDisplayDeletion(state.sequenceId);
2522 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002523 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002525 }
2526
2527 processDisplayChangesLocked();
2528 }
2529
2530 mPendingHotplugEvents.clear();
2531}
2532
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002533void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002534 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2535 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002536}
2537
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002540 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 const sp<IGraphicBufferProducer>& producer) {
2542 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002543 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002545 creationArgs.isSecure = state.isSecure;
2546 creationArgs.displaySurface = dispSurface;
2547 creationArgs.hasWideColorGamut = false;
2548 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002549
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002550 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 creationArgs.isPrimary = isInternalDisplay;
2552
2553 if (useColorManagement && displayId) {
2554 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002556 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002557 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002559
Dominik Laskowski7e045462018-05-30 13:02:02 -07002560 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 }
tangrobin6753a022018-08-10 10:58:54 +08002564 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 if (displayId) {
2567 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002568 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002570 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571
Lloyd Pique90c115d2018-09-18 21:39:42 -07002572 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002574 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576 // Make sure that composition can never be stalled by a virtual display
2577 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002578 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002579 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2581 }
2582
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 creationArgs.displayInstallOrientation =
2584 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002585
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002587 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588
Lloyd Pique90c115d2018-09-18 21:39:42 -07002589 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590
2591 if (maxFrameBufferAcquiredBuffers >= 3) {
2592 nativeWindowSurface->preallocateBuffers();
2593 }
2594
2595 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002596 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002599 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002601 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2602 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 if (!state.isVirtual()) {
2604 LOG_ALWAYS_FATAL_IF(!displayId);
2605 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002606 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 display->setLayerStack(state.layerStack);
2609 display->setProjection(state.orientation, state.viewport, state.frame);
2610 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613}
2614
Lloyd Pique347200f2017-12-14 17:00:15 -08002615void SurfaceFlinger::processDisplayChangesLocked() {
2616 // here we take advantage of Vector's copy-on-write semantics to
2617 // improve performance by skipping the transaction entirely when
2618 // know that the lists are identical
2619 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2620 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2621 if (!curr.isIdenticalTo(draw)) {
2622 mVisibleRegionsDirty = true;
2623 const size_t cc = curr.size();
2624 size_t dc = draw.size();
2625
2626 // find the displays that were removed
2627 // (ie: in drawing state but not in current state)
2628 // also handle displays that changed
2629 // (ie: displays that are in both lists)
2630 for (size_t i = 0; i < dc;) {
2631 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2632 if (j < 0) {
2633 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002634 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002635 // Save display ID before disconnecting.
2636 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002637 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002638
2639 if (!display->isVirtual()) {
2640 LOG_ALWAYS_FATAL_IF(!displayId);
2641 dispatchDisplayHotplugEvent(displayId->value, false);
2642 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002644
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002645 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002646 } else {
2647 // this display is in both lists. see if something changed.
2648 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002649 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002650 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2651 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2652 if (state_binder != draw_binder) {
2653 // changing the surface is like destroying and
2654 // recreating the DisplayDevice, so we just remove it
2655 // from the drawing state, so that it get re-added
2656 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002658 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002659 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 mDrawingState.displays.removeItemsAt(i);
2662 dc--;
2663 // at this point we must loop to the next item
2664 continue;
2665 }
2666
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002667 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002668 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002669 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002670 }
2671 if ((state.orientation != draw[i].orientation) ||
2672 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002674 }
2675 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 }
2678 }
2679 }
2680 ++i;
2681 }
2682
2683 // find displays that were added
2684 // (ie: in current state but not in drawing state)
2685 for (size_t i = 0; i < cc; i++) {
2686 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2687 const DisplayDeviceState& state(curr[i]);
2688
Lloyd Pique542307f2018-10-19 13:24:08 -07002689 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002690 sp<IGraphicBufferProducer> producer;
2691 sp<IGraphicBufferProducer> bqProducer;
2692 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002693 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002694
Dominik Laskowski075d3172018-05-24 15:50:06 -07002695 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002696 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002697 // Virtual displays without a surface are dormant:
2698 // they have external state (layer stack, projection,
2699 // etc.) but no internal state (i.e. a DisplayDevice).
2700 if (state.surface != nullptr) {
2701 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002702 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 int width = 0;
2704 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2705 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2706 int height = 0;
2707 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2708 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2709 int intFormat = 0;
2710 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2711 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002712 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 displayId =
2715 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 }
2717
2718 // TODO: Plumb requested format back up to consumer
2719
2720 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002721 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 bqProducer, bqConsumer,
2723 state.displayName);
2724
2725 dispSurface = vds;
2726 producer = vds;
2727 }
2728 } else {
2729 ALOGE_IF(state.surface != nullptr,
2730 "adding a supported display, but rendering "
2731 "surface is provided (%p), ignoring it",
2732 state.surface.get());
2733
Dominik Laskowski075d3172018-05-24 15:50:06 -07002734 displayId = state.displayId;
2735 LOG_ALWAYS_FATAL_IF(!displayId);
2736 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 producer = bqProducer;
2738 }
2739
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002742 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002743 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002744 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002745 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002747 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 }
2749 }
2750 }
2751 }
2752 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002753
2754 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002755}
2756
Mathias Agopian87baae12012-07-31 12:38:26 -07002757void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002758{
Dan Stoza7dde5992015-05-22 09:51:44 -07002759 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mCurrentState.traverseInZOrder([](Layer* layer) {
2761 layer->notifyAvailableFrames();
2762 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002763
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 /*
2765 * Traversal of the children
2766 * (perform the transaction for each of them if needed)
2767 */
2768
Mathias Agopian3559b072012-08-15 13:46:03 -07002769 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002770 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002772 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
2774 const uint32_t flags = layer->doTransaction(0);
2775 if (flags & Layer::eVisibleRegion)
2776 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002777
2778 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002779 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002780 }
Robert Carr2047fae2016-11-28 14:09:09 -08002781 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 }
2783
2784 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002785 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 */
2787
Mathias Agopiane57f2922012-08-09 16:29:12 -07002788 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002789 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002790 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002791 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002793 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002794 // The transform hint might have changed for some layers
2795 // (either because a display has changed, or because a layer
2796 // as changed).
2797 //
2798 // Walk through all the layers in currentLayers,
2799 // and update their transform hint.
2800 //
2801 // If a layer is visible only on a single display, then that
2802 // display is used to calculate the hint, otherwise we use the
2803 // default display.
2804 //
2805 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2806 // the hint is set before we acquire a buffer from the surface texture.
2807 //
2808 // NOTE: layer transactions have taken place already, so we use their
2809 // drawing state. However, SurfaceFlinger's own transaction has not
2810 // happened yet, so we must use the current state layer list
2811 // (soon to become the drawing state list).
2812 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002814 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002815 bool first = true;
2816 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002817 // NOTE: we rely on the fact that layers are sorted by
2818 // layerStack first (so we don't have to traverse the list
2819 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002821 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002822 currentlayerStack = layerStack;
2823 // figure out if this layerstack is mirrored
2824 // (more than one display) if so, pick the default display,
2825 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 hintDisplay = nullptr;
2827 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002828 if (display->getCompositionDisplay()
2829 ->belongsInOutput(layer->getLayerStack(),
2830 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 if (hintDisplay) {
2832 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002833 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002834 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002836 }
2837 }
2838 }
2839 }
Chet Haase91d25932013-04-11 15:24:55 -07002840
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002842 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2843 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002844
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002845 // could be null when this layer is using a layerStack
2846 // that is not visible on any display. Also can occur at
2847 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002849 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002850
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002852 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 if (hintDisplay) {
2854 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002855 }
Robert Carr2047fae2016-11-28 14:09:09 -08002856
2857 first = false;
2858 });
Mathias Agopian84300952012-11-21 16:02:13 -08002859 }
2860
2861
Mathias Agopian3559b072012-08-15 13:46:03 -07002862 /*
2863 * Perform our own transaction if needed
2864 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865
2866 if (mLayersAdded) {
2867 mLayersAdded = false;
2868 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002869 mVisibleRegionsDirty = true;
2870 }
2871
2872 // some layers might have been removed, so
2873 // we need to update the regions they're exposing.
2874 if (mLayersRemoved) {
2875 mLayersRemoved = false;
2876 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002877 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002879 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002881 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002882 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002883 }
Robert Carr2047fae2016-11-28 14:09:09 -08002884 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
2886
Vishnu Nairec0ab382019-02-13 15:32:56 -08002887 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002889}
2890
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002891void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002892 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002893 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002894 return;
2895 }
2896
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002897 if (mVisibleRegionsDirty || mInputInfoChanged) {
2898 mInputInfoChanged = false;
2899 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002900 } else if (mInputWindowCommands.syncInputWindows) {
2901 // If the caller requested to sync input windows, but there are no
2902 // changes to input windows, notify immediately.
2903 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002904 }
2905
2906 executeInputWindowCommands();
2907}
2908
2909void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002910 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002911
2912 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2913 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002914 // When calculating the screen bounds we ignore the transparent region since it may
2915 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002916 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002917 }
2918 });
chaviw291d88a2019-02-14 10:33:58 -08002919
2920 mInputFlinger->setInputWindows(inputHandles,
2921 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2922 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002923}
2924
Vishnu Nairec0ab382019-02-13 15:32:56 -08002925void SurfaceFlinger::commitInputWindowCommands() {
2926 mInputWindowCommands.merge(mPendingInputWindowCommands);
2927 mPendingInputWindowCommands.clear();
2928}
2929
chaviwfbe5d9c2018-12-26 12:23:37 -08002930void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002931 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2932 if (transferTouchFocusCommand.fromToken != nullptr &&
2933 transferTouchFocusCommand.toToken != nullptr &&
2934 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2935 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2936 transferTouchFocusCommand.toToken);
2937 }
2938 }
2939
2940 mInputWindowCommands.clear();
2941}
2942
Riley Andrews03414a12014-07-01 14:22:59 -07002943void SurfaceFlinger::updateCursorAsync()
2944{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002946 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002947 continue;
2948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002950 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2951 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002952 }
2953 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002954}
2955
chaviw61626f22018-11-15 16:26:27 -08002956void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2957 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002958 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002959 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002960 }
2961 layer->releasePendingBuffer(systemTime());
2962}
2963
Mathias Agopian4fec8732012-06-29 14:12:52 -07002964void SurfaceFlinger::commitTransaction()
2965{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002966 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002967 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 for (const auto& l : mLayersPendingRemoval) {
2969 recordBufferingStats(l->getName().string(),
2970 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002971
Lloyd Pique07e33212018-12-18 16:33:37 -08002972 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002973 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002974 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002975 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002976 }
2977 mLayersPendingRemoval.clear();
2978 }
2979
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002980 // If this transaction is part of a window animation then the next frame
2981 // we composite should be considered an animation as well.
2982 mAnimCompositionPending = mAnimTransactionPending;
2983
Nataniel Borges2b796da2019-02-15 13:32:18 -08002984 withTracingLock([&]() {
2985 mDrawingState = mCurrentState;
2986 // clear the "changed" flags in current state
2987 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002988
Nataniel Borges2b796da2019-02-15 13:32:18 -08002989 mDrawingState.traverseInZOrder([](Layer* layer) { layer->commitChildList(); });
Robert Carr1f0a16a2016-10-24 16:27:39 -07002990 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002991
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002992 mTransactionPending = false;
2993 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995}
2996
Nataniel Borges2b796da2019-02-15 13:32:18 -08002997void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2998 if (mTracingEnabledChanged) {
2999 mTracingEnabled = mTracing.isEnabled();
3000 mTracingEnabledChanged = false;
3001 }
3002
3003 // Synchronize with Tracing thread
3004 std::unique_lock<std::mutex> lock;
3005 if (mTracingEnabled) {
3006 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3007 }
3008
3009 lockedOperation();
3010
3011 // Synchronize with Tracing thread
3012 if (mTracingEnabled) {
3013 lock.unlock();
3014 }
3015}
3016
Lloyd Pique32cbe282018-10-19 13:09:22 -07003017void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003019 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003021
Lloyd Pique32cbe282018-10-19 13:09:22 -07003022 auto display = displayDevice->getCompositionDisplay();
3023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024 Region aboveOpaqueLayers;
3025 Region aboveCoveredLayers;
3026 Region dirty;
3027
Mathias Agopian87baae12012-07-31 12:38:26 -07003028 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029
Robert Carr2047fae2016-11-28 14:09:09 -08003030 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003031 // start with the whole surface at its current location
3032 const Layer::State& s(layer->getDrawingState());
3033
Jesse Hall01e29052013-02-19 16:13:35 -08003034 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003035 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003036 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003038
Mathias Agopianab028732010-03-16 16:41:46 -07003039 /*
3040 * opaqueRegion: area of a surface that is fully opaque.
3041 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003043
3044 /*
3045 * visibleRegion: area of a surface that is visible on screen
3046 * and not fully transparent. This is essentially the layer's
3047 * footprint minus the opaque regions above it.
3048 * Areas covered by a translucent surface are considered visible.
3049 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003051
3052 /*
3053 * coveredRegion: area of a surface that is covered by all
3054 * visible regions above it (which includes the translucent areas).
3055 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003057
Jesse Halla8026d22012-09-25 13:25:04 -07003058 /*
3059 * transparentRegion: area of a surface that is hinted to be completely
3060 * transparent. This is only used to tell when the layer has no visible
3061 * non-transparent regions and can be removed from the layer list. It
3062 * does not affect the visibleRegion of this layer or any layers
3063 * beneath it. The hint may not be correct if apps don't respect the
3064 * SurfaceView restrictions (which, sadly, some don't).
3065 */
3066 Region transparentRegion;
3067
Mathias Agopianab028732010-03-16 16:41:46 -07003068
3069 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003070 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003071 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003072 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003075 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003076 if (!visibleRegion.isEmpty()) {
3077 // Remove the transparent area from the visible region
3078 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003079 if (tr.preserveRects()) {
3080 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003081 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003082 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003083 // transformation too complex, can't do the
3084 // transparent region optimization.
3085 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003086 }
Mathias Agopianab028732010-03-16 16:41:46 -07003087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088
Mathias Agopianab028732010-03-16 16:41:46 -07003089 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003090 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003091 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003092 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003093 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003094 // the opaque region is the layer's footprint
3095 opaqueRegion = visibleRegion;
3096 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 }
3098 }
3099
Robert Carre5f4f692018-01-12 13:12:28 -08003100 if (visibleRegion.isEmpty()) {
3101 layer->clearVisibilityRegions();
3102 return;
3103 }
3104
Mathias Agopianab028732010-03-16 16:41:46 -07003105 // Clip the covered region to the visible region
3106 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3107
3108 // Update aboveCoveredLayers for next (lower) layer
3109 aboveCoveredLayers.orSelf(visibleRegion);
3110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 // subtract the opaque region covered by the layers above us
3112 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113
3114 // compute this layer's dirty region
3115 if (layer->contentDirty) {
3116 // we need to invalidate the whole region
3117 dirty = visibleRegion;
3118 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003119 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 layer->contentDirty = false;
3121 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003122 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003123 * the exposed region consists of two components:
3124 * 1) what's VISIBLE now and was COVERED before
3125 * 2) what's EXPOSED now less what was EXPOSED before
3126 *
3127 * note that (1) is conservative, we start with the whole
3128 * visible region but only keep what used to be covered by
3129 * something -- which mean it may have been exposed.
3130 *
3131 * (2) handles areas that were not covered by anything but got
3132 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003133 */
Mathias Agopianab028732010-03-16 16:41:46 -07003134 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003135 const Region oldVisibleRegion = layer->visibleRegion;
3136 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003137 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3138 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 }
3140 dirty.subtractSelf(aboveOpaqueLayers);
3141
3142 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003143 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144
Mathias Agopianab028732010-03-16 16:41:46 -07003145 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003147
Jesse Halla8026d22012-09-25 13:25:04 -07003148 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 layer->setVisibleRegion(visibleRegion);
3150 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003151 layer->setVisibleNonTransparentRegion(
3152 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003153 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154
Mathias Agopian87baae12012-07-31 12:38:26 -07003155 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156}
3157
Chia-I Wuab0c3192017-08-01 11:29:00 -07003158void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003159 for (const auto& [token, displayDevice] : mDisplays) {
3160 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003161 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003162 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003163 }
3164 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003165}
3166
Dan Stoza6b9454d2014-11-07 16:00:59 -08003167bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 ALOGV("handlePageFlip");
3170
Brian Andersond6927fb2016-07-23 23:37:30 -07003171 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003174 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003175 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003176
3177 // Store the set of layers that need updates. This set must not change as
3178 // buffers are being latched, as this could result in a deadlock.
3179 // Example: Two producers share the same command stream and:
3180 // 1.) Layer 0 is latched
3181 // 2.) Layer 0 gets a new frame
3182 // 2.) Layer 1 gets a new frame
3183 // 3.) Layer 1 is latched.
3184 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3185 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003186 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003187 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003188 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003189 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003190 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003191 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003192 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003193 } else {
3194 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003195 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003196 } else {
3197 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003198 }
Robert Carr2047fae2016-11-28 14:09:09 -08003199 });
3200
Lloyd Piquef2c79392018-12-20 16:23:33 -08003201 if (!mLayersWithQueuedFrames.empty()) {
3202 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3203 // writes to Layer current state. See also b/119481871
3204 Mutex::Autolock lock(mStateLock);
3205
3206 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003207 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003208 mLayersPendingRefresh.push_back(layer);
3209 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003210 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003211 if (layer->isBufferLatched()) {
3212 newDataLatched = true;
3213 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003214 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003215 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003216
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003217 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003218
3219 // If we will need to wake up at some time in the future to deal with a
3220 // queued frame that shouldn't be displayed during this vsync period, wake
3221 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003222 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003223 signalLayerUpdate();
3224 }
3225
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003226 // enter boot animation on first buffer latch
3227 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3228 ALOGI("Enter boot animation");
3229 mBootStage = BootStage::BOOTANIMATION;
3230 }
3231
Dan Stoza6b9454d2014-11-07 16:00:59 -08003232 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003233 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234}
3235
Mathias Agopianad456f92011-01-13 17:53:01 -08003236void SurfaceFlinger::invalidateHwcGeometry()
3237{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003238 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003239}
3240
Lloyd Pique32cbe282018-10-19 13:09:22 -07003241void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003242 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003243 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003244 // We only need to actually compose the display if:
3245 // 1) It is being handled by hardware composer, which may need this to
3246 // keep its virtual display state machine in sync, or
3247 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003248 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003249 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003250 return;
3251 }
3252
Dan Stoza9e56aa02015-11-02 13:00:03 -08003253 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003254 base::unique_fd readyFence;
3255 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003256
3257 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003258 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259}
3260
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003261bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3262 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003263 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003264 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003265
Lloyd Pique32cbe282018-10-19 13:09:22 -07003266 auto display = displayDevice->getCompositionDisplay();
3267 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003268 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003269 auto& renderEngine = getRenderEngine();
3270 const bool supportProtectedContent =
3271 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003272
3273 const Region bounds(displayState.bounds);
3274 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003275 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003276 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003277
Peiyong Lind3788632018-09-18 16:01:31 -07003278 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003279 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003280
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003281 renderengine::DisplaySettings clientCompositionDisplay;
3282 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3283 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003284 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003285
Dan Stoza9e56aa02015-11-02 13:00:03 -08003286 if (hasClientComposition) {
3287 ALOGV("hasClientComposition");
3288
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003289 if (displayDevice->isPrimary() && supportProtectedContent) {
3290 bool needsProtected = false;
3291 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3292 // If the layer is a protected layer, mark protected context is needed.
3293 if (layer->isProtected()) {
3294 needsProtected = true;
3295 break;
3296 }
3297 }
3298 if (needsProtected != renderEngine.isProtected() &&
3299 renderEngine.useProtectedContext(needsProtected)) {
3300 display->getRenderSurface()->setProtected(needsProtected);
3301 }
3302 }
3303
Alec Mouri6338c9d2019-02-07 16:57:51 -08003304 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003305
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003306 if (buf == nullptr) {
3307 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3308 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310 return false;
3311 }
3312
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003313 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3314 clientCompositionDisplay.clip = displayState.scissor;
3315 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003316 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003317
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003318 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003319 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003320 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003322 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 clientCompositionDisplay.outputDataspace = outputDataspace;
3324 clientCompositionDisplay.maxLuminance =
3325 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003326
Lloyd Pique441d5042018-10-18 16:49:51 -07003327 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003328 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003329 getHwComposer()
3330 .hasDisplayCapability(displayId,
3331 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003332
Peiyong Lind3788632018-09-18 16:01:31 -07003333 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003334 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3335 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003336 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003337 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003338 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003339
Mathias Agopian85d751c2012-08-29 16:59:24 -07003340 /*
3341 * and then, render the layers targeted at the framebuffer
3342 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003343
Dan Stoza9e56aa02015-11-02 13:00:03 -08003344 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003345 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003346 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003347 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003348 const Region viewportRegion(displayState.viewport);
3349 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003350 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003351 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003352 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003353 switch (layer->getCompositionType(displayDevice)) {
3354 case Hwc2::IComposerClient::Composition::CURSOR:
3355 case Hwc2::IComposerClient::Composition::DEVICE:
3356 case Hwc2::IComposerClient::Composition::SIDEBAND:
3357 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003358 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003359 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003360 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003361 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003362 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003363 // never clear the very first layer since we're
3364 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003365 renderengine::LayerSettings layerSettings;
3366 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003367 bool prepared =
3368 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3369 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003370
3371 if (prepared) {
3372 layerSettings.source.buffer.buffer = nullptr;
3373 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3374 layerSettings.alpha = half(0.0);
3375 layerSettings.disableBlending = true;
3376 clientCompositionLayers.push_back(layerSettings);
3377 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003378 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003379 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003380 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003381 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003382 renderengine::LayerSettings layerSettings;
3383 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003384 layer->prepareClientLayer(renderArea, clip, clearRegion,
3385 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003386 if (prepared) {
3387 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003388 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 break;
3390 }
3391 default:
3392 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003393 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003394 } else {
3395 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003396 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003397 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003398 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003399
Alec Mouri820c7402019-01-23 13:02:39 -08003400 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003401 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003403
3404 // We boost GPU frequency here because there will be color spaces conversion
3405 // and it's expensive. We boost the GPU frequency so that GPU composition can
3406 // finish in time. We must reset GPU frequency afterwards, because high frequency
3407 // consumes extra battery.
3408 const bool expensiveRenderingExpected =
3409 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3410 if (expensiveRenderingExpected && displayId) {
3411 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3412 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003413 if (!debugRegion.isEmpty()) {
3414 Region::const_iterator it = debugRegion.begin();
3415 Region::const_iterator end = debugRegion.end();
3416 while (it != end) {
3417 const Rect& rect = *it++;
3418 renderengine::LayerSettings layerSettings;
3419 layerSettings.source.buffer.buffer = nullptr;
3420 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3421 layerSettings.geometry.boundaries = rect.toFloatRect();
3422 layerSettings.alpha = half(1.0);
3423 clientCompositionLayers.push_back(layerSettings);
3424 }
3425 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003426 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3427 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003428 if (expensiveRenderingExpected && displayId) {
3429 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3430 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003431 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003432 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433}
3434
Chia-I Wu28e3a252018-09-07 12:05:02 -07003435void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003436 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003437 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438}
3439
Dan Stoza7d89d062015-04-30 13:29:25 -07003440status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003441 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003442 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003444 const sp<Layer>& parent,
3445 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003446{
Dan Stoza7d89d062015-04-30 13:29:25 -07003447 // add this layer to the current state list
3448 {
3449 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003451 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3452 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 return NO_MEMORY;
3454 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003455 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003456 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003457 } else if (parent == nullptr) {
3458 lbc->onRemovedFromCurrentState();
3459 } else if (parent->isRemovedFromCurrentState()) {
3460 parent->addChild(lbc);
3461 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 parent->addChild(lbc);
3464 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003465
Yiwei Zhang243b3782018-05-15 17:40:04 -07003466 if (gbc != nullptr) {
3467 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3468 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3469 mMaxGraphicBufferProducerListSize,
3470 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3471 mGraphicBufferProducerList.size(),
3472 mMaxGraphicBufferProducerListSize, mNumLayers);
3473 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003475 }
3476
Mathias Agopian96f08192010-06-02 23:28:45 -07003477 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003478 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003479
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003481}
3482
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003483uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003484 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003485}
3486
Mathias Agopian3f844832013-08-07 21:24:32 -07003487uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003488 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489}
3490
Mathias Agopian3f844832013-08-07 21:24:32 -07003491uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003492 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003493}
3494
3495uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003496 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003497 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003498 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003500 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501 }
3502 return old;
3503}
3504
Marissa Wall713b63f2018-10-17 15:42:43 -07003505bool SurfaceFlinger::flushTransactionQueues() {
3506 Mutex::Autolock _l(mStateLock);
3507 auto it = mTransactionQueues.begin();
3508 while (it != mTransactionQueues.end()) {
3509 auto& [applyToken, transactionQueue] = *it;
3510
3511 while (!transactionQueue.empty()) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003512 const auto& [states, displays, flags, desiredPresentTime, postTime, privileged] =
Robert Carr14167e02019-02-13 13:50:55 -08003513 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003514 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003515 break;
3516 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003517 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
Valerie Hau0779ded2019-03-19 12:43:04 -07003518 desiredPresentTime, postTime, privileged, /*isMainThread*/ true);
Marissa Wall713b63f2018-10-17 15:42:43 -07003519 transactionQueue.pop();
3520 }
3521
3522 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3523 }
3524 return mTransactionQueues.empty();
3525}
3526
chaviwca27f252018-02-06 16:46:39 -08003527bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3528 for (const ComposerState& state : states) {
3529 // Here we need to check that the interface we're given is indeed
3530 // one of our own. A malicious client could give us a nullptr
3531 // IInterface, or one of its own or even one of our own but a
3532 // different type. All these situations would cause us to crash.
3533 if (state.client == nullptr) {
3534 return true;
3535 }
3536
3537 sp<IBinder> binder = IInterface::asBinder(state.client);
3538 if (binder == nullptr) {
3539 return true;
3540 }
3541
3542 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3543 return true;
3544 }
3545 }
3546 return false;
3547}
3548
Marissa Wall17b4e452018-12-26 16:32:34 -08003549bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3550 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003551 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003552 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3553 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3554 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3555 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3556 return false;
3557 }
3558
Marissa Wall713b63f2018-10-17 15:42:43 -07003559 for (const ComposerState& state : states) {
3560 const layer_state_t& s = state.state;
3561 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3562 continue;
3563 }
3564 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003565 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003566 }
3567 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003568 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003569}
3570
3571void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3572 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003573 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003574 const InputWindowCommands& inputWindowCommands,
3575 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003576 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003577
Valerie Haubc6ddb12019-03-08 11:10:15 -08003578 const int64_t postTime = systemTime();
3579
Robert Carr14167e02019-02-13 13:50:55 -08003580 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3581
Mathias Agopian698c0872011-06-28 19:09:31 -07003582 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583
chaviwca27f252018-02-06 16:46:39 -08003584 if (containsAnyInvalidClientState(states)) {
3585 return;
3586 }
3587
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 // If its TransactionQueue already has a pending TransactionState or if it is pending
3589 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003590 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003591 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003592 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003593 setTransactionFlags(eTransactionNeeded);
3594 return;
3595 }
3596
Valerie Haubc6ddb12019-03-08 11:10:15 -08003597 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
3598 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003599}
3600
3601void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003602 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003603 const InputWindowCommands& inputWindowCommands,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003604 const int64_t desiredPresentTime, const int64_t postTime,
Valerie Hau0779ded2019-03-19 12:43:04 -07003605 bool privileged, bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003606 uint32_t transactionFlags = 0;
3607
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003608 if (flags & eAnimation) {
3609 // For window updates that are part of an animation we must wait for
3610 // previous animation "frames" to be handled.
3611 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003612 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003613 if (CC_UNLIKELY(err != NO_ERROR)) {
3614 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003615 // caller after a few seconds.
3616 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3617 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003618 mAnimTransactionPending = false;
3619 break;
3620 }
3621 }
3622 }
3623
chaviwca27f252018-02-06 16:46:39 -08003624 for (const DisplayState& display : displays) {
3625 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003626 }
3627
Marissa Walle2ffb422018-10-12 11:33:52 -07003628 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003629 for (const ComposerState& state : states) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003630 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged);
chaviwca27f252018-02-06 16:46:39 -08003631 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 // If the state doesn't require a traversal and there are callbacks, send them now
3633 if (!(clientStateFlags & eTraversalNeeded)) {
3634 mTransactionCompletedThread.sendCallbacks();
3635 }
3636 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003637
chaviw273171b2018-12-26 11:46:30 -08003638 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3639
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003640 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3641 // anyway. This can be used as a flush mechanism for previous async transactions.
3642 // Empty animation transaction can be used to simulate back-pressure, so also force a
3643 // transaction for empty animation transactions.
3644 if (transactionFlags == 0 &&
3645 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003646 transactionFlags = eTransactionNeeded;
3647 }
3648
Mathias Agopian386aa982011-11-07 21:58:03 -08003649 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003650 if (mInterceptor->isEnabled()) {
3651 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003652 }
Irvel468051e2016-06-13 16:44:44 -07003653
Mathias Agopian386aa982011-11-07 21:58:03 -08003654 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003655 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3656 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003657 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003658
3659 // if this is a synchronous transaction, wait for it to take effect
3660 // before returning.
3661 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003662 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003663 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003664 if (flags & eAnimation) {
3665 mAnimTransactionPending = true;
3666 }
chaviw95ef3c42019-02-14 10:55:09 -08003667
3668 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
Valerie Hau0779ded2019-03-19 12:43:04 -07003669
3670 // applyTransactionState can be called by either the main SF thread or by
3671 // another process through setTransactionState. While a given process may wish
3672 // to wait on synchronous transactions, the main SF thread should never
3673 // be blocked. Therefore, we only wait if isMainThread is false.
3674 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3676 if (CC_UNLIKELY(err != NO_ERROR)) {
3677 // just in case something goes wrong in SF, return to the
3678 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3680 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003681 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003682 break;
3683 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003685 }
3686}
3687
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003688uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3689 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3690 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003691
Mathias Agopiane57f2922012-08-09 16:29:12 -07003692 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003693 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3694
3695 const uint32_t what = s.what;
3696 if (what & DisplayState::eSurfaceChanged) {
3697 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3698 state.surface = s.surface;
3699 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003700 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003701 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003702 if (what & DisplayState::eLayerStackChanged) {
3703 if (state.layerStack != s.layerStack) {
3704 state.layerStack = s.layerStack;
3705 flags |= eDisplayTransactionNeeded;
3706 }
3707 }
3708 if (what & DisplayState::eDisplayProjectionChanged) {
3709 if (state.orientation != s.orientation) {
3710 state.orientation = s.orientation;
3711 flags |= eDisplayTransactionNeeded;
3712 }
3713 if (state.frame != s.frame) {
3714 state.frame = s.frame;
3715 flags |= eDisplayTransactionNeeded;
3716 }
3717 if (state.viewport != s.viewport) {
3718 state.viewport = s.viewport;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 }
3722 if (what & DisplayState::eDisplaySizeChanged) {
3723 if (state.width != s.width) {
3724 state.width = s.width;
3725 flags |= eDisplayTransactionNeeded;
3726 }
3727 if (state.height != s.height) {
3728 state.height = s.height;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 }
3732
Mathias Agopiane57f2922012-08-09 16:29:12 -07003733 return flags;
3734}
3735
Robert Carr14167e02019-02-13 13:50:55 -08003736bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003737 IPCThreadState* ipc = IPCThreadState::self();
3738 const int pid = ipc->getCallingPid();
3739 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003740 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003741 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003742 return false;
3743 }
3744 return true;
3745}
3746
Robert Carr14167e02019-02-13 13:50:55 -08003747uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003748 int64_t desiredPresentTime, int64_t postTime,
3749 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003750 const layer_state_t& s = composerState.state;
3751 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3752
Mathias Agopian13127d82013-03-05 17:47:11 -08003753 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003754 if (layer == nullptr) {
3755 return 0;
3756 }
3757
chaviw8b3871a2017-11-01 17:41:01 -07003758 uint32_t flags = 0;
3759
Garfield Tan8a3083e2018-12-03 13:21:07 -08003760 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003761 bool geometryAppliesWithResize =
3762 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003763
3764 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3765 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003766 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003767 layer->pushPendingState();
3768 }
3769
chaviw8b3871a2017-11-01 17:41:01 -07003770 if (what & layer_state_t::ePositionChanged) {
3771 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3772 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 }
chaviw8b3871a2017-11-01 17:41:01 -07003774 }
3775 if (what & layer_state_t::eLayerChanged) {
3776 // NOTE: index needs to be calculated before we update the state
3777 const auto& p = layer->getParent();
3778 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003779 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003780 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003781 mCurrentState.layersSortedByZ.removeAt(idx);
3782 mCurrentState.layersSortedByZ.add(layer);
3783 // we need traversal (state changed)
3784 // AND transaction (list changed)
3785 flags |= eTransactionNeeded|eTraversalNeeded;
3786 }
chaviw8b3871a2017-11-01 17:41:01 -07003787 } else {
3788 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003789 flags |= eTransactionNeeded|eTraversalNeeded;
3790 }
3791 }
chaviw8b3871a2017-11-01 17:41:01 -07003792 }
3793 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003794 // NOTE: index needs to be calculated before we update the state
3795 const auto& p = layer->getParent();
3796 if (p == nullptr) {
3797 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3798 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3799 mCurrentState.layersSortedByZ.removeAt(idx);
3800 mCurrentState.layersSortedByZ.add(layer);
3801 // we need traversal (state changed)
3802 // AND transaction (list changed)
3803 flags |= eTransactionNeeded|eTraversalNeeded;
3804 }
3805 } else {
3806 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3807 flags |= eTransactionNeeded|eTraversalNeeded;
3808 }
chaviw8b3871a2017-11-01 17:41:01 -07003809 }
3810 }
3811 if (what & layer_state_t::eSizeChanged) {
3812 if (layer->setSize(s.w, s.h)) {
3813 flags |= eTraversalNeeded;
3814 }
3815 }
3816 if (what & layer_state_t::eAlphaChanged) {
3817 if (layer->setAlpha(s.alpha))
3818 flags |= eTraversalNeeded;
3819 }
3820 if (what & layer_state_t::eColorChanged) {
3821 if (layer->setColor(s.color))
3822 flags |= eTraversalNeeded;
3823 }
Peiyong Lind3788632018-09-18 16:01:31 -07003824 if (what & layer_state_t::eColorTransformChanged) {
3825 if (layer->setColorTransform(s.colorTransform)) {
3826 flags |= eTraversalNeeded;
3827 }
3828 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003829 if (what & layer_state_t::eBackgroundColorChanged) {
3830 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3831 flags |= eTraversalNeeded;
3832 }
3833 }
chaviw8b3871a2017-11-01 17:41:01 -07003834 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003835 // TODO: b/109894387
3836 //
3837 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3838 // rotation. To see the problem observe that if we have a square parent, and a child
3839 // of the same size, then we rotate the child 45 degrees around it's center, the child
3840 // must now be cropped to a non rectangular 8 sided region.
3841 //
3842 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3843 // private API, and the WindowManager only uses rotation in one case, which is on a top
3844 // level layer in which cropping is not an issue.
3845 //
3846 // However given that abuse of rotation matrices could lead to surfaces extending outside
3847 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3848 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3849 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003850 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003851 flags |= eTraversalNeeded;
3852 }
3853 if (what & layer_state_t::eTransparentRegionChanged) {
3854 if (layer->setTransparentRegionHint(s.transparentRegion))
3855 flags |= eTraversalNeeded;
3856 }
3857 if (what & layer_state_t::eFlagsChanged) {
3858 if (layer->setFlags(s.flags, s.mask))
3859 flags |= eTraversalNeeded;
3860 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003861 if (what & layer_state_t::eCropChanged_legacy) {
3862 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003863 flags |= eTraversalNeeded;
3864 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003865 if (what & layer_state_t::eCornerRadiusChanged) {
3866 if (layer->setCornerRadius(s.cornerRadius))
3867 flags |= eTraversalNeeded;
3868 }
chaviw8b3871a2017-11-01 17:41:01 -07003869 if (what & layer_state_t::eLayerStackChanged) {
3870 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3871 // We only allow setting layer stacks for top level layers,
3872 // everything else inherits layer stack from its parent.
3873 if (layer->hasParent()) {
3874 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3875 layer->getName().string());
3876 } else if (idx < 0) {
3877 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3878 "that also does not appear in the top level layer list. Something"
3879 " has gone wrong.", layer->getName().string());
3880 } else if (layer->setLayerStack(s.layerStack)) {
3881 mCurrentState.layersSortedByZ.removeAt(idx);
3882 mCurrentState.layersSortedByZ.add(layer);
3883 // we need traversal (state changed)
3884 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003885 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003886 }
3887 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003888 if (what & layer_state_t::eDeferTransaction_legacy) {
3889 if (s.barrierHandle_legacy != nullptr) {
3890 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3891 } else if (s.barrierGbp_legacy != nullptr) {
3892 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003893 if (authenticateSurfaceTextureLocked(gbp)) {
3894 const auto& otherLayer =
3895 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003896 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003897 } else {
3898 ALOGE("Attempt to defer transaction to to an"
3899 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003900 }
3901 }
chaviw8b3871a2017-11-01 17:41:01 -07003902 // We don't trigger a traversal here because if no other state is
3903 // changed, we don't want this to cause any more work
3904 }
3905 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003906 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003907 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003908 if (!hadParent) {
3909 mCurrentState.layersSortedByZ.remove(layer);
3910 }
chaviw8b3871a2017-11-01 17:41:01 -07003911 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003912 }
chaviw8b3871a2017-11-01 17:41:01 -07003913 }
3914 if (what & layer_state_t::eReparentChildren) {
3915 if (layer->reparentChildren(s.reparentHandle)) {
3916 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003917 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003918 }
chaviw8b3871a2017-11-01 17:41:01 -07003919 if (what & layer_state_t::eDetachChildren) {
3920 layer->detachChildren();
3921 }
3922 if (what & layer_state_t::eOverrideScalingModeChanged) {
3923 layer->setOverrideScalingMode(s.overrideScalingMode);
3924 // We don't trigger a traversal here because if no other state is
3925 // changed, we don't want this to cause any more work
3926 }
Marissa Wall61c58622018-07-18 10:12:20 -07003927 if (what & layer_state_t::eTransformChanged) {
3928 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3931 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3932 flags |= eTraversalNeeded;
3933 }
3934 if (what & layer_state_t::eCropChanged) {
3935 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3936 }
Marissa Wall861616d2018-10-22 12:52:23 -07003937 if (what & layer_state_t::eFrameChanged) {
3938 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3939 }
Marissa Wall61c58622018-07-18 10:12:20 -07003940 if (what & layer_state_t::eAcquireFenceChanged) {
3941 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3942 }
3943 if (what & layer_state_t::eDataspaceChanged) {
3944 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3945 }
3946 if (what & layer_state_t::eHdrMetadataChanged) {
3947 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3948 }
3949 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3950 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3951 }
3952 if (what & layer_state_t::eApiChanged) {
3953 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3954 }
3955 if (what & layer_state_t::eSidebandStreamChanged) {
3956 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3957 }
Robert Carr720e5062018-07-30 17:45:14 -07003958 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003959 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003960 layer->setInputInfo(s.inputInfo);
3961 flags |= eTraversalNeeded;
3962 } else {
3963 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3964 }
Robert Carr720e5062018-07-30 17:45:14 -07003965 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003966 if (what & layer_state_t::eMetadataChanged) {
3967 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3968 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003969 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3970 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3971 flags |= eTraversalNeeded;
3972 }
3973 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003974 std::vector<sp<CallbackHandle>> callbackHandles;
3975 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3976 mTransactionCompletedThread.run();
3977 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3978 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3979 }
3980 }
Marissa Wall73411622019-01-25 10:45:41 -08003981
3982 if (what & layer_state_t::eBufferChanged) {
3983 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3984 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3985 s.buffer);
3986 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003987 if (what & layer_state_t::eCachedBufferChanged) {
3988 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003989 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3990 s.cachedBuffer.bufferId);
Valerie Haubc6ddb12019-03-08 11:10:15 -08003991 if (layer->setBuffer(buffer)) {
3992 flags |= eTraversalNeeded;
3993 layer->setPostTime(postTime);
3994 layer->setDesiredPresentTime(desiredPresentTime);
3995 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003996 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003997 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3998 // Do not put anything that updates layer state or modifies flags after
3999 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004000 return flags;
4001}
4002
chaviw273171b2018-12-26 11:46:30 -08004003uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4004 uint32_t flags = 0;
4005 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4006 flags |= eTraversalNeeded;
4007 }
4008
chaviwa911b102019-02-14 10:18:33 -08004009 if (inputWindowCommands.syncInputWindows) {
4010 flags |= eTraversalNeeded;
4011 }
4012
Vishnu Nairec0ab382019-02-13 15:32:56 -08004013 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004014 return flags;
4015}
4016
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004017status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4018 uint32_t h, PixelFormat format, uint32_t flags,
4019 LayerMetadata metadata, sp<IBinder>* handle,
4020 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004021 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004022 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004023 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004024 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004025 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004026
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004027 status_t result = NO_ERROR;
4028
4029 sp<Layer> layer;
4030
Cody Northropbc755282017-03-31 12:00:08 -06004031 String8 uniqueName = getUniqueLayerName(name);
4032
Evan Roskya1f1e152019-01-24 16:17:46 -08004033 bool primaryDisplayOnly = false;
4034
4035 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4036 // TODO b/64227542
4037 if (metadata.has(METADATA_WINDOW_TYPE)) {
4038 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4039 if (windowType == 441731) {
4040 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4041 primaryDisplayOnly = true;
4042 }
4043 }
4044
Mathias Agopian3165cc22012-08-08 19:42:09 -07004045 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004046 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004047 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4048 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004051 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004052 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4053 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004054 break;
chaviw13fdc492017-06-27 12:40:18 -07004055 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004056 // check if buffer size is set for color layer.
4057 if (w > 0 || h > 0) {
4058 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4059 int(w), int(h));
4060 return BAD_VALUE;
4061 }
4062
Evan Roskya1f1e152019-01-24 16:17:46 -08004063 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4064 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004065 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004066 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004067 // check if buffer size is set for container layer.
4068 if (w > 0 || h > 0) {
4069 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4070 int(w), int(h));
4071 return BAD_VALUE;
4072 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004073 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4074 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004075 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 default:
4077 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 break;
4079 }
4080
Dan Stoza7d89d062015-04-30 13:29:25 -07004081 if (result != NO_ERROR) {
4082 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004084
Evan Roskya1f1e152019-01-24 16:17:46 -08004085 if (primaryDisplayOnly) {
4086 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004087 }
4088
Robert Carrb89ea9d2018-12-10 13:01:14 -08004089 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4090 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4091 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004092 if (result != NO_ERROR) {
4093 return result;
4094 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004095 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004096
4097 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004098 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099}
4100
Cody Northropbc755282017-03-31 12:00:08 -06004101String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4102{
4103 bool matchFound = true;
4104 uint32_t dupeCounter = 0;
4105
4106 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4107 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4108
Dan Stoza436ccf32018-06-21 12:10:12 -07004109 // Grab the state lock since we're accessing mCurrentState
4110 Mutex::Autolock lock(mStateLock);
4111
Cody Northropbc755282017-03-31 12:00:08 -06004112 // Loop over layers until we're sure there is no matching name
4113 while (matchFound) {
4114 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004115 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004116 if (layer->getName() == uniqueName) {
4117 matchFound = true;
4118 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4119 }
4120 });
4121 }
4122
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004123 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4124 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004125
4126 return uniqueName;
4127}
4128
Marissa Wallfd668622018-05-10 10:21:13 -07004129status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4130 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004131 LayerMetadata metadata, PixelFormat& format,
4132 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004133 sp<IGraphicBufferProducer>* gbp,
4134 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004136 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 case PIXEL_FORMAT_TRANSPARENT:
4138 case PIXEL_FORMAT_TRANSLUCENT:
4139 format = PIXEL_FORMAT_RGBA_8888;
4140 break;
4141 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004142 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004143 break;
4144 }
4145
Evan Roskya1f1e152019-01-24 16:17:46 -08004146 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4147 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004148 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004149 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004150 *handle = layer->getHandle();
4151 *gbp = layer->getProducer();
4152 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154
Marissa Wallfd668622018-05-10 10:21:13 -07004155 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157}
4158
Marissa Wall61c58622018-07-18 10:12:20 -07004159status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4160 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004161 LayerMetadata metadata, sp<IBinder>* handle,
4162 sp<Layer>* outLayer) {
4163 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4164 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004165 *handle = layer->getHandle();
4166 *outLayer = layer;
4167
4168 return NO_ERROR;
4169}
4170
Evan Roskya1f1e152019-01-24 16:17:46 -08004171status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4172 uint32_t h, uint32_t flags, LayerMetadata metadata,
4173 sp<IBinder>* handle, sp<Layer>* outLayer) {
4174 *outLayer = getFactory().createColorLayer(
4175 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004176 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004177 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004178}
4179
Evan Roskya1f1e152019-01-24 16:17:46 -08004180status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4181 uint32_t w, uint32_t h, uint32_t flags,
4182 LayerMetadata metadata, sp<IBinder>* handle,
4183 sp<Layer>* outLayer) {
4184 *outLayer = getFactory().createContainerLayer(
4185 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004186 *handle = (*outLayer)->getHandle();
4187 return NO_ERROR;
4188}
4189
4190
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004191void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004192 mLayersPendingRemoval.add(layer);
4193 mLayersRemoved = true;
4194 setTransactionFlags(eTransactionNeeded);
4195}
4196
Robert Carr695d5282018-12-18 15:27:58 -08004197void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004198{
Robert Carr2e102c92018-10-23 12:11:15 -07004199 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004200 // If a layer has a parent, we allow it to out-live it's handle
4201 // with the idea that the parent holds a reference and will eventually
4202 // be cleaned up. However no one cleans up the top-level so we do so
4203 // here.
4204 if (layer->getParent() == nullptr) {
4205 mCurrentState.layersSortedByZ.remove(layer);
4206 }
4207 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004208 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004209}
4210
Mathias Agopianb60314a2012-04-10 22:09:54 -07004211// ---------------------------------------------------------------------------
4212
Andy McFadden13a082e2012-08-24 10:16:42 -07004213void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 const auto display = getDefaultDisplayDeviceLocked();
4215 if (!display) return;
4216
4217 const sp<IBinder> token = display->getDisplayToken().promote();
4218 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004219
Jesse Hall01e29052013-02-19 16:13:35 -08004220 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004221 Vector<ComposerState> state;
4222 Vector<DisplayState> displays;
4223 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004224 d.what = DisplayState::eDisplayProjectionChanged |
4225 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004227 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004228 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004229 d.frame.makeInvalid();
4230 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004231 d.width = 0;
4232 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004233 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004234 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004235
Dominik Laskowskie9774092018-12-11 10:04:24 -08004236 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004237
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 const nsecs_t vsyncPeriod = getVsyncPeriod();
4239 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004240
Brian Andersond0010582017-03-07 13:20:31 -08004241 // Use phase of 0 since phase is not known.
4242 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004243 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004244 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004245}
4246
4247void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004248 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 postMessageAsync(
4250 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004251}
4252
Dominik Laskowskie9774092018-12-11 10:04:24 -08004253void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 if (display->isVirtual()) {
4255 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004256 return;
4257 }
4258
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 const auto displayId = display->getId();
4260 LOG_ALWAYS_FATAL_IF(!displayId);
4261
Dominik Laskowski34157762018-10-31 13:07:19 -07004262 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004263
4264 int currentMode = display->getPowerMode();
4265 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004266 return;
4267 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004268
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004269 display->setPowerMode(mode);
4270
Lloyd Pique4dccc412018-01-22 17:21:36 -08004271 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004272 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004273 }
4274
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004275 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004276 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004278 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004279 mScheduler->onScreenAcquired(mAppConnectionHandle);
4280 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004281 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004282
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004283 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004284 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004285 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004286
4287 struct sched_param param = {0};
4288 param.sched_priority = 1;
4289 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4290 ALOGW("Couldn't set SCHED_FIFO on display on");
4291 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004292 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004293 // Turn off the display
4294 struct sched_param param = {0};
4295 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4296 ALOGW("Couldn't set SCHED_OTHER on display off");
4297 }
4298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004300 mScheduler->disableHardwareVsync(true);
4301 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004302 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004303
Dominik Laskowski075d3172018-05-24 15:50:06 -07004304 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004305 mVisibleRegionsDirty = true;
4306 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004307 } else if (mode == HWC_POWER_MODE_DOZE ||
4308 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004309 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004312 mScheduler->onScreenAcquired(mAppConnectionHandle);
4313 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004314 }
4315 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4316 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004318 mScheduler->disableHardwareVsync(true);
4319 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004320 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004322 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004323 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004327 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004328 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004329 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004330 // Update refresh rate stats.
4331 mRefreshRateStats->setPowerMode(mode);
4332 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004333 }
4334
Dominik Laskowski34157762018-10-31 13:07:19 -07004335 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004336}
4337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004339 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004340 const auto display = getDisplayDevice(displayToken);
4341 if (!display) {
4342 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4343 displayToken.get());
4344 } else if (display->isVirtual()) {
4345 ALOGW("Attempt to set power mode %d for virtual display", mode);
4346 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004347 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004348 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004349 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004350}
4351
4352// ---------------------------------------------------------------------------
4353
Dominik Laskowskic2867142019-01-21 11:33:38 -08004354status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4355 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004356 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004357
Mathias Agopianbd115332013-04-18 16:41:04 -07004358 IPCThreadState* ipc = IPCThreadState::self();
4359 const int pid = ipc->getCallingPid();
4360 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004361
Mathias Agopianbd115332013-04-18 16:41:04 -07004362 if ((uid != AID_SHELL) &&
4363 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4365 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004367 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004368 // (this would indicate SF is stuck, but we want to be able to
4369 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004370 status_t err = mStateLock.timedLock(s2ns(1));
4371 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004372 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 StringAppendF(&result,
4374 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4375 "(no locks held)\n",
4376 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004377 }
4378
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004380
Dominik Laskowskic2867142019-01-21 11:33:38 -08004381 static const std::unordered_map<std::string, Dumper> dumpers = {
4382 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4383 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4384 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004385 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004386 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004387 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004388 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4389 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4391 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4392 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4393 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4394 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4395 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004396 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4398 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004401
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4403 (it->second)(args, asProto, result);
4404 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004405 if (asProto) {
4406 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4407 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4408 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004410 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004411 }
4412
Mathias Agopian9795c422009-08-26 16:36:26 -07004413 if (locked) {
4414 mStateLock.unlock();
4415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004417 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004418 return NO_ERROR;
4419}
4420
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004421status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4422 if (asProto && mTracing.isEnabled()) {
4423 mTracing.writeToFileAsync();
4424 }
4425
4426 return doDump(fd, DumpArgs(), asProto);
4427}
4428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004430 mCurrentState.traverseInZOrder(
4431 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004432}
4433
Dominik Laskowskic2867142019-01-21 11:33:38 -08004434void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004435 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 if (args.size() > 1) {
4438 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004439 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004440 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004441 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004442 }
Robert Carr2047fae2016-11-28 14:09:09 -08004443 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444 } else {
4445 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446 }
4447}
4448
Dominik Laskowskic2867142019-01-21 11:33:38 -08004449void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004450 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004452 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453 }
Robert Carr2047fae2016-11-28 14:09:09 -08004454 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004455
Svetoslavd85084b2014-03-20 10:28:31 -07004456 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004457}
4458
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4460 mTimeStats->parseArgs(asProto, args, result);
4461}
4462
Jamie Gennis6547ff42013-07-16 20:12:42 -07004463// This should only be called from the main thread. Otherwise it would need
4464// the lock and should use mCurrentState rather than mDrawingState.
4465void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004466 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004467 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004468 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004469
4470 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4471}
4472
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004474 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004475
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004476 if (isLayerTripleBufferingDisabled())
4477 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004478
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4480 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4481 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4482 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4483 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4484 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004485 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004486}
4487
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004488void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004489 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004490 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004491 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004492 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004493
Ady Abraham97d04232019-03-05 19:48:12 -08004494 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004495 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4496 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004497 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4501 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004502 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4503 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004504 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004505 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004507 }
David Sodman4a36e932017-11-07 14:29:47 -08004508 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004509 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004510 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4512 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004513}
4514
Dan Stozae77c7662016-05-13 11:37:28 -07004515void SurfaceFlinger::recordBufferingStats(const char* layerName,
4516 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004517 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4518 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004519 for (const auto& segment : history) {
4520 if (!segment.usedThirdBuffer) {
4521 stats.twoBufferTime += segment.totalTime;
4522 }
4523 if (segment.occupancyAverage < 1.0f) {
4524 stats.doubleBufferedTime += segment.totalTime;
4525 } else if (segment.occupancyAverage < 2.0f) {
4526 stats.tripleBufferedTime += segment.totalTime;
4527 }
4528 ++stats.numSegments;
4529 stats.totalTime += segment.totalTime;
4530 }
4531}
4532
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4534 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004535
4536 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4537 const size_t count = currentLayers.size();
4538 for (size_t i=0 ; i<count ; i++) {
4539 currentLayers[i]->dumpFrameEvents(result);
4540 }
4541}
4542
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004544 result.append("Buffering stats:\n");
4545 result.append(" [Layer name] <Active time> <Two buffer> "
4546 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004547 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004548 typedef std::tuple<std::string, float, float, float> BufferTuple;
4549 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004550 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004551 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004552 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004553 if (stats.numSegments == 0) {
4554 continue;
4555 }
4556 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4557 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4558 stats.totalTime;
4559 float doubleBufferRatio = static_cast<float>(
4560 stats.doubleBufferedTime) / stats.totalTime;
4561 float tripleBufferRatio = static_cast<float>(
4562 stats.tripleBufferedTime) / stats.totalTime;
4563 sorted.insert({activeTime, {name, twoBufferRatio,
4564 doubleBufferRatio, tripleBufferRatio}});
4565 }
4566 for (const auto& sortedPair : sorted) {
4567 float activeTime = sortedPair.first;
4568 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4570 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004571 }
4572 result.append("\n");
4573}
4574
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004576 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004577 const auto displayId = display->getId();
4578 if (!displayId) {
4579 continue;
4580 }
4581 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004582 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004583 continue;
4584 }
4585
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586 StringAppendF(&result,
4587 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4588 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004589 uint8_t port;
4590 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004591 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 result.append("no identification data\n");
4593 continue;
4594 }
4595
4596 if (!isEdid(data)) {
4597 result.append("unknown identification data: ");
4598 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004600 }
4601 result.append("\n");
4602 continue;
4603 }
4604
4605 const auto edid = parseEdid(data);
4606 if (!edid) {
4607 result.append("invalid EDID: ");
4608 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004610 }
4611 result.append("\n");
4612 continue;
4613 }
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004616 result.append(edid->displayName.data(), edid->displayName.length());
4617 result.append("\"\n");
4618 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619}
4620
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4622 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4623 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4624 StringAppendF(&result, "DisplayColorSetting: %s\n",
4625 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004626
4627 // TODO: print out if wide-color mode is active or not
4628
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004629 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004630 const auto displayId = display->getId();
4631 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004632 continue;
4633 }
4634
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004636 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004637 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004639 }
4640
Lloyd Pique32cbe282018-10-19 13:09:22 -07004641 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, " Current color mode: %s (%d)\n",
4643 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004644 }
4645 result.append("\n");
4646}
4647
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004648LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4649 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004650 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004651 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4652 const State& state = useDrawing ? mDrawingState : mCurrentState;
4653 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004654 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004655 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004656 });
4657
4658 return layersProto;
4659}
4660
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4662 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004663 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004664
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004665 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004666 resolution->set_w(displayDevice->getWidth());
4667 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004668
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004669 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004670 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004671
Lloyd Pique32cbe282018-10-19 13:09:22 -07004672 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4673 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4674 layersProto.set_global_transform(displayState.orientation);
4675
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004676 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004677 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004679 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004680 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004681 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004682 }
4683 });
4684
4685 return layersProto;
4686}
4687
Dominik Laskowskic2867142019-01-21 11:33:38 -08004688void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4689 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 Colorizer colorizer(colorize);
4691
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 // figure out if we're stuck somewhere
4693 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4696
4697 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004698 * Dump library configuration.
4699 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700
4701 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004702 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004704 appendSfConfigString(result);
4705 appendUiConfigString(result);
4706 appendGuiConfigString(result);
4707 result.append("\n");
4708
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004709 result.append("\nDisplay identification data:\n");
4710 dumpDisplayIdentificationData(result);
4711
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004712 result.append("\nWide-Color information:\n");
4713 dumpWideColorInfo(result);
4714
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004715 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004716 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004718 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004719 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004720
Andy McFadden41d67d72014-04-25 16:58:34 -07004721 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004722 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004723 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004724 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004725 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004726
Dan Stozab90cf072015-03-05 11:05:59 -08004727 dumpStaticScreenStats(result);
4728 result.append("\n");
4729
Alec Mouri40189b02019-03-05 15:07:54 -08004730 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4731 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4732 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004733
Dan Stozae77c7662016-05-13 11:37:28 -07004734 dumpBufferingStats(result);
4735
Andy McFadden4803b742012-09-24 19:07:20 -07004736 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737 * Dump the visible layer list
4738 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4741 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4742 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004743 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004744
Chia-I Wu2f884132018-09-13 15:17:58 -07004745 {
4746 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4747 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004749 result.append("\n");
4750 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751
Lloyd Pique207def92019-02-28 16:09:52 -08004752 {
4753 StringAppendF(&result, "Composition layers\n");
4754 mDrawingState.traverseInZOrder([&](Layer* layer) {
4755 auto compositionLayer = layer->getCompositionLayer();
4756 if (compositionLayer) compositionLayer->dump(result);
4757 });
4758 }
4759
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004760 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004761 * Dump Display state
4762 */
4763
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004764 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004767 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004768 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004769 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004770 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004771
4772 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773 * Dump SurfaceFlinger global state
4774 */
4775
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004777 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004778 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004779
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004780 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781
Dominik Laskowski075d3172018-05-24 15:50:06 -07004782 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004783 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4784 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4786 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004787 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result,
4789 " transaction-flags : %08x\n"
4790 " gpu_to_cpu_unsupported : %d\n",
4791 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004792
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004793 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004794 displayId && getHwComposer().isConnected(*displayId)) {
4795 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result,
4797 " refresh-rate : %f fps\n"
4798 " x-dpi : %f\n"
4799 " y-dpi : %f\n",
4800 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4801 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004802 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805
Dan Stozae22aec72016-08-01 13:20:59 -07004806 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004807 * Tracing state
4808 */
4809 mTracing.dump(result);
4810 result.append("\n");
4811
4812 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004813 * HWC layer minidump
4814 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004815 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004816 const auto displayId = display->getId();
4817 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004818 continue;
4819 }
4820
Yiwei Zhang5434a782018-12-05 18:06:32 -08004821 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004822 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004823 const sp<DisplayDevice> displayDevice = display;
4824 mCurrentState.traverseInZOrder(
4825 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004826 result.append("\n");
4827 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004828
4829 /*
4830 * Dump HWComposer state
4831 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004832 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004833 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004835 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004838
4839 /*
4840 * Dump gralloc state
4841 */
4842 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4843 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004844
4845 /*
4846 * Dump VrFlinger state if in use.
4847 */
4848 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4849 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004850 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004851 result.append("\n");
4852 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004853
4854 /**
4855 * Scheduler dump state.
4856 */
Ana Krulecc2870422019-01-29 19:00:58 -08004857 result.append("\nScheduler state:\n");
4858 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004859 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004860 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861}
4862
Dominik Laskowski075d3172018-05-24 15:50:06 -07004863const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004864 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004865 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004866 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004867 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004868 }
4869 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004870
Dominik Laskowski34157762018-10-31 13:07:19 -07004871 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004872 static const Vector<sp<Layer>> empty;
4873 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004874}
4875
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876void SurfaceFlinger::updateColorMatrixLocked() {
4877 mat4 colorMatrix;
4878 if (mGlobalSaturationFactor != 1.0f) {
4879 // Rec.709 luma coefficients
4880 float3 luminance{0.213f, 0.715f, 0.072f};
4881 luminance *= 1.0f - mGlobalSaturationFactor;
4882 mat4 saturationMatrix = mat4(
4883 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4884 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4885 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4886 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4887 );
4888 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4889 } else {
4890 colorMatrix = mClientColorMatrix * mDaltonizer();
4891 }
4892
4893 if (mCurrentState.colorMatrix != colorMatrix) {
4894 mCurrentState.colorMatrix = colorMatrix;
4895 mCurrentState.colorMatrixChanged = true;
4896 setTransactionFlags(eTransactionNeeded);
4897 }
4898}
4899
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004900status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901#pragma clang diagnostic push
4902#pragma clang diagnostic error "-Wswitch-enum"
4903 switch (static_cast<ISurfaceComposerTag>(code)) {
4904 // These methods should at minimum make sure that the client requested
4905 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004906 case BOOT_FINISHED:
4907 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 case CREATE_DISPLAY:
4909 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004910 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911 case GET_ANIMATION_FRAME_STATS:
4912 case GET_HDR_CAPABILITIES:
4913 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004914 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004915 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004917 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004918 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004919 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004920 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4921 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004922 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4923 IPCThreadState* ipc = IPCThreadState::self();
4924 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4925 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004926 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927 }
Robert Carr1db73f62016-12-21 12:58:51 -08004928 return OK;
4929 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004930 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004931 IPCThreadState* ipc = IPCThreadState::self();
4932 const int pid = ipc->getCallingPid();
4933 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4935 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004936 return PERMISSION_DENIED;
4937 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004938 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 // Used by apps to hook Choreographer to SurfaceFlinger.
4941 case CREATE_DISPLAY_EVENT_CONNECTION:
4942 // The following calls are currently used by clients that do not
4943 // request necessary permissions. However, they do not expose any secret
4944 // information, so it is OK to pass them.
4945 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004946 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004948 case GET_PHYSICAL_DISPLAY_IDS:
4949 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004950 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004951 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 case GET_DISPLAY_CONFIGS:
4953 case GET_DISPLAY_STATS:
4954 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4955 // Calling setTransactionState is safe, because you need to have been
4956 // granted a reference to Client* and Handle* to do anything with it.
4957 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004958 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004959 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004960 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004961 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004962 case IS_WIDE_COLOR_DISPLAY:
4963 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4964 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004965 return OK;
4966 }
4967 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004968 case CAPTURE_SCREEN:
4969 case ADD_REGION_SAMPLING_LISTENER:
4970 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004972 IPCThreadState* ipc = IPCThreadState::self();
4973 const int pid = ipc->getCallingPid();
4974 const int uid = ipc->getCallingUid();
4975 if ((uid != AID_GRAPHICS) &&
4976 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4977 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4978 return PERMISSION_DENIED;
4979 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980 return OK;
4981 }
4982 // The following codes are deprecated and should never be allowed to access SF.
4983 case CONNECT_DISPLAY_UNUSED:
4984 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4985 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4986 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004987 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004988 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004989
4990 // These codes are used for the IBinder protocol to either interrogate the recipient
4991 // side of the transaction for its canonical interface descriptor or to dump its state.
4992 // We let them pass by default.
4993 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4994 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4995 code == IBinder::SYSPROPS_TRANSACTION) {
4996 return OK;
4997 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004998 // Numbers from 1000 to 1033 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004999 // in onTransact verifies that the user is root, and has access to use SF.
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005000 if (code >= 1000 && code <= 1033) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5002 return OK;
5003 }
5004 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5005 return PERMISSION_DENIED;
5006#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005007}
5008
Ana Krulec13be8ad2018-08-21 02:43:56 +00005009status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5010 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005011 status_t credentialCheck = CheckTransactCodeCredentials(code);
5012 if (credentialCheck != OK) {
5013 return credentialCheck;
5014 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005015
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5017 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005018 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005019 IPCThreadState* ipc = IPCThreadState::self();
5020 const int uid = ipc->getCallingUid();
5021 if (CC_UNLIKELY(uid != AID_SYSTEM
5022 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005023 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005024 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005025 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005026 return PERMISSION_DENIED;
5027 }
5028 int n;
5029 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005030 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005031 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005032 return NO_ERROR;
5033 case 1002: // SHOW_UPDATES
5034 n = data.readInt32();
5035 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005036 invalidateHwcGeometry();
5037 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005040 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005041 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005043 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005044 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005045 setTransactionFlags(
5046 eTransactionNeeded|
5047 eDisplayTransactionNeeded|
5048 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005049 return NO_ERROR;
5050 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005051 case 1006:{ // send empty update
5052 signalRefresh();
5053 return NO_ERROR;
5054 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005055 case 1008: // toggle use of hw composer
5056 n = data.readInt32();
5057 mDebugDisableHWC = n ? 1 : 0;
5058 invalidateHwcGeometry();
5059 repaintEverything();
5060 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005061 case 1009: // toggle use of transform hint
5062 n = data.readInt32();
5063 mDebugDisableTransformHint = n ? 1 : 0;
5064 invalidateHwcGeometry();
5065 repaintEverything();
5066 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005067 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005068 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005069 reply->writeInt32(0);
5070 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005071 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005072 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005073 return NO_ERROR;
5074 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005075 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005076 if (!display) {
5077 return NAME_NOT_FOUND;
5078 }
5079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005080 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005081 return NO_ERROR;
5082 }
5083 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005085 // daltonize
5086 n = data.readInt32();
5087 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005088 case 1:
5089 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5090 break;
5091 case 2:
5092 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5093 break;
5094 case 3:
5095 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5096 break;
5097 default:
5098 mDaltonizer.setType(ColorBlindnessType::None);
5099 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005100 }
5101 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005102 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005103 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005104 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005105 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005106
5107 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005108 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005109 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005111 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005112 // apply a color matrix
5113 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005114 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005115 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005116 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005117 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005118 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005119 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005120 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005121 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005122 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005123 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005124
5125 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5126 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005128 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5129 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5130 }
5131
Chia-I Wu28f320b2018-05-03 11:02:56 -07005132 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005133 return NO_ERROR;
5134 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005135 // This is an experimental interface
5136 // Needs to be shifted to proper binder interface when we productize
5137 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005138 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005139 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005140 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005141 return NO_ERROR;
5142 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005143 case 1017: {
5144 n = data.readInt32();
5145 mForceFullDamage = static_cast<bool>(n);
5146 return NO_ERROR;
5147 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005148 case 1018: { // Modify Choreographer's phase offset
5149 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005150 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005151 return NO_ERROR;
5152 }
5153 case 1019: { // Modify SurfaceFlinger's phase offset
5154 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005155 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005156 return NO_ERROR;
5157 }
Irvel468051e2016-06-13 16:44:44 -07005158 case 1020: { // Layer updates interceptor
5159 n = data.readInt32();
5160 if (n) {
5161 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005162 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005163 }
5164 else{
5165 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005166 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005167 }
5168 return NO_ERROR;
5169 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005170 case 1021: { // Disable HWC virtual displays
5171 n = data.readInt32();
5172 mUseHwcVirtualDisplays = !n;
5173 return NO_ERROR;
5174 }
Romain Guy0147a172017-06-01 13:53:56 -07005175 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005176 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005177 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005178
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005180 return NO_ERROR;
5181 }
Romain Guy54f154a2017-10-24 21:40:32 +01005182 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005183 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005184 invalidateHwcGeometry();
5185 repaintEverything();
5186 return NO_ERROR;
5187 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005188 // Deprecate, use 1030 to check whether the device is color managed.
5189 case 1024: {
5190 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005191 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005192 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005193 n = data.readInt32();
5194 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005195 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005196 Mutex::Autolock lock(mStateLock);
5197 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005198 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005199 reply->writeInt32(NO_ERROR);
5200 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005201 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005202 bool writeFile = false;
5203 {
5204 Mutex::Autolock lock(mStateLock);
5205 mTracingEnabledChanged = true;
5206 writeFile = mTracing.disable();
5207 }
5208
5209 if (writeFile) {
5210 reply->writeInt32(mTracing.writeToFile());
5211 } else {
5212 reply->writeInt32(NO_ERROR);
5213 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005214 }
5215 return NO_ERROR;
5216 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005217 case 1026: { // Get layer tracing status
5218 reply->writeBool(mTracing.isEnabled());
5219 return NO_ERROR;
5220 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005221 // Is a DisplayColorSetting supported?
5222 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005223 const auto display = getDefaultDisplayDevice();
5224 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005225 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005227
5228 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5229 switch (setting) {
5230 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005231 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005232 break;
5233 case DisplayColorSetting::UNMANAGED:
5234 reply->writeBool(true);
5235 break;
5236 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005238 break;
5239 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005240 reply->writeBool(
5241 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005242 break;
5243 }
5244 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005245 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005246 // Is VrFlinger active?
5247 case 1028: {
5248 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005249 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005250 return NO_ERROR;
5251 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005252 // Set buffer size for SF tracing (value in KB)
5253 case 1029: {
5254 n = data.readInt32();
5255 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5256 ALOGW("Invalid buffer size: %d KB", n);
5257 reply->writeInt32(BAD_VALUE);
5258 return BAD_VALUE;
5259 }
5260
5261 ALOGD("Updating trace buffer to %d KB", n);
5262 mTracing.setBufferSize(n * 1024);
5263 reply->writeInt32(NO_ERROR);
5264 return NO_ERROR;
5265 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005266 // Is device color managed?
5267 case 1030: {
5268 reply->writeBool(useColorManagement);
5269 return NO_ERROR;
5270 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005271 // Override default composition data space
5272 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5273 // && adb shell stop zygote && adb shell start zygote
5274 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5275 // adb shell stop zygote && adb shell start zygote
5276 case 1031: {
5277 Mutex::Autolock _l(mStateLock);
5278 n = data.readInt32();
5279 if (n) {
5280 n = data.readInt32();
5281 if (n) {
5282 Dataspace dataspace = static_cast<Dataspace>(n);
5283 if (!validateCompositionDataspace(dataspace)) {
5284 return BAD_VALUE;
5285 }
5286 mDefaultCompositionDataspace = dataspace;
5287 }
5288 n = data.readInt32();
5289 if (n) {
5290 Dataspace dataspace = static_cast<Dataspace>(n);
5291 if (!validateCompositionDataspace(dataspace)) {
5292 return BAD_VALUE;
5293 }
5294 mWideColorGamutCompositionDataspace = dataspace;
5295 }
5296 } else {
5297 // restore composition data space.
5298 mDefaultCompositionDataspace = defaultCompositionDataspace;
5299 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5300 }
5301 return NO_ERROR;
5302 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005303 case 1032: {
5304 n = data.readInt32();
5305 mDebugEnableProtectedContent = n;
5306 return NO_ERROR;
5307 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005308 // Set trace flags
5309 case 1033: {
5310 n = data.readUint32();
5311 ALOGD("Updating trace flags to 0x%x", n);
5312 mTracing.setTraceFlags(n);
5313 reply->writeInt32(NO_ERROR);
5314 return NO_ERROR;
5315 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005316 }
5317 }
5318 return err;
5319}
5320
Steven Thomas6d8110b2017-08-31 18:24:21 -07005321void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005322 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005323 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005324}
5325
Ana Krulec7d1d6832018-12-27 11:10:09 -08005326void SurfaceFlinger::repaintEverythingForHWC() {
5327 mRepaintEverything = true;
5328 mEventQueue->invalidateForHWC();
5329}
5330
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005331// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5332class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005333public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5335 ~WindowDisconnector() {
5336 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005337 }
5338
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005339private:
5340 ANativeWindow* mWindow;
5341 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005342};
5343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005344status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005345 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5346 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005347 uint32_t reqWidth, uint32_t reqHeight,
5348 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005349 ISurfaceComposer::Rotation rotation,
5350 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005351 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005352
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005353 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005354
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005355 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5356
Chia-I Wu20261cb2018-08-23 12:55:44 -07005357 sp<DisplayDevice> display;
5358 {
5359 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005360
Chia-I Wu20261cb2018-08-23 12:55:44 -07005361 display = getDisplayDeviceLocked(displayToken);
5362 if (!display) return BAD_VALUE;
5363
Chia-I Wucb023152018-08-28 12:57:23 -07005364 // set the requested width/height to the logical display viewport size
5365 // by default
5366 if (reqWidth == 0 || reqHeight == 0) {
5367 reqWidth = uint32_t(display->getViewport().width());
5368 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005369 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005370 }
5371
Peiyong Lin0e003c92018-09-17 11:09:51 -07005372 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005373 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005374
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005375 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5376 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005377 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5378 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005379}
5380
5381status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005382 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5383 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005384 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005385 ATRACE_CALL();
5386
5387 class LayerRenderArea : public RenderArea {
5388 public:
Robert Carr578038f2018-03-09 12:25:24 -08005389 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005390 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5391 bool childrenOnly)
5392 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005393 mLayer(layer),
5394 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005395 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005396 mFlinger(flinger),
5397 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005398 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005399 Rect getBounds() const override {
5400 const Layer::State& layerState(mLayer->getDrawingState());
5401 return mLayer->getBufferSize(layerState);
5402 }
Marissa Wall61c58622018-07-18 10:12:20 -07005403 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005404 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005405 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005406 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005407 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005408 }
chaviwa76b2712017-09-20 12:02:26 -07005409 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005410 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005411 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005412 Rect getSourceCrop() const override {
5413 if (mCrop.isEmpty()) {
5414 return getBounds();
5415 } else {
5416 return mCrop;
5417 }
5418 }
Robert Carr578038f2018-03-09 12:25:24 -08005419 class ReparentForDrawing {
5420 public:
5421 const sp<Layer>& oldParent;
5422 const sp<Layer>& newParent;
5423
Vishnu Nair4351ad52019-02-11 14:13:02 -08005424 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5425 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005426 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005427 // Compute and cache the bounds for the new parent layer.
5428 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005429 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005430 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005431 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005432 };
5433
5434 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005435 const Rect sourceCrop = getSourceCrop();
5436 // no need to check rotation because there is none
5437 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5438 sourceCrop.height() != getReqHeight();
5439
Robert Carr578038f2018-03-09 12:25:24 -08005440 if (!mChildrenOnly) {
5441 mTransform = mLayer->getTransform().inverse();
5442 drawLayers();
5443 } else {
5444 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005445 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005446 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005447 bounds.getWidth(), bounds.getHeight(), 0,
5448 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005449
Vishnu Nair4351ad52019-02-11 14:13:02 -08005450 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005451 drawLayers();
5452 }
5453 }
chaviwa76b2712017-09-20 12:02:26 -07005454
chaviwa76b2712017-09-20 12:02:26 -07005455 private:
chaviw7206d492017-11-10 16:16:12 -08005456 const sp<Layer> mLayer;
5457 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005458
5459 // In the "childrenOnly" case we reparent the children to a screenshot
5460 // layer which has no properties set and which does not draw.
5461 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005462 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005463 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005464
5465 SurfaceFlinger* mFlinger;
5466 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005467 };
5468
5469 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5470 auto parent = layerHandle->owner.promote();
5471
Robert Carr2e102c92018-10-23 12:11:15 -07005472 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005473 ALOGE("captureLayers called with a removed parent");
5474 return NAME_NOT_FOUND;
5475 }
5476
Robert Carr578038f2018-03-09 12:25:24 -08005477 const int uid = IPCThreadState::self()->getCallingUid();
5478 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005479 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005480 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5481 return PERMISSION_DENIED;
5482 }
5483
chaviw7206d492017-11-10 16:16:12 -08005484 Rect crop(sourceCrop);
5485 if (sourceCrop.width() <= 0) {
5486 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005487 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005488 }
5489
5490 if (sourceCrop.height() <= 0) {
5491 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005492 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005493 }
5494
5495 int32_t reqWidth = crop.width() * frameScale;
5496 int32_t reqHeight = crop.height() * frameScale;
5497
Chia-I Wu20261cb2018-08-23 12:55:44 -07005498 // really small crop or frameScale
5499 if (reqWidth <= 0) {
5500 reqWidth = 1;
5501 }
5502 if (reqHeight <= 0) {
5503 reqHeight = 1;
5504 }
5505
Peiyong Lin0e003c92018-09-17 11:09:51 -07005506 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005507
Robert Carr578038f2018-03-09 12:25:24 -08005508 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005509 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5510 if (!layer->isVisible()) {
5511 return;
Robert Carr578038f2018-03-09 12:25:24 -08005512 } else if (childrenOnly && layer == parent.get()) {
5513 return;
chaviwa76b2712017-09-20 12:02:26 -07005514 }
5515 visitor(layer);
5516 });
5517 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005518 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005519}
5520
5521status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5522 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005523 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005524 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005525 bool useIdentityTransform) {
5526 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005527
Peiyong Lin0e003c92018-09-17 11:09:51 -07005528 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005529 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5530 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005531 *outBuffer =
5532 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5533 static_cast<android_pixel_format>(reqPixelFormat), 1,
5534 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005536 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005537}
5538
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005539status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5540 TraverseLayersFunction traverseLayers,
5541 const sp<GraphicBuffer>& buffer,
5542 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005543 // This mutex protects syncFd and captureResult for communication of the return values from the
5544 // main thread back to this Binder thread
5545 std::mutex captureMutex;
5546 std::condition_variable captureCondition;
5547 std::unique_lock<std::mutex> captureLock(captureMutex);
5548 int syncFd = -1;
5549 std::optional<status_t> captureResult;
5550
Robert Carr03480e22018-01-04 16:02:06 -08005551 const int uid = IPCThreadState::self()->getCallingUid();
5552 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5553
Dominik Laskowski8c001672018-05-30 16:52:06 -07005554 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005555 // If there is a refresh pending, bug out early and tell the binder thread to try again
5556 // after the refresh.
5557 if (mRefreshPending) {
5558 ATRACE_NAME("Skipping screenshot for now");
5559 std::unique_lock<std::mutex> captureLock(captureMutex);
5560 captureResult = std::make_optional<status_t>(EAGAIN);
5561 captureCondition.notify_one();
5562 return;
5563 }
5564
5565 status_t result = NO_ERROR;
5566 int fd = -1;
5567 {
5568 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005569 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005570 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005571 useIdentityTransform, forSystem, &fd);
5572 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005573 }
5574
5575 {
5576 std::unique_lock<std::mutex> captureLock(captureMutex);
5577 syncFd = fd;
5578 captureResult = std::make_optional<status_t>(result);
5579 captureCondition.notify_one();
5580 }
5581 });
5582
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005583 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005585 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005586 while (*captureResult == EAGAIN) {
5587 captureResult.reset();
5588 result = postMessageAsync(message);
5589 if (result != NO_ERROR) {
5590 return result;
5591 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005592 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 }
5594 result = *captureResult;
5595 }
5596
5597 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005598 sync_wait(syncFd, -1);
5599 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005602 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005603}
5604
chaviwa76b2712017-09-20 12:02:26 -07005605void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005606 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005607 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5608 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005609 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005610
chaviwa76b2712017-09-20 12:02:26 -07005611 const auto reqWidth = renderArea.getReqWidth();
5612 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005613 const auto sourceCrop = renderArea.getSourceCrop();
5614 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005615
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005616 renderengine::DisplaySettings clientCompositionDisplay;
5617 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005618
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005619 // assume that bounds are never offset, and that they are the same as the
5620 // buffer bounds.
5621 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5622 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005623 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005624 mat4 rotMatrix;
5625 // Displacement for repositioning the clipping rectangle after rotating it
5626 // with the rotation hint.
5627 int displacementX = 0;
5628 int displacementY = 0;
5629 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5630 switch (rotation) {
5631 case ui::Transform::ROT_90:
5632 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5633 displacementX = reqWidth;
5634 break;
5635 case ui::Transform::ROT_180:
5636 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5637 displacementX = reqWidth;
5638 displacementY = reqHeight;
5639 break;
5640 case ui::Transform::ROT_270:
5641 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5642 displacementY = reqHeight;
5643 break;
5644 default:
5645 break;
5646 }
5647 // We need to transform the clipping window into the right spot.
5648 // First, rotate the clipping rectangle by the rotation hint to get the
5649 // right orientation
5650 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5651 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5652 const vec4 rotClipTL = rotMatrix * clipTL;
5653 const vec4 rotClipBR = rotMatrix * clipBR;
5654 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5655 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5656 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5657 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5658
5659 // Now reposition the clipping rectangle with the displacement vector
5660 // computed above.
5661 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5662
5663 clientCompositionDisplay.clip =
5664 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5665 newClipRight + displacementX, newClipBottom + displacementY);
5666
5667 // We need to perform the same transformation in layer space, so propagate
5668 // it to the global transform.
5669 mat4 clipTransform = displacementMat * rotMatrix;
5670 clientCompositionDisplay.globalTransform *= clipTransform;
5671 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5672 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005673
chaviw50da5042018-04-09 13:49:37 -07005674 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005675
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005676 renderengine::LayerSettings fillLayer;
5677 fillLayer.source.buffer.buffer = nullptr;
5678 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5679 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5680 fillLayer.alpha = half(alpha);
5681 clientCompositionLayers.push_back(fillLayer);
5682
5683 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005684 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005685 renderengine::LayerSettings layerSettings;
5686 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005687 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005688 if (prepared) {
5689 clientCompositionLayers.push_back(layerSettings);
5690 }
chaviwa76b2712017-09-20 12:02:26 -07005691 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005692
5693 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005694 // Use an empty fence for the buffer fence, since we just created the buffer so
5695 // there is no need for synchronization with the GPU.
5696 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005697 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005698 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005700 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005701
5702 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005703}
5704
chaviwa76b2712017-09-20 12:02:26 -07005705status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5706 TraverseLayersFunction traverseLayers,
5707 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005708 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005709 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005710 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005711 ATRACE_CALL();
5712
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005713 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005714
5715 traverseLayers([&](Layer* layer) {
5716 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5717 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005718
Robert Carr03480e22018-01-04 16:02:06 -08005719 // We allow the system server to take screenshots of secure layers for
5720 // use in situations like the Screen-rotation animation and place
5721 // the impetus on WindowManager to not persist them.
5722 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005723 ALOGW("FB is protected: PERMISSION_DENIED");
5724 return PERMISSION_DENIED;
5725 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005726 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005727 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005728}
5729
chaviw95ef3c42019-02-14 10:55:09 -08005730void SurfaceFlinger::setInputWindowsFinished() {
5731 Mutex::Autolock _l(mStateLock);
5732
5733 mPendingSyncInputWindows = false;
5734 mTransactionCV.broadcast();
5735}
chaviw5f21a5e2019-02-14 10:00:34 -08005736
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005737// ---------------------------------------------------------------------------
5738
Dan Stoza412903f2017-04-27 13:42:17 -07005739void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5740 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005741}
5742
Dan Stoza412903f2017-04-27 13:42:17 -07005743void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5744 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005745}
5746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005747void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005748 const LayerVector::Visitor& visitor) {
5749 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005750 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005751 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005752 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005753 continue;
5754 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005755 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005756 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005757 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005758 return;
5759 }
chaviwa76b2712017-09-20 12:02:26 -07005760 if (!layer->isVisible()) {
5761 return;
5762 }
5763 visitor(layer);
5764 });
5765 }
5766}
5767
Ady Abraham838de062019-02-04 10:24:03 -08005768void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5769 const android::sp<android::IBinder>& displayToken,
5770 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5771 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5772 if (!displayId) {
5773 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5774 return;
5775 }
5776
5777 ALOGV("Updating allowed configs");
5778 {
5779 std::lock_guard lock(mAllowedConfigsLock);
5780 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5781 }
5782
5783 // make sure that the current config is still allowed
5784 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5785 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005786 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
5787 if (isConfigAllowed(*displayId, config.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005788 // TODO: we switch to the first allowed config. In the future
5789 // we may want to enhance this logic to pick a similar config
5790 // to the current one
Ady Abraham1902d072019-03-01 17:18:59 -08005791 ALOGV("Old config is not allowed - switching to config %d", config.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005792 setDesiredActiveConfig(displayToken, config.configId,
5793 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005794 break;
5795 }
5796 }
5797 }
Ady Abraham97d04232019-03-05 19:48:12 -08005798
5799 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5800 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5801 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
5802 const auto performanceRefreshRate =
5803 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
5804 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ady Abraham97d04232019-03-05 19:48:12 -08005805 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5806 }
5807 }
Ady Abraham838de062019-02-04 10:24:03 -08005808}
5809
5810status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5811 const std::vector<int32_t>& allowedConfigs) {
5812 ATRACE_CALL();
5813
5814 if (!displayToken) {
5815 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5816 return BAD_VALUE;
5817 }
5818
5819 if (!allowedConfigs.size()) {
5820 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5821 return BAD_VALUE;
5822 }
5823
5824 {
5825 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5826 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5827 if (!displayId) {
5828 ALOGE("setAllowedDisplayConfigs: display not found");
5829 return NAME_NOT_FOUND;
5830 }
5831 }
5832
5833 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5834 for (int config : allowedConfigs) {
5835 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5836 allowedDisplayConfigsBuilder.addConfig(config);
5837 }
5838 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5839 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5840 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5841 }));
5842 return NO_ERROR;
5843}
5844
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005845status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5846 std::vector<int32_t>* outAllowedConfigs) {
5847 ATRACE_CALL();
5848
5849 if (!displayToken) {
5850 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5851 return BAD_VALUE;
5852 }
5853
5854 if (!outAllowedConfigs) {
5855 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5856 return BAD_VALUE;
5857 }
5858
5859 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5860 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5861 if (!displayId) {
5862 ALOGE("getAllowedDisplayConfigs: display not found");
5863 return NAME_NOT_FOUND;
5864 }
5865
5866 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5867 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5868 if (allowedConfigIterator != mAllowedConfigs.end()) {
5869 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5870 }
5871
5872 return NO_ERROR;
5873}
5874
chaviw291d88a2019-02-14 10:33:58 -08005875// ----------------------------------------------------------------------------
5876
5877void SetInputWindowsListener::onSetInputWindowsFinished() {
5878 mFlinger->setInputWindowsFinished();
5879}
5880
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005881}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005882
Lloyd Pique074e8122018-07-26 12:57:23 -07005883
Mathias Agopian3f844832013-08-07 21:24:32 -07005884#if defined(__gl_h_)
5885#error "don't include gl/gl.h in this file"
5886#endif
5887
5888#if defined(__gl2_h_)
5889#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005890#endif