blob: fa2233bb898bde1a77b5c0e7df7cecca09c4817e [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>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
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 Krulecc2870422019-01-29 19:00:58 -0800396 property_get("debug.sf.use_90Hz", value, "0");
397 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800398
Ana Krulec757f63a2019-01-25 10:46:18 -0800399 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
400 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700401
Romain Guy11d63f42017-07-20 12:47:14 -0700402 // We should be reading 'persist.sys.sf.color_saturation' here
403 // but since /data may be encrypted, we need to wait until after vold
404 // comes online to attempt to read the property. The property is
405 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800406
407 if (useTrebleTestingOverride()) {
408 // Without the override SurfaceFlinger cannot connect to HIDL
409 // services that are not listed in the manifests. Considered
410 // deriving the setting from the set service name, but it
411 // would be brittle if the name that's not 'default' is used
412 // for production purposes later on.
413 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422SurfaceFlinger::~SurfaceFlinger()
423{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Dan Stozac7014012014-02-14 15:03:43 -0800426void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427{
428 // the window manager died on us. prepare its eulogy.
429
Andy McFadden13a082e2012-08-24 10:16:42 -0700430 // restore initial conditions (default device unblank, etc)
431 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432
433 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
Robert Carr1db73f62016-12-21 12:58:51 -0800437static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700438 status_t err = client->initCheck();
439 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return nullptr;
443}
444
445sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
446 return initClient(new Client(this));
447}
448
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700449sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
450 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451{
452 class DisplayToken : public BBinder {
453 sp<SurfaceFlinger> flinger;
454 virtual ~DisplayToken() {
455 // no more references, this display must be terminated
456 Mutex::Autolock _l(flinger->mStateLock);
457 flinger->mCurrentState.displays.removeItem(this);
458 flinger->setTransactionFlags(eDisplayTransactionNeeded);
459 }
460 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700461 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462 : flinger(flinger) {
463 }
464 };
465
466 sp<BBinder> token = new DisplayToken(this);
467
468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 // Display ID is assigned when virtual display is allocated by HWC.
470 DisplayDeviceState state;
471 state.isSecure = secure;
472 state.displayName = displayName;
473 mCurrentState.displays.add(token, state);
474 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 return token;
476}
477
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700478void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 Mutex::Autolock _l(mStateLock);
480
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
482 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 return;
485 }
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
488 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 ALOGE("destroyDisplay called for non-virtual display");
490 return;
491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 mInterceptor->saveDisplayDeletion(state.sequenceId);
493 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 setTransactionFlags(eDisplayTransactionNeeded);
495}
496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
498 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 const auto internalDisplayId = getInternalDisplayIdLocked();
501 if (!internalDisplayId) {
502 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 }
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 std::vector<PhysicalDisplayId> displayIds;
506 displayIds.reserve(mPhysicalDisplayTokens.size());
507 displayIds.push_back(internalDisplayId->value);
508
509 for (const auto& [id, token] : mPhysicalDisplayTokens) {
510 if (id != *internalDisplayId) {
511 displayIds.push_back(id.value);
512 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800515 return displayIds;
516}
517
518sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
519 Mutex::Autolock lock(mStateLock);
520 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521}
522
Ady Abraham37965d42018-11-01 13:43:32 -0700523status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
524 if (!outGetColorManagement) {
525 return BAD_VALUE;
526 }
527 *outGetColorManagement = useColorManagement;
528 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700529}
530
Lloyd Pique441d5042018-10-18 16:49:51 -0700531HWComposer& SurfaceFlinger::getHwComposer() const {
532 return mCompositionEngine->getHwComposer();
533}
534
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700535renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
536 return mCompositionEngine->getRenderEngine();
537}
538
Lloyd Pique70d91362018-10-18 16:02:55 -0700539compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
540 return *mCompositionEngine.get();
541}
542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543void SurfaceFlinger::bootFinished()
544{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
552 // wait patiently for the window manager death
553 const String16 name("window");
554 sp<IBinder> window(defaultServiceManager()->getService(name));
555 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 }
Robert Carr720e5062018-07-30 17:45:14 -0700558 sp<IBinder> input(defaultServiceManager()->getService(
559 String16("inputflinger")));
560 if (input == nullptr) {
561 ALOGE("Failed to link to input service");
562 } else {
563 mInputFlinger = interface_cast<IInputFlinger>(input);
564 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 if (mVrFlinger) {
567 mVrFlinger->OnBootFinished();
568 }
569
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700571 // formerly we would just kill the process, but we now ask it to exit so it
572 // can choose where to stop the animation.
573 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700574
575 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
576 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
577 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700578
Ana Krulecbd6654b2019-02-15 15:18:15 -0800579 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582
583 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
584 // away and it should be controlled by flipping the switch in setting. The switch in
585 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
586 // The boot must be complete before we can set the active config.
587
588 if (mUse90Hz) {
589 mPhaseOffsets->setRefreshRateType(
590 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
591 setRefreshRateTo(RefreshRateType::PERFORMANCE);
592 } else {
593 mPhaseOffsets->setRefreshRateType(
594 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
595 setRefreshRateTo(RefreshRateType::DEFAULT);
596 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800597 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800598}
599
Dan Stoza436ccf32018-06-21 12:10:12 -0700600uint32_t SurfaceFlinger::getNewTexture() {
601 {
602 std::lock_guard lock(mTexturePoolMutex);
603 if (!mTexturePool.empty()) {
604 uint32_t name = mTexturePool.back();
605 mTexturePool.pop_back();
606 ATRACE_INT("TexturePoolSize", mTexturePool.size());
607 return name;
608 }
609
610 // The pool was too small, so increase it for the future
611 ++mTexturePoolSize;
612 }
613
614 // The pool was empty, so we need to get a new texture name directly using a
615 // blocking call to the main thread
616 uint32_t name = 0;
617 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
618 return name;
619}
620
Mathias Agopian3f844832013-08-07 21:24:32 -0700621void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700622 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700623}
624
Wei Wangf9b05ee2017-07-19 20:59:39 -0700625// Do not call property_set on main thread which will be blocked by init
626// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700628 ALOGI( "SurfaceFlinger's main thread ready to run. "
629 "Initializing graphics H/W...");
630
Ana Krulec757f63a2019-01-25 10:46:18 -0800631 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800635 mScheduler =
636 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
637 auto resyncCallback =
638 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800639
Ana Krulecc2870422019-01-29 19:00:58 -0800640 mAppConnectionHandle =
641 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
642 resyncCallback,
643 impl::EventThread::InterceptVSyncsCallback());
644 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
645 resyncCallback, [this](nsecs_t timestamp) {
646 mInterceptor->saveVSyncEvent(timestamp);
647 });
648
649 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
650 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
651 mSfConnectionHandle.get());
652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700654 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700655 renderEngineFeature |= (useColorManagement ?
656 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700657 renderEngineFeature |= (useContextPriority ?
658 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700659
660 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700661 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700663 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700664
665 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
666 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700667 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
668 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 const auto display = getDefaultDisplayDeviceLocked();
672 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700673 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800675
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 // This callback is called from the vr flinger dispatch thread. We
679 // need to call signalTransaction(), which requires holding
680 // mStateLock when we're not on the main thread. Acquiring
681 // mStateLock from the vr flinger dispatch thread might trigger a
682 // deadlock in surface flinger (see b/66916578), so post a message
683 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
686 mVrFlingerRequestsDisplay = requestDisplay;
687 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
691 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700692 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 .value_or(0),
694 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (!mVrFlinger) {
696 ALOGE("Failed to start vrflinger");
697 }
698 }
699
Mathias Agopian92a979a2012-08-02 18:32:23 -0700700 // initialize our drawing state
701 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700702
Andy McFadden13a082e2012-08-24 10:16:42 -0700703 // set initial conditions (e.g. unblank default device)
704 initializeDisplays();
705
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700706 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700707
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709
710 const bool presentFenceReliable =
711 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
712 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Ana Krulecc2870422019-01-29 19:00:58 -0800718 mScheduler->setExpiredIdleTimerCallback([this] {
719 Mutex::Autolock lock(mStateLock);
720 setRefreshRateTo(RefreshRateType::DEFAULT);
721 });
722 mScheduler->setResetIdleTimerCallback([this] {
723 Mutex::Autolock lock(mStateLock);
724 setRefreshRateTo(RefreshRateType::PERFORMANCE);
725 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800726
Ana Krulecc2870422019-01-29 19:00:58 -0800727 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
728 *display->getId()),
729 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700732}
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700735 Mutex::Autolock _l(mStateLock);
736
Romain Guy11d63f42017-07-20 12:47:14 -0700737 char value[PROPERTY_VALUE_MAX];
738
739 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100743
744 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700745 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800746
747 property_get("persist.sys.sf.color_mode", value, "0");
748 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700749}
750
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800752 // Start boot animation service by setting a property mailbox
753 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756 if (mStartPropertySetThread->join() != NO_ERROR) {
757 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800758 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700762 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800770
Jamie Gennis582270d2011-08-17 18:19:00 -0700771bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800772 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800773 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800774 return authenticateSurfaceTextureLocked(bufferProducer);
775}
776
777bool SurfaceFlinger::authenticateSurfaceTextureLocked(
778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800779 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800780 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800781}
782
Brian Anderson6b376712017-04-04 10:51:39 -0700783status_t SurfaceFlinger::getSupportedFrameTimestamps(
784 std::vector<FrameEvent>* outSupported) const {
785 *outSupported = {
786 FrameEvent::REQUESTED_PRESENT,
787 FrameEvent::ACQUIRE,
788 FrameEvent::LATCH,
789 FrameEvent::FIRST_REFRESH_START,
790 FrameEvent::LAST_REFRESH_START,
791 FrameEvent::GPU_COMPOSITION_DONE,
792 FrameEvent::DEQUEUE_READY,
793 FrameEvent::RELEASE,
794 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 ConditionalLock _l(mStateLock,
796 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700797 if (!getHwComposer().hasCapability(
798 HWC2::Capability::PresentFenceIsNotReliable)) {
799 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
800 }
801 return NO_ERROR;
802}
803
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800804status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
805 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700806 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 return BAD_VALUE;
808 }
809
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800810 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700811 if (!displayId) {
812 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700813 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 // TODO: Not sure if display density should handled by SF any longer
816 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700819 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800820 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 }
823 return density;
824 }
825 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("ro.sf.lcd_density"); }
830 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840 info.w = hwConfig->getWidth();
841 info.h = hwConfig->getHeight();
842 // Default display viewport to display width and height
843 info.viewportW = info.w;
844 info.viewportH = info.h;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 // The density of the device is provided by a build property
848 float density = Density::getBuildDensity() / 160.0f;
849 if (density == 0) {
850 // the build doesn't provide a density -- this is wrong!
851 // use xdpi instead
852 ALOGE("ro.sf.lcd_density must be defined as a build property");
853 density = xdpi / 160.0f;
854 }
855 if (Density::getEmuDensity()) {
856 // if "qemu.sf.lcd_density" is specified, it overrides everything
857 xdpi = ydpi = density = Density::getEmuDensity();
858 density /= 160.0f;
859 }
860 info.density = density;
861
862 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863 const auto display = getDefaultDisplayDeviceLocked();
864 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
866 // This is for screenrecord
867 const Rect viewport = display->getViewport();
868 if (viewport.isValid()) {
869 info.viewportW = uint32_t(viewport.getWidth());
870 info.viewportH = uint32_t(viewport.getHeight());
871 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 } else {
873 // TODO: where should this value come from?
874 static const int TV_DENSITY = 213;
875 info.density = TV_DENSITY / 160.0f;
876 info.orientation = 0;
877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 info.xdpi = xdpi;
880 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800882 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883
Andy McFadden91b2ca82014-06-13 14:04:23 -0700884 // This is how far in advance a buffer must be queued for
885 // presentation at a given time. If you want a buffer to appear
886 // on the screen at time N, you must submit the buffer before
887 // (N - presentationDeadline).
888 //
889 // Normally it's one full refresh period (to give SF a chance to
890 // latch the buffer), but this can be reduced by configuring a
891 // DispSync offset. Any additional delays introduced by the hardware
892 // composer or panel must be accounted for here.
893 //
894 // We add an additional 1ms to allow for processing time and
895 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800896 info.presentationDeadline =
897 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
899 // All non-virtual displays are currently considered secure.
900 info.secure = true;
901
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800902 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700903 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800904 std::swap(info.w, info.h);
905 }
906
Michael Wright28f24d02016-07-12 13:30:53 -0700907 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 }
909
Dan Stoza7f7da322014-05-02 15:26:25 -0700910 return NO_ERROR;
911}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
914 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return BAD_VALUE;
916 }
917
Ana Krulecc2870422019-01-29 19:00:58 -0800918 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
933 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800934
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 // Lock is acquired by setRefreshRateTo.
937 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800938 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
939 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
940 return;
941 }
942
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 // Lock is acquired by setRefreshRateTo.
944 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800945 if (!display) {
946 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
947 displayToken.get());
948 return;
949 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700950 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 ALOGW("Attempt to set active config %d for virtual display", mode);
952 return;
953 }
954 int currentDisplayPowerMode = display->getPowerMode();
955 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
956 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700957 return;
958 }
959
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960 // Don't check against the current mode yet. Worst case we set the desired
961 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 std::lock_guard<std::mutex> lock(mActiveConfigLock);
963 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
964
965 if (!mDesiredActiveConfigChanged) {
966 // This is the first time we set the desired
967 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
968
969 // This will trigger HWC refresh without resetting the idle timer.
970 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972 mDesiredActiveConfigChanged = true;
973 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974}
975
976status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
977 ATRACE_CALL();
978 postMessageSync(new LambdaMessage(
979 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
980 return NO_ERROR;
981}
982
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983void SurfaceFlinger::setActiveConfigInternal() {
984 ATRACE_CALL();
985
986 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800987 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988
989 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
990 display->setActiveConfig(mUpcomingActiveConfig.configId);
991
Ana Krulecc2870422019-01-29 19:00:58 -0800992 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
994}
995
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
997 // we may be in the process of changing the active state
998 if (mWaitForNextInvalidate) {
999 mWaitForNextInvalidate = false;
1000
1001 repaintEverythingForHWC();
1002 // We do not want to give another frame to HWC while we are transitioning.
1003 return true;
1004 }
1005
1006 if (mCheckPendingFence) {
1007 if (mPreviousPresentFence != Fence::NO_FENCE &&
1008 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1009 // fence has not signaled yet. wait for the next invalidate
1010 repaintEverythingForHWC();
1011 return true;
1012 }
1013
1014 // We received the present fence from the HWC, so we assume it successfully updated
1015 // the config, hence we update SF.
1016 mCheckPendingFence = false;
1017 setActiveConfigInternal();
1018 }
1019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 // Store the local variable to release the lock.
1021 ActiveConfigInfo desiredActiveConfig;
1022 {
1023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 if (!mDesiredActiveConfigChanged) {
1025 return false;
1026 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 desiredActiveConfig = mDesiredActiveConfig;
1028 }
1029
1030 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1032 // display is not valid or we are already in the requested mode
1033 // on both cases there is nothing left to do
1034 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1035 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1036 mDesiredActiveConfigChanged = false;
1037 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1038 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040
1041 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1042 mUpcomingActiveConfig = desiredActiveConfig;
1043 const auto displayId = display->getId();
1044 LOG_ALWAYS_FATAL_IF(!displayId);
1045
1046 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1047 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1048
1049 // we need to submit an empty frame to HWC to start the process
1050 mWaitForNextInvalidate = true;
1051 mCheckPendingFence = true;
1052
1053 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1057 Vector<ColorMode>* outColorModes) {
1058 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 return BAD_VALUE;
1060 }
1061
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001063 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001064 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1065
1066 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1067 if (!displayId) {
1068 return NAME_NOT_FOUND;
1069 }
1070
Dominik Laskowski075d3172018-05-24 15:50:06 -07001071 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001072 }
Michael Wright28f24d02016-07-12 13:30:53 -07001073 outColorModes->clear();
1074 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1075
1076 return NO_ERROR;
1077}
1078
Daniel Solomon42d04562019-01-20 21:03:19 -08001079status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1080 ui::DisplayPrimaries &primaries) {
1081 if (!displayToken) {
1082 return BAD_VALUE;
1083 }
1084
1085 // Currently we only support this API for a single internal display.
1086 if (getInternalDisplayToken() != displayToken) {
1087 return BAD_VALUE;
1088 }
1089
1090 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1091 return NO_ERROR;
1092}
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1095 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001096 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001097 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001098 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001102 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 Vector<ColorMode> modes;
1104 getDisplayColorModes(displayToken, &modes);
1105 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1106 if (mode < ColorMode::NATIVE || !exists) {
1107 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1108 decodeColorMode(mode).c_str(), mode, displayToken.get());
1109 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001110 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 const auto display = getDisplayDevice(displayToken);
1112 if (!display) {
1113 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1114 decodeColorMode(mode).c_str(), mode, displayToken.get());
1115 } else if (display->isVirtual()) {
1116 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1117 decodeColorMode(mode).c_str(), mode);
1118 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001119 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1120 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121 }
1122 }));
1123
Michael Wright28f24d02016-07-12 13:30:53 -07001124 return NO_ERROR;
1125}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001126
Svetoslavd85084b2014-03-20 10:28:31 -07001127status_t SurfaceFlinger::clearAnimationFrameStats() {
1128 Mutex::Autolock _l(mStateLock);
1129 mAnimFrameTracker.clearStats();
1130 return NO_ERROR;
1131}
1132
1133status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1134 Mutex::Autolock _l(mStateLock);
1135 mAnimFrameTracker.getStats(outStats);
1136 return NO_ERROR;
1137}
1138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1140 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001141 Mutex::Autolock _l(mStateLock);
1142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143 const auto display = getDisplayDeviceLocked(displayToken);
1144 if (!display) {
1145 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001146 return BAD_VALUE;
1147 }
1148
Peiyong Linfb069302018-04-25 14:34:31 -07001149 // At this point the DisplayDeivce should already be set up,
1150 // meaning the luminance information is already queried from
1151 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001152 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001153 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1154 capabilities.getDesiredMaxLuminance(),
1155 capabilities.getDesiredMaxAverageLuminance(),
1156 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001157
1158 return NO_ERROR;
1159}
1160
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001161status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1162 ui::PixelFormat* outFormat,
1163 ui::Dataspace* outDataspace,
1164 uint8_t* outComponentMask) const {
1165 if (!outFormat || !outDataspace || !outComponentMask) {
1166 return BAD_VALUE;
1167 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001168 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001169 if (!display || !display->getId()) {
1170 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1171 return BAD_VALUE;
1172 }
1173 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1174 outDataspace, outComponentMask);
1175}
1176
Kevin DuBois74e53772018-11-19 10:52:38 -08001177status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1178 bool enable, uint8_t componentMask,
1179 uint64_t maxFrames) const {
1180 const auto display = getDisplayDevice(displayToken);
1181 if (!display || !display->getId()) {
1182 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1183 return BAD_VALUE;
1184 }
1185
1186 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1187 componentMask, maxFrames);
1188}
1189
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001190status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1191 uint64_t maxFrames, uint64_t timestamp,
1192 DisplayedFrameStats* outStats) const {
1193 const auto display = getDisplayDevice(displayToken);
1194 if (!display || !display->getId()) {
1195 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1196 return BAD_VALUE;
1197 }
1198
1199 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1200 outStats);
1201}
1202
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001203status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1204 if (!outSupported) {
1205 return BAD_VALUE;
1206 }
1207 *outSupported = getRenderEngine().supportsProtectedContent();
1208 return NO_ERROR;
1209}
1210
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001211status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1212 bool* outIsWideColorDisplay) const {
1213 if (!displayToken || !outIsWideColorDisplay) {
1214 return BAD_VALUE;
1215 }
1216 Mutex::Autolock _l(mStateLock);
1217 const auto display = getDisplayDeviceLocked(displayToken);
1218 if (!display) {
1219 return BAD_VALUE;
1220 }
1221 *outIsWideColorDisplay = display->hasWideColorGamut();
1222 return NO_ERROR;
1223}
1224
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001225status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001226 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001227 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228
Chia-I Wu90f669f2017-10-05 14:24:41 -07001229 if (mInjectVSyncs == enable) {
1230 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001231 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001232
Ana Krulecc2870422019-01-29 19:00:58 -08001233 auto resyncCallback =
1234 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001235
Ana Krulec98b5b242018-08-10 15:03:23 -07001236 // TODO(akrulec): Part of the Injector should be refactored, so that it
1237 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001238 if (enable) {
1239 ALOGV("VSync Injections enabled");
1240 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001241 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001242 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001243 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001244 impl::EventThread::InterceptVSyncsCallback(),
1245 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001248 } else {
1249 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001250 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1251 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 }
1253
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001255 }));
1256
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 return NO_ERROR;
1258}
1259
1260status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001261 Mutex::Autolock _l(mStateLock);
1262
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001263 if (!mInjectVSyncs) {
1264 ALOGE("VSync Injections not enabled");
1265 return BAD_VALUE;
1266 }
1267 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1268 ALOGV("Injecting VSync inside SurfaceFlinger");
1269 mVSyncInjector->onInjectSyncEvent(when);
1270 }
1271 return NO_ERROR;
1272}
1273
Lloyd Pique755e3192018-01-31 16:46:15 -08001274status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1275 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001276 // Try to acquire a lock for 1s, fail gracefully
1277 const status_t err = mStateLock.timedLock(s2ns(1));
1278 const bool locked = (err == NO_ERROR);
1279 if (!locked) {
1280 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1281 return TIMED_OUT;
1282 }
1283
1284 outLayers->clear();
1285 mCurrentState.traverseInZOrder([&](Layer* layer) {
1286 outLayers->push_back(layer->getLayerDebugInfo());
1287 });
1288
1289 mStateLock.unlock();
1290 return NO_ERROR;
1291}
1292
Peiyong Linc6780972018-10-28 15:24:08 -07001293status_t SurfaceFlinger::getCompositionPreference(
1294 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1295 Dataspace* outWideColorGamutDataspace,
1296 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001297 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001298 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001299 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001300 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001301 return NO_ERROR;
1302}
1303
Dan Stoza84ab9372018-12-17 15:27:57 -08001304status_t SurfaceFlinger::addRegionSamplingListener(
1305 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1306 const sp<IRegionSamplingListener>& /*listener*/) {
1307 return NO_ERROR;
1308}
1309
1310status_t SurfaceFlinger::removeRegionSamplingListener(
1311 const sp<IRegionSamplingListener>& /*listener*/) {
1312 return NO_ERROR;
1313}
1314
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001315// ----------------------------------------------------------------------------
1316
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001317sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1318 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001319 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001320 Mutex::Autolock lock(mStateLock);
1321 return getVsyncPeriod();
1322 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001323
Ana Krulecc2870422019-01-29 19:00:58 -08001324 const auto& handle =
1325 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001326
Ana Krulecc2870422019-01-29 19:00:58 -08001327 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001328}
1329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001330// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001331
1332void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001337 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338}
1339
1340void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001341 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001342}
1343
1344void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001345 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001346 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347}
1348
1349status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001350 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001351 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001352}
1353
1354status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001355 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001356 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001357 if (res == NO_ERROR) {
1358 msg->wait();
1359 }
1360 return res;
1361}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001363void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001364 do {
1365 waitForEvent();
1366 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001367}
1368
Dominik Laskowski83b88212018-12-11 13:34:06 -08001369nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001370 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001371 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1372 return 0;
1373 }
1374
1375 const auto config = getHwComposer().getActiveConfig(*displayId);
1376 return config ? config->getVsyncPeriod() : 0;
1377}
1378
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001379void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1380 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001381 ATRACE_NAME("SF onVsync");
1382
Steven Thomas3cfac282017-02-06 12:29:30 -08001383 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 return;
1387 }
1388
Dominik Laskowski075d3172018-05-24 15:50:06 -07001389 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 return;
1391 }
1392
Dominik Laskowski075d3172018-05-24 15:50:06 -07001393 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001394 // For now, we don't do anything with external display vsyncs.
1395 return;
1396 }
1397
Ana Krulecc2870422019-01-29 19:00:58 -08001398 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001399}
1400
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001401void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001402 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1403 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001404}
1405
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001406void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1407 mPhaseOffsets->setRefreshRateType(refreshRate);
1408
1409 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1410 mVsyncModulator.setPhaseOffsets(early, gl, late);
1411
1412 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001413 return;
1414 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001415
Ana Krulec7d1d6832018-12-27 11:10:09 -08001416 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1417 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1418 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1419 // refresh cycle.
1420
1421 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001422 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001423 if (currentVsyncPeriod == 0) {
1424 return;
1425 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001426
Ana Krulec7d1d6832018-12-27 11:10:09 -08001427 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1428 // floating numbers.
1429 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001430 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1431 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001432 if (std::abs(currentFps - newFps) <= 1) {
1433 return;
1434 }
1435
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001436 const auto displayId = getInternalDisplayIdLocked();
1437 LOG_ALWAYS_FATAL_IF(!displayId);
1438
1439 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001440 for (int i = 0; i < configs.size(); i++) {
1441 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1442 if (vsyncPeriod == 0) {
1443 continue;
1444 }
1445 const float fps = 1e9 / vsyncPeriod;
1446 // TODO(b/113612090): There should be a better way at determining which config
1447 // has the right refresh rate.
1448 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001449 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001450 }
1451 }
1452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001455 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 // Ignore events that do not have the right sequenceId.
1460 if (sequenceId != getBE().mComposerSequenceId) {
1461 return;
1462 }
1463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Only lock if we're not on the main thread. This function is normally
1465 // called on a hwbinder thread, but for the primary display it's called on
1466 // the main thread with the state lock already held, so don't attempt to
1467 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001468 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001471
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001472 if (std::this_thread::get_id() == mMainThreadId) {
1473 // Process all pending hot plug events immediately if we are on the main thread.
1474 processDisplayHotplugEventsLocked();
1475 }
1476
Lloyd Piqueba04e622017-12-14 17:11:26 -08001477 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001478}
1479
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001480void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001482 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001485 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001486}
1487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001488void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001489 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001491 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 getHwComposer().setVsyncEnabled(*displayId,
1493 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1494 }
Mathias Agopian86303202012-07-24 22:46:10 -07001495}
1496
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001498void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001499 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001500 // Clear the drawing state so that the logic inside of
1501 // handleTransactionLocked will fire. It will determine the delta between
1502 // mCurrentState and mDrawingState and re-apply all changes when we make the
1503 // transition.
1504 mDrawingState.displays.clear();
1505 mDisplays.clear();
1506}
1507
Steven Thomas050b2c82017-03-06 11:45:16 -08001508void SurfaceFlinger::updateVrFlinger() {
1509 if (!mVrFlinger)
1510 return;
1511 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001512 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001513 return;
1514 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001515
Lloyd Pique441d5042018-10-18 16:49:51 -07001516 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 ALOGE("Vr flinger is only supported for remote hardware composer"
1518 " service connections. Ignoring request to transition to vr"
1519 " flinger.");
1520 mVrFlingerRequestsDisplay = false;
1521 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001522 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001523
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001524 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001525
Steven Thomas0123ac62018-07-12 11:32:34 -07001526 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001527 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001528
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001529 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001530
1531 // Clear out all the output layers from the composition engine for all
1532 // displays before destroying the hardware composer interface. This ensures
1533 // any HWC layers are destroyed through that interface before it becomes
1534 // invalid.
1535 for (const auto& [token, displayDevice] : mDisplays) {
1536 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1537 compositionengine::Output::OutputLayers());
1538 }
1539
Steven Thomas0123ac62018-07-12 11:32:34 -07001540 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1541 // called below. Clear the reference now so we don't accidentally use it
1542 // later.
1543 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 // Delete the current instance before creating the new one
1551 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1552 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1553 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1554 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001557 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001558
1559 if (vrFlingerRequestsDisplay) {
1560 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001561 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562
1563 mVisibleRegionsDirty = true;
1564 invalidateHwcGeometry();
1565
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 display = getDefaultDisplayDeviceLocked();
1568 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001569 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 const nsecs_t vsyncPeriod = getVsyncPeriod();
1573 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001575 // The present fences returned from vr_hwc are not an accurate
1576 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001577 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 // Use phase of 0 since phase is not known.
1580 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001581 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001582 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001583
Ana Krulecc2870422019-01-29 19:00:58 -08001584 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001585
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001586 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001587 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588}
1589
Mathias Agopian4fec8732012-06-29 14:12:52 -07001590void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001591 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001592 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001593 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001594 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001595 break;
1596 }
1597
Ana Krulecc2870422019-01-29 19:00:58 -08001598 // This call is made each time SF wakes up and creates a new frame.
1599 mScheduler->incrementFrameCounter();
1600
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001601 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1602 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001603 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001604 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001605 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001606 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001607 if (mPropagateBackpressure) {
1608 signalLayerUpdate();
1609 break;
1610 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 }
Dan Stoza50182882016-07-08 12:02:20 -07001612
Steven Thomas050b2c82017-03-06 11:45:16 -08001613 // Now that we're going to make it to the handleMessageTransaction()
1614 // call below it's safe to call updateVrFlinger(), which will
1615 // potentially trigger a display handoff.
1616 updateVrFlinger();
1617
Dan Stoza6b9454d2014-11-07 16:00:59 -08001618 bool refreshNeeded = handleMessageTransaction();
1619 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001620
1621 updateCursorAsync();
1622 updateInputFlinger();
1623
Dan Stoza58784442014-12-02 16:58:17 -08001624 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001625 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001626 // Signal a refresh if a transaction modified the window state,
1627 // a new buffer was latched, or if HWC has requested a full
1628 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 signalRefresh();
1630 }
1631 break;
1632 }
1633 case MessageQueue::REFRESH: {
1634 handleMessageRefresh();
1635 break;
1636 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001637 }
1638}
1639
Dan Stoza6b9454d2014-11-07 16:00:59 -08001640bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001641 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001642
1643 // Apply any ready transactions in the queues if there are still transactions that have not been
1644 // applied, wake up during the next vsync period and check again
1645 bool transactionNeeded = false;
1646 if (!flushTransactionQueues()) {
1647 transactionNeeded = true;
1648 }
1649
Mathias Agopian4fec8732012-06-29 14:12:52 -07001650 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001651 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001652 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001653
1654 if (transactionNeeded) {
1655 setTransactionFlags(eTransactionNeeded);
1656 }
1657
1658 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001659}
1660
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001663
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001664 mRefreshPending = false;
1665
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001666 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001667 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001668 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001669 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001670 for (const auto& [token, display] : mDisplays) {
1671 beginFrame(display);
1672 prepareFrame(display);
1673 doDebugFlashRegions(display, repaintEverything);
1674 doComposition(display, repaintEverything);
1675 }
1676
Adrian Roos1e1a1282017-11-01 19:05:31 +01001677 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001678 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679
1680 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001681 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001682
Dan Stozabfbffeb2016-07-21 14:49:33 -07001683 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001684 for (const auto& [token, displayDevice] : mDisplays) {
1685 auto display = displayDevice->getCompositionDisplay();
1686 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001687 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001688 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001689 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690
Jorim Jaggi90535212018-05-23 23:44:06 +02001691 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001692
David Sodman7e4ae112018-02-09 15:02:28 -08001693 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001694
1695 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698
1699bool SurfaceFlinger::handleMessageInvalidate() {
1700 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001701 bool refreshNeeded = handlePageFlip();
1702
Vishnu Nair4351ad52019-02-11 14:13:02 -08001703 if (mVisibleRegionsDirty) {
1704 computeLayerBounds();
1705 }
1706
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001707 for (auto& layer : mLayersPendingRefresh) {
1708 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001709 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001710 invalidateLayerStack(layer, visibleReg);
1711 }
1712 mLayersPendingRefresh.clear();
1713 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714}
1715
David Sodman79bba0e2018-08-05 18:07:49 -07001716void SurfaceFlinger::calculateWorkingSet() {
1717 ATRACE_CALL();
1718 ALOGV(__FUNCTION__);
1719
David Sodman79bba0e2018-08-05 18:07:49 -07001720 // build the h/w work list
1721 if (CC_UNLIKELY(mGeometryInvalid)) {
1722 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001723 for (const auto& [token, displayDevice] : mDisplays) {
1724 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001725 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001726 if (!displayId) {
1727 continue;
1728 }
David Sodman79bba0e2018-08-05 18:07:49 -07001729
Lloyd Pique32cbe282018-10-19 13:09:22 -07001730 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001731 for (size_t i = 0; i < currentLayers.size(); i++) {
1732 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001733
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001734 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001735 layer->forceClientComposition(displayDevice);
1736 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001737 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738
Lloyd Pique32cbe282018-10-19 13:09:22 -07001739 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001741 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001742 }
David Sodman79bba0e2018-08-05 18:07:49 -07001743 }
1744 }
1745 }
1746
1747 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001748 for (const auto& [token, displayDevice] : mDisplays) {
1749 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001750 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001751 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001752 continue;
1753 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001754 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001755
1756 if (mDrawingState.colorMatrixChanged) {
1757 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001759 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001760 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001761 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001762 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1763 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001764 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001765 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1767 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001768 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001769 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 }
1771
Peiyong Lind3788632018-09-18 16:01:31 -07001772 // TODO(b/111562338) remove when composer 2.3 is shipped.
1773 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001774 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001775 }
1776
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001777 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001778 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001779 }
1780
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001781 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001782 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001783 layer->setCompositionType(displayDevice,
1784 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 continue;
1786 }
1787
Lloyd Pique32cbe282018-10-19 13:09:22 -07001788 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001789 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792
Peiyong Lin13effd12018-07-24 17:01:47 -07001793 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 ColorMode colorMode;
1795 Dataspace dataSpace;
1796 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001799 }
1800 }
1801
1802 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001803
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001804 for (const auto& [token, displayDevice] : mDisplays) {
1805 auto display = displayDevice->getCompositionDisplay();
1806 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001807 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001808 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1809 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1810 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001811 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001812 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001813 }
1814 }
David Sodman79bba0e2018-08-05 18:07:49 -07001815}
1816
Lloyd Pique32cbe282018-10-19 13:09:22 -07001817void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1818 bool repaintEverything) {
1819 auto display = displayDevice->getCompositionDisplay();
1820 const auto& displayState = display->getState();
1821
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822 // is debugging enabled
1823 if (CC_LIKELY(!mDebugRegion))
1824 return;
1825
Lloyd Pique32cbe282018-10-19 13:09:22 -07001826 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001827 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001828 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001829 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001830 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001831 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001832 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001834 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001835 }
1836 }
1837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839
1840 if (mDebugRegion > 1) {
1841 usleep(mDebugRegion * 1000);
1842 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001843
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845}
1846
Adrian Roos1e1a1282017-11-01 19:05:31 +01001847void SurfaceFlinger::doTracing(const char* where) {
1848 ATRACE_CALL();
1849 ATRACE_NAME(where);
1850 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001851 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001852 }
1853}
1854
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001855void SurfaceFlinger::logLayerStats() {
1856 ATRACE_CALL();
1857 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001858 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001859 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001860 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001861 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001862 }
1863 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001864
1865 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001866 }
1867}
1868
David Sodman2b406362017-12-15 13:33:47 -08001869void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ATRACE_CALL();
1872 ALOGV("preComposition");
1873
David Sodman2b406362017-12-15 13:33:47 -08001874 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1875
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001877 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001878 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879 needExtraInvalidate = true;
1880 }
Robert Carr2047fae2016-11-28 14:09:09 -08001881 });
1882
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883 if (needExtraInvalidate) {
1884 signalLayerUpdate();
1885 }
1886}
1887
Ana Krulece588e312018-09-18 12:32:24 -07001888void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1889 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890 // Update queue of past composite+present times and determine the
1891 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001892 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001894 while (!getBE().mCompositePresentTimes.empty()) {
1895 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 // Cached values should have been updated before calling this method,
1897 // which helps avoid duplicate syscalls.
1898 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1899 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1900 break;
1901 }
1902 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001903 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 }
1905
1906 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001907 while (getBE().mCompositePresentTimes.size() > 16) {
1908 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 }
1910
Ana Krulece588e312018-09-18 12:32:24 -07001911 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001912}
1913
Ana Krulece588e312018-09-18 12:32:24 -07001914void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1915 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916 // Integer division and modulo round toward 0 not -inf, so we need to
1917 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001918 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1919 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1920 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921
Ana Krulec757f63a2019-01-25 10:46:18 -08001922 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001923 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001924 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001925 }
1926
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927 // Snap the latency to a value that removes scheduling jitter from the
1928 // composition and present times, which often have >1ms of jitter.
1929 // Reducing jitter is important if an app attempts to extrapolate
1930 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001931 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001933 nsecs_t bias = stats.vsyncPeriod / 2;
1934 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1935 nsecs_t snappedCompositeToPresentLatency =
1936 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937
David Sodman99974d22017-11-28 12:04:33 -08001938 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001939 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1940 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001941 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942}
1943
Ady Abraham8164d482019-01-11 14:47:59 -08001944// debug patch for b/119477596 - add stack guards to catch stack
1945// corruptions and disable clang optimizations.
1946// The code below is temporary and planned to be removed once stack
1947// corruptions are found.
1948#pragma clang optimize off
1949class StackGuard {
1950public:
1951 StackGuard(const char* name, const char* func, int line) {
1952 guarders.reserve(MIN_CAPACITY);
1953 guarders.push_back({this, name, func, line});
1954 validate();
1955 }
1956 ~StackGuard() {
1957 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1958 if (i->guard == this) {
1959 guarders.erase(i);
1960 break;
1961 }
1962 }
1963 }
1964
1965 static void validate() {
1966 for (const auto& guard : guarders) {
1967 if (guard.guard->cookie != COOKIE_VALUE) {
1968 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1969 CallStack stack(LOG_TAG);
1970 abort();
1971 }
1972 }
1973 }
1974
1975private:
1976 uint64_t cookie = COOKIE_VALUE;
1977 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1978 static constexpr size_t MIN_CAPACITY = 16;
1979
1980 struct GuarderElement {
1981 StackGuard* guard;
1982 const char* name;
1983 const char* func;
1984 int line;
1985 };
1986
1987 static std::vector<GuarderElement> guarders;
1988};
1989std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1990
1991#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1992
1993#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001994void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001995{
Ady Abraham8164d482019-01-11 14:47:59 -08001996 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 ATRACE_CALL();
1998 ALOGV("postComposition");
1999
Brian Anderson3546a3f2016-07-14 11:51:14 -07002000 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002001 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002002 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002003 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002004 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002005 }
Ady Abraham8164d482019-01-11 14:47:59 -08002006 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002007
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002008 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002009 const auto displayDevice = getDefaultDisplayDeviceLocked();
2010 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011
David Sodman73beded2017-11-15 11:56:06 -08002012 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002013 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002014 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2015
Lloyd Pique32cbe282018-10-19 13:09:22 -07002016 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002018 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2019 ->getRenderSurface()
2020 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002021 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 } else {
2023 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2024 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025
Ady Abraham8164d482019-01-11 14:47:59 -08002026 ASSERT_ON_STACK_GUARD();
2027
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002029 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2030 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002031 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002032 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034
Ana Krulece588e312018-09-18 12:32:24 -07002035 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002036 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002037 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038
Ady Abraham8164d482019-01-11 14:47:59 -08002039 ASSERT_ON_STACK_GUARD();
2040
David Sodman2b406362017-12-15 13:33:47 -08002041 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 // when we started doing work for this frame, but that should be okay
2043 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002044 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002045 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(compositorTiming);
2047
Brian Andersond0010582017-03-07 13:20:31 -08002048 {
David Sodman99974d22017-11-28 12:04:33 -08002049 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002051 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002052
2053 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002054 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Robert Carr2047fae2016-11-28 14:09:09 -08002056 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002057 bool frameLatched =
2058 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2059 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002060 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002061 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002062 recordBufferingStats(layer->getName().string(),
2063 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002064 }
Ady Abraham8164d482019-01-11 14:47:59 -08002065 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002066 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002067
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002068 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002069 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002070 mScheduler->addPresentFence(presentFenceTime);
2071 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002072 }
2073
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002074 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002075 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2076 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002077 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002078 }
2079 }
2080
Ady Abraham8164d482019-01-11 14:47:59 -08002081 ASSERT_ON_STACK_GUARD();
2082
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083 if (mAnimCompositionPending) {
2084 mAnimCompositionPending = false;
2085
Brian Anderson4e606e32017-03-16 15:34:57 -07002086 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002087 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002088 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002089
2090 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002091 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 // The HWC doesn't support present fences, so use the refresh
2093 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002094 const nsecs_t presentTime =
2095 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002096 DEFINE_STACK_GUARD(presentTime);
2097
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002098 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002099 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002100 }
2101 mAnimFrameTracker.advanceFrame();
2102 }
Dan Stozab90cf072015-03-05 11:05:59 -08002103
Ady Abraham8164d482019-01-11 14:47:59 -08002104 ASSERT_ON_STACK_GUARD();
2105
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002106 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002107 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002108 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002109 }
2110
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
2112
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002113 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002114
Ady Abraham8164d482019-01-11 14:47:59 -08002115 ASSERT_ON_STACK_GUARD();
2116
Lloyd Pique32cbe282018-10-19 13:09:22 -07002117 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2118 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002119 return;
2120 }
2121
2122 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002123 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002124 if (mHasPoweredOff) {
2125 mHasPoweredOff = false;
2126 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002127 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002128 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002129 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002131 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2132 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002133 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002134 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002135 }
David Sodman4a36e932017-11-07 14:29:47 -08002136 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002137
2138 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002139 }
David Sodman4a36e932017-11-07 14:29:47 -08002140 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002141 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002142
2143 {
2144 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002146 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002147 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002148 if (refillCount > 0) {
2149 const size_t offset = mTexturePool.size();
2150 mTexturePool.resize(mTexturePoolSize);
2151 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2152 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2153 }
Ady Abraham8164d482019-01-11 14:47:59 -08002154 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002155 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002156
Marissa Wallfda30bb2018-10-12 11:34:28 -07002157 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002158 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002159
2160 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002161}
Ady Abraham8164d482019-01-11 14:47:59 -08002162#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002163
Vishnu Nair4351ad52019-02-11 14:13:02 -08002164void SurfaceFlinger::computeLayerBounds() {
2165 for (const auto& pair : mDisplays) {
2166 const auto& displayDevice = pair.second;
2167 const auto display = displayDevice->getCompositionDisplay();
2168 for (const auto& layer : mDrawingState.layersSortedByZ) {
2169 // only consider the layers on the given layer stack
2170 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002171 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002172 }
2173
2174 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2175 }
2176 }
2177}
2178
Mathias Agopiancd60f992012-08-16 16:28:27 -07002179void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 ATRACE_CALL();
2181 ALOGV("rebuildLayerStacks");
2182
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002183 // We need to clear these out now as these may be holding on to a
2184 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2185 // also holds a reference. When the set of visible layers is recomputed,
2186 // some layers may be destroyed if the only thing keeping them alive was
2187 // that list of visible layers associated with each display. The layer
2188 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2189 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2190 for (const auto& [token, display] : mDisplays) {
2191 getBE().mCompositionInfo[token].clear();
2192 }
2193
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002195 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002196 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 mVisibleRegionsDirty = false;
2198 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002199
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002200 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002201 const auto& displayDevice = pair.second;
2202 auto display = displayDevice->getCompositionDisplay();
2203 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 Region opaqueRegion;
2205 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002206 compositionengine::Output::OutputLayers layersSortedByZ;
2207 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002208 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002209 const ui::Transform& tr = displayState.transform;
2210 const Rect bounds = displayState.bounds;
2211 if (displayState.isEnabled) {
2212 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002213
Jeff Sharkey76488112017-02-27 14:15:18 -07002214 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002215 auto compositionLayer = layer->getCompositionLayer();
2216 if (compositionLayer == nullptr) {
2217 return;
2218 }
2219
Lloyd Pique32cbe282018-10-19 13:09:22 -07002220 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002221 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2222 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2223
Lloyd Pique07e33212018-12-18 16:33:37 -08002224 bool needsOutputLayer = false;
2225
Lloyd Piqueef36b002019-01-23 17:52:04 -08002226 if (display->belongsInOutput(layer->getLayerStack(),
2227 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002228 Region drawRegion(tr.transform(
2229 layer->visibleNonTransparentRegion));
2230 drawRegion.andSelf(bounds);
2231 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002232 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002233 }
Chia-I Wu83806892017-11-16 10:50:20 -08002234 }
2235
Lloyd Pique07e33212018-12-18 16:33:37 -08002236 if (needsOutputLayer) {
2237 layersSortedByZ.emplace_back(
2238 display->getOrCreateOutputLayer(displayId, compositionLayer,
2239 layerFE));
2240 deprecated_layersSortedByZ.add(layer);
2241
2242 auto& outputLayerState = layersSortedByZ.back()->editState();
2243 outputLayerState.visibleRegion =
2244 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2245 } else if (displayId) {
2246 // For layers that are being removed from a HWC display,
2247 // and that have queued frames, add them to a a list of
2248 // released layers so we can properly set a fence.
2249 bool hasExistingOutputLayer =
2250 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2251 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2252 mLayersWithQueuedFrames.cend(),
2253 layer) != mLayersWithQueuedFrames.cend();
2254
2255 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002256 layersNeedingFences.add(layer);
2257 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002258 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 });
2260 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002261
2262 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2263
2264 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 displayDevice->setLayersNeedingFences(layersNeedingFences);
2266
2267 Region undefinedRegion{bounds};
2268 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2269
2270 display->editState().undefinedRegion = undefinedRegion;
2271 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002272 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002273 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002274}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002275
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002278// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002279// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002280// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281// The returned HDR data space is one of
2282// - Dataspace::UNKNOWN
2283// - Dataspace::BT2020_HLG
2284// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2286 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002287 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288 *outHdrDataSpace = Dataspace::UNKNOWN;
2289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002291 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002292 case Dataspace::V0_SCRGB:
2293 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002294 case Dataspace::BT2020:
2295 case Dataspace::BT2020_ITU:
2296 case Dataspace::BT2020_LINEAR:
2297 case Dataspace::DISPLAY_BT2020:
2298 bestDataSpace = Dataspace::DISPLAY_BT2020;
2299 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002301 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 case Dataspace::BT2020_PQ:
2304 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002305 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002308 case Dataspace::BT2020_HLG:
2309 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002310 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 // When there's mixed PQ content and HLG content, we set the HDR
2312 // data space to be BT2020_PQ and convert HLG to PQ.
2313 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2314 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002315 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 break;
2317 default:
2318 break;
2319 }
Romain Guy54f154a2017-10-24 21:40:32 +01002320 }
2321
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002323}
2324
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2327 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2329 *outMode = ColorMode::NATIVE;
2330 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002333 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002334
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002338 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2339
Peiyong Lina3ea5592019-02-10 14:45:00 -08002340 switch (mForceColorMode) {
2341 case ColorMode::SRGB:
2342 bestDataSpace = Dataspace::V0_SRGB;
2343 break;
2344 case ColorMode::DISPLAY_P3:
2345 bestDataSpace = Dataspace::DISPLAY_P3;
2346 break;
2347 default:
2348 break;
2349 }
2350
Peiyong Lindfde5112018-06-05 10:58:41 -07002351 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002352 const bool isHdr =
2353 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002354 if (isHdr) {
2355 bestDataSpace = hdrDataSpace;
2356 }
2357
Chia-I Wu0d711262018-05-21 15:19:35 -07002358 RenderIntent intent;
2359 switch (mDisplayColorSetting) {
2360 case DisplayColorSetting::MANAGED:
2361 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002362 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002363 break;
2364 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002365 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002366 break;
2367 default: // vendor display color setting
2368 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2369 break;
2370 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002371
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002372 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002373}
2374
Lloyd Pique32cbe282018-10-19 13:09:22 -07002375void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2376 auto display = displayDevice->getCompositionDisplay();
2377 const auto& displayState = display->getState();
2378
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002379 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002380 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2381 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002382
David Sodmanfa9b2af2017-12-24 13:28:59 -08002383 // If nothing has changed (!dirty), don't recompose.
2384 // If something changed, but we don't currently have any visible layers,
2385 // and didn't when we last did a composition, then skip it this time.
2386 // The second rule does two things:
2387 // - When all layers are removed from a display, we'll emit one black
2388 // frame, then nothing more until we get new layers.
2389 // - When a display is created with a private layer stack, we won't
2390 // emit any black frames until a layer is added to the layer stack.
2391 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002392
Dominik Laskowski075d3172018-05-24 15:50:06 -07002393 const char flagPrefix[] = {'-', '+'};
2394 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002395 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2396 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2397 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2398 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002399
Lloyd Pique31cb2942018-10-19 17:23:03 -07002400 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002401
David Sodmanfa9b2af2017-12-24 13:28:59 -08002402 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002404 }
2405}
2406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2408 auto display = displayDevice->getCompositionDisplay();
2409 const auto& displayState = display->getState();
2410
2411 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002412 return;
David Sodman2b406362017-12-15 13:33:47 -08002413 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002415 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002416 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002418}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002419
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002421 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422 ALOGV("doComposition");
2423
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 auto display = displayDevice->getCompositionDisplay();
2425 const auto& displayState = display->getState();
2426
2427 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002429 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002430
David Sodmanfa9b2af2017-12-24 13:28:59 -08002431 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002433
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002435 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002436 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002438}
2439
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440void SurfaceFlinger::postFrame()
2441{
2442 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002443 const auto display = getDefaultDisplayDeviceLocked();
2444 if (display && getHwComposer().isConnected(*display->getId())) {
2445 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002446 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2447 logFrameStats();
2448 }
2449 }
2450}
2451
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002453 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002455
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456 auto display = displayDevice->getCompositionDisplay();
2457 const auto& displayState = display->getState();
2458 const auto displayId = display->getId();
2459
David Sodmanfa9b2af2017-12-24 13:28:59 -08002460 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002461
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 if (displayId) {
2464 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002465 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002466 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002468 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002469
Chia-I Wu7b549592017-11-15 09:14:57 -08002470 // The layer buffer from the previous frame (if any) is released
2471 // by HWC only when the release fence from this frame (if any) is
2472 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002473 if (displayId && layer->hasHwcLayer(displayDevice)) {
2474 releaseFence =
2475 getHwComposer().getLayerReleaseFence(*displayId,
2476 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002477 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002478
2479 // If the layer was client composited in the previous frame, we
2480 // need to merge with the previous client target acquire fence.
2481 // Since we do not track that, always merge with the current
2482 // client target acquire fence when it is available, even though
2483 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002484 if (layer->getCompositionType(displayDevice) ==
2485 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002486 releaseFence =
2487 Fence::merge("LayerRelease", releaseFence,
2488 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002489 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002490
David Sodman15094112018-10-11 09:39:37 -07002491 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 }
Chia-I Wu83806892017-11-16 10:50:20 -08002493
2494 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002496 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002497 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002499 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002500 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002501 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002502 }
2503 }
2504
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 if (displayId) {
2506 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002507 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509}
2510
Mathias Agopian87baae12012-07-31 12:38:26 -07002511void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512{
Mathias Agopian841cde52012-03-01 15:44:37 -08002513 ATRACE_CALL();
2514
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002515 // here we keep a copy of the drawing state (that is the state that's
2516 // going to be overwritten by handleTransactionLocked()) outside of
2517 // mStateLock so that the side-effects of the State assignment
2518 // don't happen with mStateLock held (which can cause deadlocks).
2519 State drawingState(mDrawingState);
2520
Mathias Agopianca4d3602011-05-19 15:38:14 -07002521 Mutex::Autolock _l(mStateLock);
2522 const nsecs_t now = systemTime();
2523 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524
Mathias Agopianca4d3602011-05-19 15:38:14 -07002525 // Here we're guaranteed that some transaction flags are set
2526 // so we can call handleTransactionLocked() unconditionally.
2527 // We call getTransactionFlags(), which will also clear the flags,
2528 // with mStateLock held to guarantee that mCurrentState won't change
2529 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002530
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002531 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002532 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002533 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002534
Mathias Agopianca4d3602011-05-19 15:38:14 -07002535 mLastTransactionTime = systemTime() - now;
2536 mDebugInTransaction = 0;
2537 invalidateHwcGeometry();
2538 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002539}
2540
Lloyd Piqueba04e622017-12-14 17:11:26 -08002541void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2542 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 const std::optional<DisplayIdentificationInfo> info =
2544 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002545
Dominik Laskowski075d3172018-05-24 15:50:06 -07002546 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002547 continue;
2548 }
2549
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002552 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 mPhysicalDisplayTokens[info->id] = new BBinder();
2554 DisplayDeviceState state;
2555 state.displayId = info->id;
2556 state.isSecure = true; // All physical displays are currently considered secure.
2557 state.displayName = info->name;
2558 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2559 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002560 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002561 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002562 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002563
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2565 if (index >= 0) {
2566 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2567 mInterceptor->saveDisplayDeletion(state.sequenceId);
2568 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002569 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571 }
2572
2573 processDisplayChangesLocked();
2574 }
2575
2576 mPendingHotplugEvents.clear();
2577}
2578
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002579void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002580 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2581 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002582}
2583
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002586 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 const sp<IGraphicBufferProducer>& producer) {
2588 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002589 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002591 creationArgs.isSecure = state.isSecure;
2592 creationArgs.displaySurface = dispSurface;
2593 creationArgs.hasWideColorGamut = false;
2594 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002595
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002596 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 creationArgs.isPrimary = isInternalDisplay;
2598
2599 if (useColorManagement && displayId) {
2600 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002602 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002603 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002605
Dominik Laskowski7e045462018-05-30 13:02:02 -07002606 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002608 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609 }
tangrobin6753a022018-08-10 10:58:54 +08002610 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 if (displayId) {
2613 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002616 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617
Lloyd Pique90c115d2018-09-18 21:39:42 -07002618 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622 // Make sure that composition can never be stalled by a virtual display
2623 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002624 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002625 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2627 }
2628
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 creationArgs.displayInstallOrientation =
2630 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002631
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002633 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
Lloyd Pique90c115d2018-09-18 21:39:42 -07002635 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636
2637 if (maxFrameBufferAcquiredBuffers >= 3) {
2638 nativeWindowSurface->preallocateBuffers();
2639 }
2640
2641 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002642 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002643 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002645 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002647 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2648 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 if (!state.isVirtual()) {
2650 LOG_ALWAYS_FATAL_IF(!displayId);
2651 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002652 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 display->setLayerStack(state.layerStack);
2655 display->setProjection(state.orientation, state.viewport, state.frame);
2656 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659}
2660
Lloyd Pique347200f2017-12-14 17:00:15 -08002661void SurfaceFlinger::processDisplayChangesLocked() {
2662 // here we take advantage of Vector's copy-on-write semantics to
2663 // improve performance by skipping the transaction entirely when
2664 // know that the lists are identical
2665 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2666 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2667 if (!curr.isIdenticalTo(draw)) {
2668 mVisibleRegionsDirty = true;
2669 const size_t cc = curr.size();
2670 size_t dc = draw.size();
2671
2672 // find the displays that were removed
2673 // (ie: in drawing state but not in current state)
2674 // also handle displays that changed
2675 // (ie: displays that are in both lists)
2676 for (size_t i = 0; i < dc;) {
2677 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2678 if (j < 0) {
2679 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002681 // Save display ID before disconnecting.
2682 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002683 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002684
2685 if (!display->isVirtual()) {
2686 LOG_ALWAYS_FATAL_IF(!displayId);
2687 dispatchDisplayHotplugEvent(displayId->value, false);
2688 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002690
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002692 } else {
2693 // this display is in both lists. see if something changed.
2694 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2697 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2698 if (state_binder != draw_binder) {
2699 // changing the surface is like destroying and
2700 // recreating the DisplayDevice, so we just remove it
2701 // from the drawing state, so that it get re-added
2702 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002704 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 mDrawingState.displays.removeItemsAt(i);
2708 dc--;
2709 // at this point we must loop to the next item
2710 continue;
2711 }
2712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 }
2717 if ((state.orientation != draw[i].orientation) ||
2718 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 }
2721 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 }
2724 }
2725 }
2726 ++i;
2727 }
2728
2729 // find displays that were added
2730 // (ie: in current state but not in drawing state)
2731 for (size_t i = 0; i < cc; i++) {
2732 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2733 const DisplayDeviceState& state(curr[i]);
2734
Lloyd Pique542307f2018-10-19 13:24:08 -07002735 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 sp<IGraphicBufferProducer> producer;
2737 sp<IGraphicBufferProducer> bqProducer;
2738 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002739 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002742 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 // Virtual displays without a surface are dormant:
2744 // they have external state (layer stack, projection,
2745 // etc.) but no internal state (i.e. a DisplayDevice).
2746 if (state.surface != nullptr) {
2747 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 int width = 0;
2750 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2751 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2752 int height = 0;
2753 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2754 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2755 int intFormat = 0;
2756 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2757 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002758 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002759
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 displayId =
2761 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 }
2763
2764 // TODO: Plumb requested format back up to consumer
2765
2766 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 bqProducer, bqConsumer,
2769 state.displayName);
2770
2771 dispSurface = vds;
2772 producer = vds;
2773 }
2774 } else {
2775 ALOGE_IF(state.surface != nullptr,
2776 "adding a supported display, but rendering "
2777 "surface is provided (%p), ignoring it",
2778 state.surface.get());
2779
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 displayId = state.displayId;
2781 LOG_ALWAYS_FATAL_IF(!displayId);
2782 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 producer = bqProducer;
2784 }
2785
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002786 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002789 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002790 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002791 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002793 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 }
2795 }
2796 }
2797 }
2798 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002799
2800 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002801}
2802
Mathias Agopian87baae12012-07-31 12:38:26 -07002803void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002804{
Dan Stoza7dde5992015-05-22 09:51:44 -07002805 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mCurrentState.traverseInZOrder([](Layer* layer) {
2807 layer->notifyAvailableFrames();
2808 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002809
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 /*
2811 * Traversal of the children
2812 * (perform the transaction for each of them if needed)
2813 */
2814
Mathias Agopian3559b072012-08-15 13:46:03 -07002815 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002816 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002818 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819
2820 const uint32_t flags = layer->doTransaction(0);
2821 if (flags & Layer::eVisibleRegion)
2822 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002823
2824 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002825 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002826 }
Robert Carr2047fae2016-11-28 14:09:09 -08002827 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828 }
2829
2830 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002831 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 */
2833
Mathias Agopiane57f2922012-08-09 16:29:12 -07002834 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002835 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002836 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002837 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002839 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002840 // The transform hint might have changed for some layers
2841 // (either because a display has changed, or because a layer
2842 // as changed).
2843 //
2844 // Walk through all the layers in currentLayers,
2845 // and update their transform hint.
2846 //
2847 // If a layer is visible only on a single display, then that
2848 // display is used to calculate the hint, otherwise we use the
2849 // default display.
2850 //
2851 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2852 // the hint is set before we acquire a buffer from the surface texture.
2853 //
2854 // NOTE: layer transactions have taken place already, so we use their
2855 // drawing state. However, SurfaceFlinger's own transaction has not
2856 // happened yet, so we must use the current state layer list
2857 // (soon to become the drawing state list).
2858 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002860 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002861 bool first = true;
2862 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002863 // NOTE: we rely on the fact that layers are sorted by
2864 // layerStack first (so we don't have to traverse the list
2865 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002867 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002868 currentlayerStack = layerStack;
2869 // figure out if this layerstack is mirrored
2870 // (more than one display) if so, pick the default display,
2871 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002872 hintDisplay = nullptr;
2873 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002874 if (display->getCompositionDisplay()
2875 ->belongsInOutput(layer->getLayerStack(),
2876 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002877 if (hintDisplay) {
2878 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002879 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002880 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002882 }
2883 }
2884 }
2885 }
Chet Haase91d25932013-04-11 15:24:55 -07002886
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002888 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2889 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002890
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002891 // could be null when this layer is using a layerStack
2892 // that is not visible on any display. Also can occur at
2893 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002894 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002895 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002896
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002897 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002898 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002899 if (hintDisplay) {
2900 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002901 }
Robert Carr2047fae2016-11-28 14:09:09 -08002902
2903 first = false;
2904 });
Mathias Agopian84300952012-11-21 16:02:13 -08002905 }
2906
2907
Mathias Agopian3559b072012-08-15 13:46:03 -07002908 /*
2909 * Perform our own transaction if needed
2910 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911
2912 if (mLayersAdded) {
2913 mLayersAdded = false;
2914 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002915 mVisibleRegionsDirty = true;
2916 }
2917
2918 // some layers might have been removed, so
2919 // we need to update the regions they're exposing.
2920 if (mLayersRemoved) {
2921 mLayersRemoved = false;
2922 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002923 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002924 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002925 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002927 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002928 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002929 }
Robert Carr2047fae2016-11-28 14:09:09 -08002930 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931 }
2932
Vishnu Nairec0ab382019-02-13 15:32:56 -08002933 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002935}
2936
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002937void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002938 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002939 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002940 return;
2941 }
2942
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002943 if (mVisibleRegionsDirty || mInputInfoChanged) {
2944 mInputInfoChanged = false;
2945 updateInputWindowInfo();
2946 }
2947
2948 executeInputWindowCommands();
2949}
2950
2951void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002952 Vector<InputWindowInfo> inputHandles;
2953
2954 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2955 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002956 // When calculating the screen bounds we ignore the transparent region since it may
2957 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002958 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002959 }
2960 });
2961 mInputFlinger->setInputWindows(inputHandles);
2962}
2963
Vishnu Nairec0ab382019-02-13 15:32:56 -08002964void SurfaceFlinger::commitInputWindowCommands() {
2965 mInputWindowCommands.merge(mPendingInputWindowCommands);
2966 mPendingInputWindowCommands.clear();
2967}
2968
chaviwfbe5d9c2018-12-26 12:23:37 -08002969void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002970 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2971 if (transferTouchFocusCommand.fromToken != nullptr &&
2972 transferTouchFocusCommand.toToken != nullptr &&
2973 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2974 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2975 transferTouchFocusCommand.toToken);
2976 }
2977 }
2978
2979 mInputWindowCommands.clear();
2980}
2981
Riley Andrews03414a12014-07-01 14:22:59 -07002982void SurfaceFlinger::updateCursorAsync()
2983{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002984 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002985 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002986 continue;
2987 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002989 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2990 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002991 }
2992 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002993}
2994
chaviw61626f22018-11-15 16:26:27 -08002995void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2996 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002997 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002998 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002999 }
3000 layer->releasePendingBuffer(systemTime());
3001}
3002
Mathias Agopian4fec8732012-06-29 14:12:52 -07003003void SurfaceFlinger::commitTransaction()
3004{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003005 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003006 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003007 for (const auto& l : mLayersPendingRemoval) {
3008 recordBufferingStats(l->getName().string(),
3009 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003010
Lloyd Pique07e33212018-12-18 16:33:37 -08003011 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003012 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003013 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003014 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 }
3016 mLayersPendingRemoval.clear();
3017 }
3018
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003019 // If this transaction is part of a window animation then the next frame
3020 // we composite should be considered an animation as well.
3021 mAnimCompositionPending = mAnimTransactionPending;
3022
Mathias Agopian4fec8732012-06-29 14:12:52 -07003023 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003024 // clear the "changed" flags in current state
3025 mCurrentState.colorMatrixChanged = false;
3026
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 mDrawingState.traverseInZOrder([](Layer* layer) {
3028 layer->commitChildList();
3029 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003030 mTransactionPending = false;
3031 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003032 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033}
3034
Lloyd Pique32cbe282018-10-19 13:09:22 -07003035void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003039
Lloyd Pique32cbe282018-10-19 13:09:22 -07003040 auto display = displayDevice->getCompositionDisplay();
3041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 Region aboveOpaqueLayers;
3043 Region aboveCoveredLayers;
3044 Region dirty;
3045
Mathias Agopian87baae12012-07-31 12:38:26 -07003046 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Robert Carr2047fae2016-11-28 14:09:09 -08003048 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003049 // start with the whole surface at its current location
3050 const Layer::State& s(layer->getDrawingState());
3051
Jesse Hall01e29052013-02-19 16:13:35 -08003052 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003053 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003054 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003056
Mathias Agopianab028732010-03-16 16:41:46 -07003057 /*
3058 * opaqueRegion: area of a surface that is fully opaque.
3059 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003061
3062 /*
3063 * visibleRegion: area of a surface that is visible on screen
3064 * and not fully transparent. This is essentially the layer's
3065 * footprint minus the opaque regions above it.
3066 * Areas covered by a translucent surface are considered visible.
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 /*
3071 * coveredRegion: area of a surface that is covered by all
3072 * visible regions above it (which includes the translucent areas).
3073 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075
Jesse Halla8026d22012-09-25 13:25:04 -07003076 /*
3077 * transparentRegion: area of a surface that is hinted to be completely
3078 * transparent. This is only used to tell when the layer has no visible
3079 * non-transparent regions and can be removed from the layer list. It
3080 * does not affect the visibleRegion of this layer or any layers
3081 * beneath it. The hint may not be correct if apps don't respect the
3082 * SurfaceView restrictions (which, sadly, some don't).
3083 */
3084 Region transparentRegion;
3085
Mathias Agopianab028732010-03-16 16:41:46 -07003086
3087 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003088 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003090 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003093 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003094 if (!visibleRegion.isEmpty()) {
3095 // Remove the transparent area from the visible region
3096 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003097 if (tr.preserveRects()) {
3098 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003099 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003101 // transformation too complex, can't do the
3102 // transparent region optimization.
3103 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003104 }
Mathias Agopianab028732010-03-16 16:41:46 -07003105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
Mathias Agopianab028732010-03-16 16:41:46 -07003107 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003109 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003110 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003111 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003112 // the opaque region is the layer's footprint
3113 opaqueRegion = visibleRegion;
3114 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 }
3116 }
3117
Robert Carre5f4f692018-01-12 13:12:28 -08003118 if (visibleRegion.isEmpty()) {
3119 layer->clearVisibilityRegions();
3120 return;
3121 }
3122
Mathias Agopianab028732010-03-16 16:41:46 -07003123 // Clip the covered region to the visible region
3124 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3125
3126 // Update aboveCoveredLayers for next (lower) layer
3127 aboveCoveredLayers.orSelf(visibleRegion);
3128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 // subtract the opaque region covered by the layers above us
3130 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131
3132 // compute this layer's dirty region
3133 if (layer->contentDirty) {
3134 // we need to invalidate the whole region
3135 dirty = visibleRegion;
3136 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 layer->contentDirty = false;
3139 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003140 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003141 * the exposed region consists of two components:
3142 * 1) what's VISIBLE now and was COVERED before
3143 * 2) what's EXPOSED now less what was EXPOSED before
3144 *
3145 * note that (1) is conservative, we start with the whole
3146 * visible region but only keep what used to be covered by
3147 * something -- which mean it may have been exposed.
3148 *
3149 * (2) handles areas that were not covered by anything but got
3150 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003151 */
Mathias Agopianab028732010-03-16 16:41:46 -07003152 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 const Region oldVisibleRegion = layer->visibleRegion;
3154 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003155 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3156 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 dirty.subtractSelf(aboveOpaqueLayers);
3159
3160 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003161 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopianab028732010-03-16 16:41:46 -07003163 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003165
Jesse Halla8026d22012-09-25 13:25:04 -07003166 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 layer->setVisibleRegion(visibleRegion);
3168 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003169 layer->setVisibleNonTransparentRegion(
3170 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003171 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian87baae12012-07-31 12:38:26 -07003173 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174}
3175
Chia-I Wuab0c3192017-08-01 11:29:00 -07003176void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003177 for (const auto& [token, displayDevice] : mDisplays) {
3178 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003179 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003180 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003181 }
3182 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003183}
3184
Daniel Solomon42d04562019-01-20 21:03:19 -08003185void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3186 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3187 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3188 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3189 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3190 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3191 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3192 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3193 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3194 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3195 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3196 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3197 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3198}
3199
Dan Stoza6b9454d2014-11-07 16:00:59 -08003200bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003202 ALOGV("handlePageFlip");
3203
Brian Andersond6927fb2016-07-23 23:37:30 -07003204 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205
Mathias Agopian4fec8732012-06-29 14:12:52 -07003206 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003207 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003208 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003209
3210 // Store the set of layers that need updates. This set must not change as
3211 // buffers are being latched, as this could result in a deadlock.
3212 // Example: Two producers share the same command stream and:
3213 // 1.) Layer 0 is latched
3214 // 2.) Layer 0 gets a new frame
3215 // 2.) Layer 1 gets a new frame
3216 // 3.) Layer 1 is latched.
3217 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3218 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003219 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003220 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003222 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003223 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003224 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003225 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003226 } else {
3227 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003229 } else {
3230 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 }
Robert Carr2047fae2016-11-28 14:09:09 -08003232 });
3233
Lloyd Piquef2c79392018-12-20 16:23:33 -08003234 if (!mLayersWithQueuedFrames.empty()) {
3235 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3236 // writes to Layer current state. See also b/119481871
3237 Mutex::Autolock lock(mStateLock);
3238
3239 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003240 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003241 mLayersPendingRefresh.push_back(layer);
3242 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003243 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003244 if (layer->isBufferLatched()) {
3245 newDataLatched = true;
3246 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003247 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003248 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003249
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003250 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251
3252 // If we will need to wake up at some time in the future to deal with a
3253 // queued frame that shouldn't be displayed during this vsync period, wake
3254 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003255 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003256 signalLayerUpdate();
3257 }
3258
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003259 // enter boot animation on first buffer latch
3260 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3261 ALOGI("Enter boot animation");
3262 mBootStage = BootStage::BOOTANIMATION;
3263 }
3264
Dan Stoza6b9454d2014-11-07 16:00:59 -08003265 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003266 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267}
3268
Mathias Agopianad456f92011-01-13 17:53:01 -08003269void SurfaceFlinger::invalidateHwcGeometry()
3270{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003271 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003272}
3273
Lloyd Pique32cbe282018-10-19 13:09:22 -07003274void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003275 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003276 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003277 // We only need to actually compose the display if:
3278 // 1) It is being handled by hardware composer, which may need this to
3279 // keep its virtual display state machine in sync, or
3280 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003281 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003283 return;
3284 }
3285
Dan Stoza9e56aa02015-11-02 13:00:03 -08003286 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003287 base::unique_fd readyFence;
3288 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003289
3290 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003291 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292}
3293
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003294bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3295 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003296 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003298
Lloyd Pique32cbe282018-10-19 13:09:22 -07003299 auto display = displayDevice->getCompositionDisplay();
3300 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003301 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003302
3303 const Region bounds(displayState.bounds);
3304 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003305 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003306 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003307
Peiyong Lind3788632018-09-18 16:01:31 -07003308 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003309 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003310
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003311 renderengine::DisplaySettings clientCompositionDisplay;
3312 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3313 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003314
Dan Stoza9e56aa02015-11-02 13:00:03 -08003315 if (hasClientComposition) {
3316 ALOGV("hasClientComposition");
3317
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003318 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003319
3320 if (buf == nullptr) {
3321 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3322 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003323 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003324 return false;
3325 }
3326
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003327 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3328 clientCompositionDisplay.clip = displayState.scissor;
3329 const ui::Transform& displayTransform = displayState.transform;
3330 mat4 m;
3331 m[0][0] = displayTransform[0][0];
3332 m[0][1] = displayTransform[0][1];
3333 m[0][3] = displayTransform[0][2];
3334 m[1][0] = displayTransform[1][0];
3335 m[1][1] = displayTransform[1][1];
3336 m[1][3] = displayTransform[1][2];
3337 m[3][0] = displayTransform[2][0];
3338 m[3][1] = displayTransform[2][1];
3339 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003340
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003341 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003343 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003344 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003345 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003347 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003348 clientCompositionDisplay.outputDataspace = outputDataspace;
3349 clientCompositionDisplay.maxLuminance =
3350 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003351
Lloyd Pique441d5042018-10-18 16:49:51 -07003352 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003353 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003354 getHwComposer()
3355 .hasDisplayCapability(displayId,
3356 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003357
Peiyong Lind3788632018-09-18 16:01:31 -07003358 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003359 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3360 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003361 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003362 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003363 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003364
Mathias Agopian85d751c2012-08-29 16:59:24 -07003365 /*
3366 * and then, render the layers targeted at the framebuffer
3367 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003368
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003370 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003371 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 const Region viewportRegion(displayState.viewport);
3374 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003375 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003376 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003377 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003378 switch (layer->getCompositionType(displayDevice)) {
3379 case Hwc2::IComposerClient::Composition::CURSOR:
3380 case Hwc2::IComposerClient::Composition::DEVICE:
3381 case Hwc2::IComposerClient::Composition::SIDEBAND:
3382 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003383 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003384 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003385 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003386 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003387 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003388 // never clear the very first layer since we're
3389 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390 renderengine::LayerSettings layerSettings;
3391 Region dummyRegion;
3392 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3393 layerSettings);
3394
3395 if (prepared) {
3396 layerSettings.source.buffer.buffer = nullptr;
3397 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3398 layerSettings.alpha = half(0.0);
3399 layerSettings.disableBlending = true;
3400 clientCompositionLayers.push_back(layerSettings);
3401 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003402 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003404 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003405 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003406 renderengine::LayerSettings layerSettings;
3407 bool prepared =
3408 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3409 if (prepared) {
3410 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003411 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 break;
3413 }
3414 default:
3415 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003416 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003417 } else {
3418 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003419 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003420 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003421 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003422
Alec Mouri820c7402019-01-23 13:02:39 -08003423 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003424 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003425 clientCompositionDisplay.clearRegion = clearRegion;
3426 if (!debugRegion.isEmpty()) {
3427 Region::const_iterator it = debugRegion.begin();
3428 Region::const_iterator end = debugRegion.end();
3429 while (it != end) {
3430 const Rect& rect = *it++;
3431 renderengine::LayerSettings layerSettings;
3432 layerSettings.source.buffer.buffer = nullptr;
3433 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3434 layerSettings.geometry.boundaries = rect.toFloatRect();
3435 layerSettings.alpha = half(1.0);
3436 clientCompositionLayers.push_back(layerSettings);
3437 }
3438 }
3439 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3440 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003441 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003442 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003443}
3444
Chia-I Wu28e3a252018-09-07 12:05:02 -07003445void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003446 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003447 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003448}
3449
Dan Stoza7d89d062015-04-30 13:29:25 -07003450status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003451 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003452 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003453 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003454 const sp<Layer>& parent,
3455 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003456{
Dan Stoza7d89d062015-04-30 13:29:25 -07003457 // add this layer to the current state list
3458 {
3459 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003460 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003461 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3462 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003463 return NO_MEMORY;
3464 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003465 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003467 } else if (parent == nullptr) {
3468 lbc->onRemovedFromCurrentState();
3469 } else if (parent->isRemovedFromCurrentState()) {
3470 parent->addChild(lbc);
3471 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003472 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003473 parent->addChild(lbc);
3474 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003475
Yiwei Zhang243b3782018-05-15 17:40:04 -07003476 if (gbc != nullptr) {
3477 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3478 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3479 mMaxGraphicBufferProducerListSize,
3480 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3481 mGraphicBufferProducerList.size(),
3482 mMaxGraphicBufferProducerListSize, mNumLayers);
3483 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003484 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003485 }
3486
Mathias Agopian96f08192010-06-02 23:28:45 -07003487 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003488 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003489
Dan Stoza7d89d062015-04-30 13:29:25 -07003490 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003491}
3492
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003493uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003494 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003495}
3496
Mathias Agopian3f844832013-08-07 21:24:32 -07003497uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003498 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499}
3500
Mathias Agopian3f844832013-08-07 21:24:32 -07003501uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003502 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003503}
3504
3505uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003506 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003507 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003508 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003510 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 }
3512 return old;
3513}
3514
Marissa Wall713b63f2018-10-17 15:42:43 -07003515bool SurfaceFlinger::flushTransactionQueues() {
3516 Mutex::Autolock _l(mStateLock);
3517 auto it = mTransactionQueues.begin();
3518 while (it != mTransactionQueues.end()) {
3519 auto& [applyToken, transactionQueue] = *it;
3520
3521 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003522 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3523 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003524 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003525 break;
3526 }
Robert Carr14167e02019-02-13 13:50:55 -08003527 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003528 transactionQueue.pop();
3529 }
3530
3531 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3532 }
3533 return mTransactionQueues.empty();
3534}
3535
chaviwca27f252018-02-06 16:46:39 -08003536bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3537 for (const ComposerState& state : states) {
3538 // Here we need to check that the interface we're given is indeed
3539 // one of our own. A malicious client could give us a nullptr
3540 // IInterface, or one of its own or even one of our own but a
3541 // different type. All these situations would cause us to crash.
3542 if (state.client == nullptr) {
3543 return true;
3544 }
3545
3546 sp<IBinder> binder = IInterface::asBinder(state.client);
3547 if (binder == nullptr) {
3548 return true;
3549 }
3550
3551 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3552 return true;
3553 }
3554 }
3555 return false;
3556}
3557
Marissa Wall17b4e452018-12-26 16:32:34 -08003558bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3559 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003560 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003561 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3562 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3563 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3564 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3565 return false;
3566 }
3567
Marissa Wall713b63f2018-10-17 15:42:43 -07003568 for (const ComposerState& state : states) {
3569 const layer_state_t& s = state.state;
3570 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3571 continue;
3572 }
3573 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003574 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003575 }
3576 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003577 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003578}
3579
3580void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3581 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003582 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003583 const InputWindowCommands& inputWindowCommands,
3584 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003585 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003586
3587 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3588
Mathias Agopian698c0872011-06-28 19:09:31 -07003589 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003590
chaviwca27f252018-02-06 16:46:39 -08003591 if (containsAnyInvalidClientState(states)) {
3592 return;
3593 }
3594
Marissa Wall713b63f2018-10-17 15:42:43 -07003595 // If its TransactionQueue already has a pending TransactionState or if it is pending
3596 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003597 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003598 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3599 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003600 setTransactionFlags(eTransactionNeeded);
3601 return;
3602 }
3603
Robert Carr14167e02019-02-13 13:50:55 -08003604 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003605}
3606
3607void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003608 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003609 const InputWindowCommands& inputWindowCommands,
3610 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003611 uint32_t transactionFlags = 0;
3612
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003613 if (flags & eAnimation) {
3614 // For window updates that are part of an animation we must wait for
3615 // previous animation "frames" to be handled.
3616 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003617 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003618 if (CC_UNLIKELY(err != NO_ERROR)) {
3619 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003620 // caller after a few seconds.
3621 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3622 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003623 mAnimTransactionPending = false;
3624 break;
3625 }
3626 }
3627 }
3628
chaviwca27f252018-02-06 16:46:39 -08003629 for (const DisplayState& display : displays) {
3630 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003631 }
3632
Marissa Walle2ffb422018-10-12 11:33:52 -07003633 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003634 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003635 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003636 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003637 // If the state doesn't require a traversal and there are callbacks, send them now
3638 if (!(clientStateFlags & eTraversalNeeded)) {
3639 mTransactionCompletedThread.sendCallbacks();
3640 }
3641 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003642
chaviw273171b2018-12-26 11:46:30 -08003643 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3644
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003645 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3646 // anyway. This can be used as a flush mechanism for previous async transactions.
3647 // Empty animation transaction can be used to simulate back-pressure, so also force a
3648 // transaction for empty animation transactions.
3649 if (transactionFlags == 0 &&
3650 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003651 transactionFlags = eTransactionNeeded;
3652 }
3653
Mathias Agopian386aa982011-11-07 21:58:03 -08003654 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003655 if (mInterceptor->isEnabled()) {
3656 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003657 }
Irvel468051e2016-06-13 16:44:44 -07003658
Mathias Agopian386aa982011-11-07 21:58:03 -08003659 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003660 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3661 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003662 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003663
3664 // if this is a synchronous transaction, wait for it to take effect
3665 // before returning.
3666 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003667 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003668 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003669 if (flags & eAnimation) {
3670 mAnimTransactionPending = true;
3671 }
3672 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003673 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3674 if (CC_UNLIKELY(err != NO_ERROR)) {
3675 // just in case something goes wrong in SF, return to the
3676 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003677 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3678 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003679 break;
3680 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003681 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682 }
3683}
3684
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003685uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3686 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3687 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003688
Mathias Agopiane57f2922012-08-09 16:29:12 -07003689 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003690 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3691
3692 const uint32_t what = s.what;
3693 if (what & DisplayState::eSurfaceChanged) {
3694 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3695 state.surface = s.surface;
3696 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003697 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003698 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003699 if (what & DisplayState::eLayerStackChanged) {
3700 if (state.layerStack != s.layerStack) {
3701 state.layerStack = s.layerStack;
3702 flags |= eDisplayTransactionNeeded;
3703 }
3704 }
3705 if (what & DisplayState::eDisplayProjectionChanged) {
3706 if (state.orientation != s.orientation) {
3707 state.orientation = s.orientation;
3708 flags |= eDisplayTransactionNeeded;
3709 }
3710 if (state.frame != s.frame) {
3711 state.frame = s.frame;
3712 flags |= eDisplayTransactionNeeded;
3713 }
3714 if (state.viewport != s.viewport) {
3715 state.viewport = s.viewport;
3716 flags |= eDisplayTransactionNeeded;
3717 }
3718 }
3719 if (what & DisplayState::eDisplaySizeChanged) {
3720 if (state.width != s.width) {
3721 state.width = s.width;
3722 flags |= eDisplayTransactionNeeded;
3723 }
3724 if (state.height != s.height) {
3725 state.height = s.height;
3726 flags |= eDisplayTransactionNeeded;
3727 }
3728 }
3729
Mathias Agopiane57f2922012-08-09 16:29:12 -07003730 return flags;
3731}
3732
Robert Carr14167e02019-02-13 13:50:55 -08003733bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003734 IPCThreadState* ipc = IPCThreadState::self();
3735 const int pid = ipc->getCallingPid();
3736 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003737 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003738 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003739 return false;
3740 }
3741 return true;
3742}
3743
Robert Carr14167e02019-02-13 13:50:55 -08003744uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3745 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003746 const layer_state_t& s = composerState.state;
3747 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3748
Mathias Agopian13127d82013-03-05 17:47:11 -08003749 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003750 if (layer == nullptr) {
3751 return 0;
3752 }
3753
chaviw8b3871a2017-11-01 17:41:01 -07003754 uint32_t flags = 0;
3755
Garfield Tan8a3083e2018-12-03 13:21:07 -08003756 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003757 bool geometryAppliesWithResize =
3758 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003759
3760 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3761 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003762 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003763 layer->pushPendingState();
3764 }
3765
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (what & layer_state_t::ePositionChanged) {
3767 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3768 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003769 }
chaviw8b3871a2017-11-01 17:41:01 -07003770 }
3771 if (what & layer_state_t::eLayerChanged) {
3772 // NOTE: index needs to be calculated before we update the state
3773 const auto& p = layer->getParent();
3774 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003775 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003776 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003777 mCurrentState.layersSortedByZ.removeAt(idx);
3778 mCurrentState.layersSortedByZ.add(layer);
3779 // we need traversal (state changed)
3780 // AND transaction (list changed)
3781 flags |= eTransactionNeeded|eTraversalNeeded;
3782 }
chaviw8b3871a2017-11-01 17:41:01 -07003783 } else {
3784 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003785 flags |= eTransactionNeeded|eTraversalNeeded;
3786 }
3787 }
chaviw8b3871a2017-11-01 17:41:01 -07003788 }
3789 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003790 // NOTE: index needs to be calculated before we update the state
3791 const auto& p = layer->getParent();
3792 if (p == nullptr) {
3793 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3794 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3795 mCurrentState.layersSortedByZ.removeAt(idx);
3796 mCurrentState.layersSortedByZ.add(layer);
3797 // we need traversal (state changed)
3798 // AND transaction (list changed)
3799 flags |= eTransactionNeeded|eTraversalNeeded;
3800 }
3801 } else {
3802 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3803 flags |= eTransactionNeeded|eTraversalNeeded;
3804 }
chaviw8b3871a2017-11-01 17:41:01 -07003805 }
3806 }
3807 if (what & layer_state_t::eSizeChanged) {
3808 if (layer->setSize(s.w, s.h)) {
3809 flags |= eTraversalNeeded;
3810 }
3811 }
3812 if (what & layer_state_t::eAlphaChanged) {
3813 if (layer->setAlpha(s.alpha))
3814 flags |= eTraversalNeeded;
3815 }
3816 if (what & layer_state_t::eColorChanged) {
3817 if (layer->setColor(s.color))
3818 flags |= eTraversalNeeded;
3819 }
Peiyong Lind3788632018-09-18 16:01:31 -07003820 if (what & layer_state_t::eColorTransformChanged) {
3821 if (layer->setColorTransform(s.colorTransform)) {
3822 flags |= eTraversalNeeded;
3823 }
3824 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003825 if (what & layer_state_t::eBackgroundColorChanged) {
3826 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3827 flags |= eTraversalNeeded;
3828 }
3829 }
chaviw8b3871a2017-11-01 17:41:01 -07003830 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003831 // TODO: b/109894387
3832 //
3833 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3834 // rotation. To see the problem observe that if we have a square parent, and a child
3835 // of the same size, then we rotate the child 45 degrees around it's center, the child
3836 // must now be cropped to a non rectangular 8 sided region.
3837 //
3838 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3839 // private API, and the WindowManager only uses rotation in one case, which is on a top
3840 // level layer in which cropping is not an issue.
3841 //
3842 // However given that abuse of rotation matrices could lead to surfaces extending outside
3843 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3844 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3845 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003846 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003847 flags |= eTraversalNeeded;
3848 }
3849 if (what & layer_state_t::eTransparentRegionChanged) {
3850 if (layer->setTransparentRegionHint(s.transparentRegion))
3851 flags |= eTraversalNeeded;
3852 }
3853 if (what & layer_state_t::eFlagsChanged) {
3854 if (layer->setFlags(s.flags, s.mask))
3855 flags |= eTraversalNeeded;
3856 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003857 if (what & layer_state_t::eCropChanged_legacy) {
3858 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003859 flags |= eTraversalNeeded;
3860 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003861 if (what & layer_state_t::eCornerRadiusChanged) {
3862 if (layer->setCornerRadius(s.cornerRadius))
3863 flags |= eTraversalNeeded;
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 if (what & layer_state_t::eLayerStackChanged) {
3866 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3867 // We only allow setting layer stacks for top level layers,
3868 // everything else inherits layer stack from its parent.
3869 if (layer->hasParent()) {
3870 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3871 layer->getName().string());
3872 } else if (idx < 0) {
3873 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3874 "that also does not appear in the top level layer list. Something"
3875 " has gone wrong.", layer->getName().string());
3876 } else if (layer->setLayerStack(s.layerStack)) {
3877 mCurrentState.layersSortedByZ.removeAt(idx);
3878 mCurrentState.layersSortedByZ.add(layer);
3879 // we need traversal (state changed)
3880 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003881 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003882 }
3883 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003884 if (what & layer_state_t::eDeferTransaction_legacy) {
3885 if (s.barrierHandle_legacy != nullptr) {
3886 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3887 } else if (s.barrierGbp_legacy != nullptr) {
3888 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003889 if (authenticateSurfaceTextureLocked(gbp)) {
3890 const auto& otherLayer =
3891 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003892 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003893 } else {
3894 ALOGE("Attempt to defer transaction to to an"
3895 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003896 }
3897 }
chaviw8b3871a2017-11-01 17:41:01 -07003898 // We don't trigger a traversal here because if no other state is
3899 // changed, we don't want this to cause any more work
3900 }
3901 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003902 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003903 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003904 if (!hadParent) {
3905 mCurrentState.layersSortedByZ.remove(layer);
3906 }
chaviw8b3871a2017-11-01 17:41:01 -07003907 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003908 }
chaviw8b3871a2017-11-01 17:41:01 -07003909 }
3910 if (what & layer_state_t::eReparentChildren) {
3911 if (layer->reparentChildren(s.reparentHandle)) {
3912 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003913 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003914 }
chaviw8b3871a2017-11-01 17:41:01 -07003915 if (what & layer_state_t::eDetachChildren) {
3916 layer->detachChildren();
3917 }
3918 if (what & layer_state_t::eOverrideScalingModeChanged) {
3919 layer->setOverrideScalingMode(s.overrideScalingMode);
3920 // We don't trigger a traversal here because if no other state is
3921 // changed, we don't want this to cause any more work
3922 }
Marissa Wall61c58622018-07-18 10:12:20 -07003923 if (what & layer_state_t::eTransformChanged) {
3924 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3925 }
3926 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3927 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3928 flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eCropChanged) {
3931 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3932 }
Marissa Wall861616d2018-10-22 12:52:23 -07003933 if (what & layer_state_t::eFrameChanged) {
3934 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3935 }
Marissa Wall61c58622018-07-18 10:12:20 -07003936 if (what & layer_state_t::eAcquireFenceChanged) {
3937 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eDataspaceChanged) {
3940 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eHdrMetadataChanged) {
3943 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3946 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eApiChanged) {
3949 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eSidebandStreamChanged) {
3952 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3953 }
Robert Carr720e5062018-07-30 17:45:14 -07003954 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003955 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3956 layer->setInputInfo(s.inputInfo);
3957 flags |= eTraversalNeeded;
3958 } else {
3959 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3960 }
Robert Carr720e5062018-07-30 17:45:14 -07003961 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003962 if (what & layer_state_t::eMetadataChanged) {
3963 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3964 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003965 std::vector<sp<CallbackHandle>> callbackHandles;
3966 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3967 mTransactionCompletedThread.run();
3968 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3969 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3970 }
3971 }
Marissa Wall73411622019-01-25 10:45:41 -08003972
3973 if (what & layer_state_t::eBufferChanged) {
3974 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3975 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3976 s.buffer);
3977 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003978 if (what & layer_state_t::eCachedBufferChanged) {
3979 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003980 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3981 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003982 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3983 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003984 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3985 // Do not put anything that updates layer state or modifies flags after
3986 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003987 return flags;
3988}
3989
chaviw273171b2018-12-26 11:46:30 -08003990uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3991 uint32_t flags = 0;
3992 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3993 flags |= eTraversalNeeded;
3994 }
3995
chaviwa911b102019-02-14 10:18:33 -08003996 if (inputWindowCommands.syncInputWindows) {
3997 flags |= eTraversalNeeded;
3998 }
3999
Vishnu Nairec0ab382019-02-13 15:32:56 -08004000 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004001 return flags;
4002}
4003
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004004status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4005 uint32_t h, PixelFormat format, uint32_t flags,
4006 LayerMetadata metadata, sp<IBinder>* handle,
4007 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004008 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004009 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004010 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004012 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004013
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004014 status_t result = NO_ERROR;
4015
4016 sp<Layer> layer;
4017
Cody Northropbc755282017-03-31 12:00:08 -06004018 String8 uniqueName = getUniqueLayerName(name);
4019
Mathias Agopian3165cc22012-08-08 19:42:09 -07004020 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004021 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004022 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4023 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004026 case ISurfaceComposerClient::eFXSurfaceBufferState:
4027 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4028 break;
chaviw13fdc492017-06-27 12:40:18 -07004029 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004030 // check if buffer size is set for color layer.
4031 if (w > 0 || h > 0) {
4032 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4033 int(w), int(h));
4034 return BAD_VALUE;
4035 }
4036
chaviw13fdc492017-06-27 12:40:18 -07004037 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004038 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004039 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004040 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004041 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004042 // check if buffer size is set for container layer.
4043 if (w > 0 || h > 0) {
4044 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4045 int(w), int(h));
4046 return BAD_VALUE;
4047 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004048 result = createContainerLayer(client,
4049 uniqueName, w, h, flags,
4050 handle, &layer);
4051 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004052 default:
4053 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 break;
4055 }
4056
Dan Stoza7d89d062015-04-30 13:29:25 -07004057 if (result != NO_ERROR) {
4058 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004060
Chia-I Wuab0c3192017-08-01 11:29:00 -07004061 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4062 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004063 if (metadata.has(METADATA_WINDOW_TYPE)) {
4064 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4065 if (windowType == 441731) {
4066 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4067 layer->setPrimaryDisplayOnly();
4068 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004069 }
4070
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004071 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004072
Robert Carrb89ea9d2018-12-10 13:01:14 -08004073 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4074 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4075 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004076 if (result != NO_ERROR) {
4077 return result;
4078 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004079 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004080
4081 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004082 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083}
4084
Cody Northropbc755282017-03-31 12:00:08 -06004085String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4086{
4087 bool matchFound = true;
4088 uint32_t dupeCounter = 0;
4089
4090 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4091 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4092
Dan Stoza436ccf32018-06-21 12:10:12 -07004093 // Grab the state lock since we're accessing mCurrentState
4094 Mutex::Autolock lock(mStateLock);
4095
Cody Northropbc755282017-03-31 12:00:08 -06004096 // Loop over layers until we're sure there is no matching name
4097 while (matchFound) {
4098 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004099 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004100 if (layer->getName() == uniqueName) {
4101 matchFound = true;
4102 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4103 }
4104 });
4105 }
4106
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004107 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4108 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004109
4110 return uniqueName;
4111}
4112
Marissa Wallfd668622018-05-10 10:21:13 -07004113status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4114 uint32_t w, uint32_t h, uint32_t flags,
4115 PixelFormat& format, sp<IBinder>* handle,
4116 sp<IGraphicBufferProducer>* gbp,
4117 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004119 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 case PIXEL_FORMAT_TRANSPARENT:
4121 case PIXEL_FORMAT_TRANSLUCENT:
4122 format = PIXEL_FORMAT_RGBA_8888;
4123 break;
4124 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004125 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 break;
4127 }
4128
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004129 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004130 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004131 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004132 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004133 *handle = layer->getHandle();
4134 *gbp = layer->getProducer();
4135 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004137
Marissa Wallfd668622018-05-10 10:21:13 -07004138 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004139 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140}
4141
Marissa Wall61c58622018-07-18 10:12:20 -07004142status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4143 uint32_t w, uint32_t h, uint32_t flags,
4144 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004145 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004146 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004147 *handle = layer->getHandle();
4148 *outLayer = layer;
4149
4150 return NO_ERROR;
4151}
4152
chaviw13fdc492017-06-27 12:40:18 -07004153status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004155 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004157 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004158 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004159 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004160}
4161
Robert Carr6b3f6c52018-08-13 13:05:17 -07004162status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4163 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4164 sp<IBinder>* handle, sp<Layer>* outLayer)
4165{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004166 *outLayer =
4167 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004168 *handle = (*outLayer)->getHandle();
4169 return NO_ERROR;
4170}
4171
4172
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004173void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004174 mLayersPendingRemoval.add(layer);
4175 mLayersRemoved = true;
4176 setTransactionFlags(eTransactionNeeded);
4177}
4178
Robert Carr695d5282018-12-18 15:27:58 -08004179void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004180{
Robert Carr2e102c92018-10-23 12:11:15 -07004181 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004182 // If a layer has a parent, we allow it to out-live it's handle
4183 // with the idea that the parent holds a reference and will eventually
4184 // be cleaned up. However no one cleans up the top-level so we do so
4185 // here.
4186 if (layer->getParent() == nullptr) {
4187 mCurrentState.layersSortedByZ.remove(layer);
4188 }
4189 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004190 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004191}
4192
Mathias Agopianb60314a2012-04-10 22:09:54 -07004193// ---------------------------------------------------------------------------
4194
Andy McFadden13a082e2012-08-24 10:16:42 -07004195void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004196 const auto display = getDefaultDisplayDeviceLocked();
4197 if (!display) return;
4198
4199 const sp<IBinder> token = display->getDisplayToken().promote();
4200 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004201
Jesse Hall01e29052013-02-19 16:13:35 -08004202 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004203 Vector<ComposerState> state;
4204 Vector<DisplayState> displays;
4205 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004206 d.what = DisplayState::eDisplayProjectionChanged |
4207 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004208 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004209 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004210 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004211 d.frame.makeInvalid();
4212 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004213 d.width = 0;
4214 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004215 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004216 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004217
Dominik Laskowskie9774092018-12-11 10:04:24 -08004218 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004219
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 const nsecs_t vsyncPeriod = getVsyncPeriod();
4221 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004222
Brian Andersond0010582017-03-07 13:20:31 -08004223 // Use phase of 0 since phase is not known.
4224 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004225 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004226 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004227}
4228
4229void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004230 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004231 postMessageAsync(
4232 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004233}
4234
Dominik Laskowskie9774092018-12-11 10:04:24 -08004235void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004236 if (display->isVirtual()) {
4237 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004238 return;
4239 }
4240
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241 const auto displayId = display->getId();
4242 LOG_ALWAYS_FATAL_IF(!displayId);
4243
Dominik Laskowski34157762018-10-31 13:07:19 -07004244 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004245
4246 int currentMode = display->getPowerMode();
4247 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004248 return;
4249 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004250
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004251 display->setPowerMode(mode);
4252
Lloyd Pique4dccc412018-01-22 17:21:36 -08004253 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004254 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004255 }
4256
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004257 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004258 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004260 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004261 mScheduler->onScreenAcquired(mAppConnectionHandle);
4262 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004263 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004264
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004266 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004267 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004268
4269 struct sched_param param = {0};
4270 param.sched_priority = 1;
4271 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4272 ALOGW("Couldn't set SCHED_FIFO on display on");
4273 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004274 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004275 // Turn off the display
4276 struct sched_param param = {0};
4277 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4278 ALOGW("Couldn't set SCHED_OTHER on display off");
4279 }
4280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004282 mScheduler->disableHardwareVsync(true);
4283 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004284 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285
Dominik Laskowski075d3172018-05-24 15:50:06 -07004286 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004287 mVisibleRegionsDirty = true;
4288 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004289 } else if (mode == HWC_POWER_MODE_DOZE ||
4290 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004291 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004294 mScheduler->onScreenAcquired(mAppConnectionHandle);
4295 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004296 }
4297 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4298 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004300 mScheduler->disableHardwareVsync(true);
4301 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004302 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004305 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004306 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004307 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004309 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004310 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004311 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004312 // Update refresh rate stats.
4313 mRefreshRateStats->setPowerMode(mode);
4314 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004315 }
4316
Dominik Laskowski34157762018-10-31 13:07:19 -07004317 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004318}
4319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004321 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004322 const auto display = getDisplayDevice(displayToken);
4323 if (!display) {
4324 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4325 displayToken.get());
4326 } else if (display->isVirtual()) {
4327 ALOGW("Attempt to set power mode %d for virtual display", mode);
4328 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004329 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004330 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004332}
4333
4334// ---------------------------------------------------------------------------
4335
Dominik Laskowskic2867142019-01-21 11:33:38 -08004336status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4337 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004338 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004339
Mathias Agopianbd115332013-04-18 16:41:04 -07004340 IPCThreadState* ipc = IPCThreadState::self();
4341 const int pid = ipc->getCallingPid();
4342 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004343
Mathias Agopianbd115332013-04-18 16:41:04 -07004344 if ((uid != AID_SHELL) &&
4345 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004346 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4347 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004349 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004350 // (this would indicate SF is stuck, but we want to be able to
4351 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004352 status_t err = mStateLock.timedLock(s2ns(1));
4353 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004354 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355 StringAppendF(&result,
4356 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4357 "(no locks held)\n",
4358 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004359 }
4360
Dominik Laskowskic2867142019-01-21 11:33:38 -08004361 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004362
Dominik Laskowskic2867142019-01-21 11:33:38 -08004363 static const std::unordered_map<std::string, Dumper> dumpers = {
4364 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4365 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4366 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004367 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004368 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004369 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004370 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4371 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004372 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4373 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4374 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4375 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4376 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4377 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004378 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4380 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004381
Dominik Laskowskic2867142019-01-21 11:33:38 -08004382 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004383
Dominik Laskowskic2867142019-01-21 11:33:38 -08004384 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4385 (it->second)(args, asProto, result);
4386 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004387 if (asProto) {
4388 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4389 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4390 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004391 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004392 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004393 }
4394
Mathias Agopian9795c422009-08-26 16:36:26 -07004395 if (locked) {
4396 mStateLock.unlock();
4397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004399 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004400 return NO_ERROR;
4401}
4402
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404 mCurrentState.traverseInZOrder(
4405 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004406}
4407
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004409 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004410
Dominik Laskowskic2867142019-01-21 11:33:38 -08004411 if (args.size() > 1) {
4412 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004413 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004414 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004415 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004416 }
Robert Carr2047fae2016-11-28 14:09:09 -08004417 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 } else {
4419 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420 }
4421}
4422
Dominik Laskowskic2867142019-01-21 11:33:38 -08004423void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004424 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004426 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004427 }
Robert Carr2047fae2016-11-28 14:09:09 -08004428 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004429
Svetoslavd85084b2014-03-20 10:28:31 -07004430 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004431}
4432
Dominik Laskowskic2867142019-01-21 11:33:38 -08004433void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4434 mTimeStats->parseArgs(asProto, args, result);
4435}
4436
Jamie Gennis6547ff42013-07-16 20:12:42 -07004437// This should only be called from the main thread. Otherwise it would need
4438// the lock and should use mCurrentState rather than mDrawingState.
4439void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004440 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004441 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004442 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004443
4444 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4445}
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004448 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004449
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004450 if (isLayerTripleBufferingDisabled())
4451 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004452
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4454 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4455 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4456 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4457 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4458 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004459 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004460}
4461
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004462void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004463 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004464 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004465 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004466 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004467
Ana Krulecc2870422019-01-29 19:00:58 -08004468 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n\n", mUse90Hz ? "on" : "off");
4469 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004470}
4471
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4473 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004474 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4475 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004476 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004477 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004479 }
David Sodman4a36e932017-11-07 14:29:47 -08004480 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004481 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004482 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004483 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4484 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004485}
4486
Dan Stozae77c7662016-05-13 11:37:28 -07004487void SurfaceFlinger::recordBufferingStats(const char* layerName,
4488 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004489 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4490 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004491 for (const auto& segment : history) {
4492 if (!segment.usedThirdBuffer) {
4493 stats.twoBufferTime += segment.totalTime;
4494 }
4495 if (segment.occupancyAverage < 1.0f) {
4496 stats.doubleBufferedTime += segment.totalTime;
4497 } else if (segment.occupancyAverage < 2.0f) {
4498 stats.tripleBufferedTime += segment.totalTime;
4499 }
4500 ++stats.numSegments;
4501 stats.totalTime += segment.totalTime;
4502 }
4503}
4504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4506 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004507
4508 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4509 const size_t count = currentLayers.size();
4510 for (size_t i=0 ; i<count ; i++) {
4511 currentLayers[i]->dumpFrameEvents(result);
4512 }
4513}
4514
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004516 result.append("Buffering stats:\n");
4517 result.append(" [Layer name] <Active time> <Two buffer> "
4518 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004519 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004520 typedef std::tuple<std::string, float, float, float> BufferTuple;
4521 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004522 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004523 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004524 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004525 if (stats.numSegments == 0) {
4526 continue;
4527 }
4528 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4529 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4530 stats.totalTime;
4531 float doubleBufferRatio = static_cast<float>(
4532 stats.doubleBufferedTime) / stats.totalTime;
4533 float tripleBufferRatio = static_cast<float>(
4534 stats.tripleBufferedTime) / stats.totalTime;
4535 sorted.insert({activeTime, {name, twoBufferRatio,
4536 doubleBufferRatio, tripleBufferRatio}});
4537 }
4538 for (const auto& sortedPair : sorted) {
4539 float activeTime = sortedPair.first;
4540 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4542 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004543 }
4544 result.append("\n");
4545}
4546
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004548 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004549 const auto displayId = display->getId();
4550 if (!displayId) {
4551 continue;
4552 }
4553 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004554 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004555 continue;
4556 }
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result,
4559 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4560 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 uint8_t port;
4562 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004563 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564 result.append("no identification data\n");
4565 continue;
4566 }
4567
4568 if (!isEdid(data)) {
4569 result.append("unknown identification data: ");
4570 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004571 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004572 }
4573 result.append("\n");
4574 continue;
4575 }
4576
4577 const auto edid = parseEdid(data);
4578 if (!edid) {
4579 result.append("invalid EDID: ");
4580 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004582 }
4583 result.append("\n");
4584 continue;
4585 }
4586
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004588 result.append(edid->displayName.data(), edid->displayName.length());
4589 result.append("\"\n");
4590 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004591}
4592
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4594 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4595 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4596 StringAppendF(&result, "DisplayColorSetting: %s\n",
4597 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004598
4599 // TODO: print out if wide-color mode is active or not
4600
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004601 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004602 const auto displayId = display->getId();
4603 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604 continue;
4605 }
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004608 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004609 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004611 }
4612
Lloyd Pique32cbe282018-10-19 13:09:22 -07004613 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614 StringAppendF(&result, " Current color mode: %s (%d)\n",
4615 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004616 }
4617 result.append("\n");
4618}
4619
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004620LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004621 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004622 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4623 const State& state = useDrawing ? mDrawingState : mCurrentState;
4624 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004625 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004626 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004627 });
4628
4629 return layersProto;
4630}
4631
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004632LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4633 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004634 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004635
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004636 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004637 resolution->set_w(displayDevice->getWidth());
4638 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004639
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004640 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004641 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004642
Lloyd Pique32cbe282018-10-19 13:09:22 -07004643 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4644 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4645 layersProto.set_global_transform(displayState.orientation);
4646
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004647 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004648 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004649 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004650 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004651 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004652 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004653 }
4654 });
4655
4656 return layersProto;
4657}
4658
Dominik Laskowskic2867142019-01-21 11:33:38 -08004659void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4660 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661 Colorizer colorizer(colorize);
4662
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004663 // figure out if we're stuck somewhere
4664 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004666 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4667
4668 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004669 * Dump library configuration.
4670 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004671
4672 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004673 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004674 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004675 appendSfConfigString(result);
4676 appendUiConfigString(result);
4677 appendGuiConfigString(result);
4678 result.append("\n");
4679
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004680 result.append("\nDisplay identification data:\n");
4681 dumpDisplayIdentificationData(result);
4682
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004683 result.append("\nWide-Color information:\n");
4684 dumpWideColorInfo(result);
4685
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004686 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004687 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004689 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004690 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004691
Andy McFadden41d67d72014-04-25 16:58:34 -07004692 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004693 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004694 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004695 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004696 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004697
Dan Stozab90cf072015-03-05 11:05:59 -08004698 dumpStaticScreenStats(result);
4699 result.append("\n");
4700
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004702
Dan Stozae77c7662016-05-13 11:37:28 -07004703 dumpBufferingStats(result);
4704
Andy McFadden4803b742012-09-24 19:07:20 -07004705 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004706 * Dump the visible layer list
4707 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4710 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4711 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004713
Chia-I Wu2f884132018-09-13 15:17:58 -07004714 {
4715 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4716 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004718 result.append("\n");
4719 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720
4721 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004722 * Dump Display state
4723 */
4724
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004725 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004727 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004729 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004730 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004731 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004732
4733 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 * Dump SurfaceFlinger global state
4735 */
4736
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004737 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004738 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004740
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004741 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004744 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4745 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4747 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004748 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result,
4750 " transaction-flags : %08x\n"
4751 " gpu_to_cpu_unsupported : %d\n",
4752 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004753
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004754 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004755 displayId && getHwComposer().isConnected(*displayId)) {
4756 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result,
4758 " refresh-rate : %f fps\n"
4759 " x-dpi : %f\n"
4760 " y-dpi : %f\n",
4761 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4762 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004763 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004764
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004766
Dan Stozae22aec72016-08-01 13:20:59 -07004767 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004768 * Tracing state
4769 */
4770 mTracing.dump(result);
4771 result.append("\n");
4772
4773 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004774 * HWC layer minidump
4775 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004776 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004777 const auto displayId = display->getId();
4778 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004779 continue;
4780 }
4781
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004783 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004784 const sp<DisplayDevice> displayDevice = display;
4785 mCurrentState.traverseInZOrder(
4786 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004787 result.append("\n");
4788 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004789
4790 /*
4791 * Dump HWComposer state
4792 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004793 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004794 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004795 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004796 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004797 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004798 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799
4800 /*
4801 * Dump gralloc state
4802 */
4803 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4804 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004805
4806 /*
4807 * Dump VrFlinger state if in use.
4808 */
4809 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4810 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004812 result.append("\n");
4813 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004814
4815 /**
4816 * Scheduler dump state.
4817 */
Ana Krulecc2870422019-01-29 19:00:58 -08004818 result.append("\nScheduler state:\n");
4819 result.append(mScheduler->doDump() + "\n");
4820 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004821}
4822
Dominik Laskowski075d3172018-05-24 15:50:06 -07004823const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004824 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004825 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004826 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004827 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004828 }
4829 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004830
Dominik Laskowski34157762018-10-31 13:07:19 -07004831 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004832 static const Vector<sp<Layer>> empty;
4833 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004834}
4835
Chia-I Wu28f320b2018-05-03 11:02:56 -07004836void SurfaceFlinger::updateColorMatrixLocked() {
4837 mat4 colorMatrix;
4838 if (mGlobalSaturationFactor != 1.0f) {
4839 // Rec.709 luma coefficients
4840 float3 luminance{0.213f, 0.715f, 0.072f};
4841 luminance *= 1.0f - mGlobalSaturationFactor;
4842 mat4 saturationMatrix = mat4(
4843 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4844 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4845 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4846 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4847 );
4848 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4849 } else {
4850 colorMatrix = mClientColorMatrix * mDaltonizer();
4851 }
4852
4853 if (mCurrentState.colorMatrix != colorMatrix) {
4854 mCurrentState.colorMatrix = colorMatrix;
4855 mCurrentState.colorMatrixChanged = true;
4856 setTransactionFlags(eTransactionNeeded);
4857 }
4858}
4859
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004860status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861#pragma clang diagnostic push
4862#pragma clang diagnostic error "-Wswitch-enum"
4863 switch (static_cast<ISurfaceComposerTag>(code)) {
4864 // These methods should at minimum make sure that the client requested
4865 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004866 case BOOT_FINISHED:
4867 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 case CREATE_DISPLAY:
4869 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004870 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004871 case GET_ACTIVE_COLOR_MODE:
4872 case GET_ANIMATION_FRAME_STATS:
4873 case GET_HDR_CAPABILITIES:
4874 case SET_ACTIVE_CONFIG:
4875 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004876 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004877 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004878 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004879 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4880 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004881 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4882 IPCThreadState* ipc = IPCThreadState::self();
4883 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4884 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004885 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 }
Robert Carr1db73f62016-12-21 12:58:51 -08004887 return OK;
4888 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004890 IPCThreadState* ipc = IPCThreadState::self();
4891 const int pid = ipc->getCallingPid();
4892 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4894 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004895 return PERMISSION_DENIED;
4896 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004898 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004899 // Used by apps to hook Choreographer to SurfaceFlinger.
4900 case CREATE_DISPLAY_EVENT_CONNECTION:
4901 // The following calls are currently used by clients that do not
4902 // request necessary permissions. However, they do not expose any secret
4903 // information, so it is OK to pass them.
4904 case AUTHENTICATE_SURFACE:
4905 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004906 case GET_PHYSICAL_DISPLAY_IDS:
4907 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004909 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 case GET_DISPLAY_CONFIGS:
4911 case GET_DISPLAY_STATS:
4912 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4913 // Calling setTransactionState is safe, because you need to have been
4914 // granted a reference to Client* and Handle* to do anything with it.
4915 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004916 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004917 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004918 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004919 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004920 case IS_WIDE_COLOR_DISPLAY:
4921 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 return OK;
4923 }
4924 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004925 case CAPTURE_SCREEN:
4926 case ADD_REGION_SAMPLING_LISTENER:
4927 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004928 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004929 IPCThreadState* ipc = IPCThreadState::self();
4930 const int pid = ipc->getCallingPid();
4931 const int uid = ipc->getCallingUid();
4932 if ((uid != AID_GRAPHICS) &&
4933 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4934 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4935 return PERMISSION_DENIED;
4936 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 return OK;
4938 }
4939 // The following codes are deprecated and should never be allowed to access SF.
4940 case CONNECT_DISPLAY_UNUSED:
4941 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4942 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4943 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004945 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946
4947 // These codes are used for the IBinder protocol to either interrogate the recipient
4948 // side of the transaction for its canonical interface descriptor or to dump its state.
4949 // We let them pass by default.
4950 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4951 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4952 code == IBinder::SYSPROPS_TRANSACTION) {
4953 return OK;
4954 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004955 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004957 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004958 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4959 return OK;
4960 }
4961 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4962 return PERMISSION_DENIED;
4963#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004964}
4965
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4967 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004968 status_t credentialCheck = CheckTransactCodeCredentials(code);
4969 if (credentialCheck != OK) {
4970 return credentialCheck;
4971 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004972
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4974 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004975 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004976 IPCThreadState* ipc = IPCThreadState::self();
4977 const int uid = ipc->getCallingUid();
4978 if (CC_UNLIKELY(uid != AID_SYSTEM
4979 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004980 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004981 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004982 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 return PERMISSION_DENIED;
4984 }
4985 int n;
4986 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004987 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004988 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 return NO_ERROR;
4990 case 1002: // SHOW_UPDATES
4991 n = data.readInt32();
4992 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004993 invalidateHwcGeometry();
4994 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004995 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004996 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004997 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004998 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005000 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005001 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005002 setTransactionFlags(
5003 eTransactionNeeded|
5004 eDisplayTransactionNeeded|
5005 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005006 return NO_ERROR;
5007 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005008 case 1006:{ // send empty update
5009 signalRefresh();
5010 return NO_ERROR;
5011 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005012 case 1008: // toggle use of hw composer
5013 n = data.readInt32();
5014 mDebugDisableHWC = n ? 1 : 0;
5015 invalidateHwcGeometry();
5016 repaintEverything();
5017 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005018 case 1009: // toggle use of transform hint
5019 n = data.readInt32();
5020 mDebugDisableTransformHint = n ? 1 : 0;
5021 invalidateHwcGeometry();
5022 repaintEverything();
5023 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005025 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005026 reply->writeInt32(0);
5027 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005028 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005029 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 return NO_ERROR;
5031 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005032 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005033 if (!display) {
5034 return NAME_NOT_FOUND;
5035 }
5036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005037 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005038 return NO_ERROR;
5039 }
5040 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005041 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005042 // daltonize
5043 n = data.readInt32();
5044 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005045 case 1:
5046 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5047 break;
5048 case 2:
5049 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5050 break;
5051 case 3:
5052 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5053 break;
5054 default:
5055 mDaltonizer.setType(ColorBlindnessType::None);
5056 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005057 }
5058 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005059 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005060 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005061 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005062 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005063
5064 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005065 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005067 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005068 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005069 // apply a color matrix
5070 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005072 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005073 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005074 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005075 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005076 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005077 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005078 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005079 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005080 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005081
5082 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5083 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005085 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5086 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5087 }
5088
Chia-I Wu28f320b2018-05-03 11:02:56 -07005089 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005090 return NO_ERROR;
5091 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005092 // This is an experimental interface
5093 // Needs to be shifted to proper binder interface when we productize
5094 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005095 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005096 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005097 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005098 return NO_ERROR;
5099 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005100 case 1017: {
5101 n = data.readInt32();
5102 mForceFullDamage = static_cast<bool>(n);
5103 return NO_ERROR;
5104 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005105 case 1018: { // Modify Choreographer's phase offset
5106 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005107 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005108 return NO_ERROR;
5109 }
5110 case 1019: { // Modify SurfaceFlinger's phase offset
5111 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005112 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005113 return NO_ERROR;
5114 }
Irvel468051e2016-06-13 16:44:44 -07005115 case 1020: { // Layer updates interceptor
5116 n = data.readInt32();
5117 if (n) {
5118 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005119 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005120 }
5121 else{
5122 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005123 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005124 }
5125 return NO_ERROR;
5126 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005127 case 1021: { // Disable HWC virtual displays
5128 n = data.readInt32();
5129 mUseHwcVirtualDisplays = !n;
5130 return NO_ERROR;
5131 }
Romain Guy0147a172017-06-01 13:53:56 -07005132 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005133 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005134 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005135
Chia-I Wu28f320b2018-05-03 11:02:56 -07005136 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005137 return NO_ERROR;
5138 }
Romain Guy54f154a2017-10-24 21:40:32 +01005139 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005140 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005141 invalidateHwcGeometry();
5142 repaintEverything();
5143 return NO_ERROR;
5144 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005145 // Deprecate, use 1030 to check whether the device is color managed.
5146 case 1024: {
5147 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005148 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005149 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005150 n = data.readInt32();
5151 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005152 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005153 mTracing.enable();
5154 doTracing("tracing.enable");
5155 reply->writeInt32(NO_ERROR);
5156 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005157 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005158 status_t err = mTracing.disable();
5159 reply->writeInt32(err);
5160 }
5161 return NO_ERROR;
5162 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005163 case 1026: { // Get layer tracing status
5164 reply->writeBool(mTracing.isEnabled());
5165 return NO_ERROR;
5166 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005167 // Is a DisplayColorSetting supported?
5168 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005169 const auto display = getDefaultDisplayDevice();
5170 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005171 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005172 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005173
5174 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5175 switch (setting) {
5176 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005177 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005178 break;
5179 case DisplayColorSetting::UNMANAGED:
5180 reply->writeBool(true);
5181 break;
5182 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005183 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005184 break;
5185 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005186 reply->writeBool(
5187 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005188 break;
5189 }
5190 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005191 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005192 // Is VrFlinger active?
5193 case 1028: {
5194 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005195 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005196 return NO_ERROR;
5197 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005198 // Is device color managed?
5199 case 1030: {
5200 reply->writeBool(useColorManagement);
5201 return NO_ERROR;
5202 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005203 // Override default composition data space
5204 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5205 // && adb shell stop zygote && adb shell start zygote
5206 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5207 // adb shell stop zygote && adb shell start zygote
5208 case 1031: {
5209 Mutex::Autolock _l(mStateLock);
5210 n = data.readInt32();
5211 if (n) {
5212 n = data.readInt32();
5213 if (n) {
5214 Dataspace dataspace = static_cast<Dataspace>(n);
5215 if (!validateCompositionDataspace(dataspace)) {
5216 return BAD_VALUE;
5217 }
5218 mDefaultCompositionDataspace = dataspace;
5219 }
5220 n = data.readInt32();
5221 if (n) {
5222 Dataspace dataspace = static_cast<Dataspace>(n);
5223 if (!validateCompositionDataspace(dataspace)) {
5224 return BAD_VALUE;
5225 }
5226 mWideColorGamutCompositionDataspace = dataspace;
5227 }
5228 } else {
5229 // restore composition data space.
5230 mDefaultCompositionDataspace = defaultCompositionDataspace;
5231 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5232 }
5233 return NO_ERROR;
5234 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005235 }
5236 }
5237 return err;
5238}
5239
Steven Thomas6d8110b2017-08-31 18:24:21 -07005240void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005241 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005242 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005243}
5244
Ana Krulec7d1d6832018-12-27 11:10:09 -08005245void SurfaceFlinger::repaintEverythingForHWC() {
5246 mRepaintEverything = true;
5247 mEventQueue->invalidateForHWC();
5248}
5249
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005250// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5251class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005252public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005253 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5254 ~WindowDisconnector() {
5255 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005256 }
5257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258private:
5259 ANativeWindow* mWindow;
5260 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005261};
5262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005263status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005264 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5265 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005266 uint32_t reqWidth, uint32_t reqHeight,
5267 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005268 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005269 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005271 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005272
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005273 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5274
Chia-I Wu20261cb2018-08-23 12:55:44 -07005275 sp<DisplayDevice> display;
5276 {
5277 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005278
Chia-I Wu20261cb2018-08-23 12:55:44 -07005279 display = getDisplayDeviceLocked(displayToken);
5280 if (!display) return BAD_VALUE;
5281
Chia-I Wucb023152018-08-28 12:57:23 -07005282 // set the requested width/height to the logical display viewport size
5283 // by default
5284 if (reqWidth == 0 || reqHeight == 0) {
5285 reqWidth = uint32_t(display->getViewport().width());
5286 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005287 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005288 }
5289
Peiyong Lin0e003c92018-09-17 11:09:51 -07005290 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5291 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005292
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005293 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5294 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005295 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5296 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005297}
5298
5299status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005300 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5301 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005302 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005303 ATRACE_CALL();
5304
5305 class LayerRenderArea : public RenderArea {
5306 public:
Robert Carr578038f2018-03-09 12:25:24 -08005307 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005308 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5309 bool childrenOnly)
5310 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005311 mLayer(layer),
5312 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005313 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005314 mFlinger(flinger),
5315 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005316 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005317 Rect getBounds() const override {
5318 const Layer::State& layerState(mLayer->getDrawingState());
5319 return mLayer->getBufferSize(layerState);
5320 }
Marissa Wall61c58622018-07-18 10:12:20 -07005321 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005322 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005323 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005324 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005325 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005326 }
chaviwa76b2712017-09-20 12:02:26 -07005327 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005328 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005329 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005330 Rect getSourceCrop() const override {
5331 if (mCrop.isEmpty()) {
5332 return getBounds();
5333 } else {
5334 return mCrop;
5335 }
5336 }
Robert Carr578038f2018-03-09 12:25:24 -08005337 class ReparentForDrawing {
5338 public:
5339 const sp<Layer>& oldParent;
5340 const sp<Layer>& newParent;
5341
Vishnu Nair4351ad52019-02-11 14:13:02 -08005342 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5343 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005344 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005345 // Compute and cache the bounds for the new parent layer.
5346 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005347 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005348 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005349 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005350 };
5351
5352 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005353 const Rect sourceCrop = getSourceCrop();
5354 // no need to check rotation because there is none
5355 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5356 sourceCrop.height() != getReqHeight();
5357
Robert Carr578038f2018-03-09 12:25:24 -08005358 if (!mChildrenOnly) {
5359 mTransform = mLayer->getTransform().inverse();
5360 drawLayers();
5361 } else {
5362 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005363 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005364 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5365 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005366
Vishnu Nair4351ad52019-02-11 14:13:02 -08005367 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005368 drawLayers();
5369 }
5370 }
chaviwa76b2712017-09-20 12:02:26 -07005371
chaviwa76b2712017-09-20 12:02:26 -07005372 private:
chaviw7206d492017-11-10 16:16:12 -08005373 const sp<Layer> mLayer;
5374 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005375
5376 // In the "childrenOnly" case we reparent the children to a screenshot
5377 // layer which has no properties set and which does not draw.
5378 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005379 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005380 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005381
5382 SurfaceFlinger* mFlinger;
5383 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005384 };
5385
5386 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5387 auto parent = layerHandle->owner.promote();
5388
Robert Carr2e102c92018-10-23 12:11:15 -07005389 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005390 ALOGE("captureLayers called with a removed parent");
5391 return NAME_NOT_FOUND;
5392 }
5393
Robert Carr578038f2018-03-09 12:25:24 -08005394 const int uid = IPCThreadState::self()->getCallingUid();
5395 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005396 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005397 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5398 return PERMISSION_DENIED;
5399 }
5400
chaviw7206d492017-11-10 16:16:12 -08005401 Rect crop(sourceCrop);
5402 if (sourceCrop.width() <= 0) {
5403 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005404 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005405 }
5406
5407 if (sourceCrop.height() <= 0) {
5408 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005409 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005410 }
5411
5412 int32_t reqWidth = crop.width() * frameScale;
5413 int32_t reqHeight = crop.height() * frameScale;
5414
Chia-I Wu20261cb2018-08-23 12:55:44 -07005415 // really small crop or frameScale
5416 if (reqWidth <= 0) {
5417 reqWidth = 1;
5418 }
5419 if (reqHeight <= 0) {
5420 reqHeight = 1;
5421 }
5422
Peiyong Lin0e003c92018-09-17 11:09:51 -07005423 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005424
Robert Carr578038f2018-03-09 12:25:24 -08005425 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005426 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5427 if (!layer->isVisible()) {
5428 return;
Robert Carr578038f2018-03-09 12:25:24 -08005429 } else if (childrenOnly && layer == parent.get()) {
5430 return;
chaviwa76b2712017-09-20 12:02:26 -07005431 }
5432 visitor(layer);
5433 });
5434 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005436}
5437
5438status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5439 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005440 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005441 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005442 bool useIdentityTransform) {
5443 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005444
Peiyong Lin0e003c92018-09-17 11:09:51 -07005445 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005446 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5447 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005448 *outBuffer =
5449 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5450 static_cast<android_pixel_format>(reqPixelFormat), 1,
5451 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005452
5453 // This mutex protects syncFd and captureResult for communication of the return values from the
5454 // main thread back to this Binder thread
5455 std::mutex captureMutex;
5456 std::condition_variable captureCondition;
5457 std::unique_lock<std::mutex> captureLock(captureMutex);
5458 int syncFd = -1;
5459 std::optional<status_t> captureResult;
5460
Robert Carr03480e22018-01-04 16:02:06 -08005461 const int uid = IPCThreadState::self()->getCallingUid();
5462 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5463
Dominik Laskowski8c001672018-05-30 16:52:06 -07005464 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005465 // If there is a refresh pending, bug out early and tell the binder thread to try again
5466 // after the refresh.
5467 if (mRefreshPending) {
5468 ATRACE_NAME("Skipping screenshot for now");
5469 std::unique_lock<std::mutex> captureLock(captureMutex);
5470 captureResult = std::make_optional<status_t>(EAGAIN);
5471 captureCondition.notify_one();
5472 return;
5473 }
5474
5475 status_t result = NO_ERROR;
5476 int fd = -1;
5477 {
5478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005479 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005480 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5481 useIdentityTransform, forSystem, &fd);
5482 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483 }
5484
5485 {
5486 std::unique_lock<std::mutex> captureLock(captureMutex);
5487 syncFd = fd;
5488 captureResult = std::make_optional<status_t>(result);
5489 captureCondition.notify_one();
5490 }
5491 });
5492
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005493 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005494 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005495 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 while (*captureResult == EAGAIN) {
5497 captureResult.reset();
5498 result = postMessageAsync(message);
5499 if (result != NO_ERROR) {
5500 return result;
5501 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005502 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 }
5504 result = *captureResult;
5505 }
5506
5507 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005508 sync_wait(syncFd, -1);
5509 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005510 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005511
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005512 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005513}
5514
chaviwa76b2712017-09-20 12:02:26 -07005515void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005516 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005517 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5518 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005519 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005520
chaviwa76b2712017-09-20 12:02:26 -07005521 const auto reqWidth = renderArea.getReqWidth();
5522 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005523 const auto sourceCrop = renderArea.getSourceCrop();
5524 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005525
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005526 renderengine::DisplaySettings clientCompositionDisplay;
5527 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005528
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005529 // assume that bounds are never offset, and that they are the same as the
5530 // buffer bounds.
5531 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5532 ui::Transform transform = renderArea.getTransform();
5533 mat4 m;
5534 m[0][0] = transform[0][0];
5535 m[0][1] = transform[0][1];
5536 m[0][3] = transform[0][2];
5537 m[1][0] = transform[1][0];
5538 m[1][1] = transform[1][1];
5539 m[1][3] = transform[1][2];
5540 m[3][0] = transform[2][0];
5541 m[3][1] = transform[2][1];
5542 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005543
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005544 clientCompositionDisplay.globalTransform = m;
5545 mat4 rotMatrix;
5546 // Displacement for repositioning the clipping rectangle after rotating it
5547 // with the rotation hint.
5548 int displacementX = 0;
5549 int displacementY = 0;
5550 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5551 switch (rotation) {
5552 case ui::Transform::ROT_90:
5553 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5554 displacementX = reqWidth;
5555 break;
5556 case ui::Transform::ROT_180:
5557 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5558 displacementX = reqWidth;
5559 displacementY = reqHeight;
5560 break;
5561 case ui::Transform::ROT_270:
5562 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5563 displacementY = reqHeight;
5564 break;
5565 default:
5566 break;
5567 }
5568 // We need to transform the clipping window into the right spot.
5569 // First, rotate the clipping rectangle by the rotation hint to get the
5570 // right orientation
5571 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5572 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5573 const vec4 rotClipTL = rotMatrix * clipTL;
5574 const vec4 rotClipBR = rotMatrix * clipBR;
5575 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5576 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5577 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5578 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5579
5580 // Now reposition the clipping rectangle with the displacement vector
5581 // computed above.
5582 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5583
5584 clientCompositionDisplay.clip =
5585 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5586 newClipRight + displacementX, newClipBottom + displacementY);
5587
5588 // We need to perform the same transformation in layer space, so propagate
5589 // it to the global transform.
5590 mat4 clipTransform = displacementMat * rotMatrix;
5591 clientCompositionDisplay.globalTransform *= clipTransform;
5592 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5593 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005594
chaviw50da5042018-04-09 13:49:37 -07005595 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005596
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005597 renderengine::LayerSettings fillLayer;
5598 fillLayer.source.buffer.buffer = nullptr;
5599 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5600 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5601 fillLayer.alpha = half(alpha);
5602 clientCompositionLayers.push_back(fillLayer);
5603
5604 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005605 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005606 renderengine::LayerSettings layerSettings;
5607 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5608 layerSettings);
5609 if (prepared) {
5610 clientCompositionLayers.push_back(layerSettings);
5611 }
chaviwa76b2712017-09-20 12:02:26 -07005612 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005613
5614 clientCompositionDisplay.clearRegion = clearRegion;
5615 base::unique_fd drawFence;
5616 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5617 &drawFence);
5618
5619 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005620}
5621
chaviwa76b2712017-09-20 12:02:26 -07005622status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5623 TraverseLayersFunction traverseLayers,
5624 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005625 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005626 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005627 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005628 ATRACE_CALL();
5629
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005630 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005631
5632 traverseLayers([&](Layer* layer) {
5633 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5634 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005635
Robert Carr03480e22018-01-04 16:02:06 -08005636 // We allow the system server to take screenshots of secure layers for
5637 // use in situations like the Screen-rotation animation and place
5638 // the impetus on WindowManager to not persist them.
5639 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005640 ALOGW("FB is protected: PERMISSION_DENIED");
5641 return PERMISSION_DENIED;
5642 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005643 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005645}
5646
chaviw5f21a5e2019-02-14 10:00:34 -08005647void SurfaceFlinger::setInputWindowsFinished() {}
5648
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005649// ---------------------------------------------------------------------------
5650
Dan Stoza412903f2017-04-27 13:42:17 -07005651void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5652 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005653}
5654
Dan Stoza412903f2017-04-27 13:42:17 -07005655void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5656 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005657}
5658
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005659void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005660 const LayerVector::Visitor& visitor) {
5661 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005662 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005663 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005664 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005665 continue;
5666 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005667 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005668 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005669 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005670 return;
5671 }
chaviwa76b2712017-09-20 12:02:26 -07005672 if (!layer->isVisible()) {
5673 return;
5674 }
5675 visitor(layer);
5676 });
5677 }
5678}
5679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005680}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005681
Lloyd Pique074e8122018-07-26 12:57:23 -07005682
Mathias Agopian3f844832013-08-07 21:24:32 -07005683#if defined(__gl_h_)
5684#error "don't include gl/gl.h in this file"
5685#endif
5686
5687#if defined(__gl2_h_)
5688#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005689#endif