blob: daa9ff904793de8a514b4a5ab304ae44db9f85fc [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
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800206constexpr float kDefaultRefreshRate = 60.f;
207constexpr float kPerformanceRefreshRate = 90.f;
208
Mathias Agopian99b49842011-06-27 16:05:52 -0700209// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700211bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800212uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800213bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800214bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800215int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600216bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700217int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700218bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700219bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700220Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
221ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
222Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
223ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700224
Kalle Raitaa099a242017-01-11 11:17:29 -0800225std::string getHwcServiceName() {
226 char value[PROPERTY_VALUE_MAX] = {};
227 property_get("debug.sf.hwc_service_name", value, "default");
228 ALOGI("Using HWComposer service: '%s'", value);
229 return std::string(value);
230}
231
232bool useTrebleTestingOverride() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.treble_testing_override", value, "false");
235 ALOGI("Treble testing override: '%s'", value);
236 return std::string(value) == "true";
237}
238
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800239std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
240 switch(displayColorSetting) {
241 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700242 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800243 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700244 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700246 return std::string("Enhanced");
247 default:
248 return std::string("Unknown ") +
249 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251}
252
David Sodmanbc815282017-11-05 18:57:52 -0800253SurfaceFlingerBE::SurfaceFlingerBE()
254 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800255 mFrameBuckets(),
256 mTotalTime(0),
257 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800258 mComposerSequenceId(0) {
259}
260
Lloyd Pique90c115d2018-09-18 21:39:42 -0700261SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
262 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800263 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700264 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700265 mTransactionPending(false),
266 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700267 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700268 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800270 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800272 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800273 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800274 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700276 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700277 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700278 mDebugInTransaction(0),
279 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700280 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800281 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800282 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800283 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800284 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700285 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700286 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800287 mCompositionEngine{getFactory().createCompositionEngine()} {
288 mSetInputWindowsListener = new SetInputWindowsListener(this);
289}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800290
Lloyd Pique90c115d2018-09-18 21:39:42 -0700291SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
292 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800293 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800302
Steven Thomas050b2c82017-03-06 11:45:16 -0800303 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 mDefaultCompositionDataspace =
313 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
314 mWideColorGamutCompositionDataspace =
315 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
316 defaultCompositionDataspace = mDefaultCompositionDataspace;
317 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
318 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
319 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
320 wideColorGamutCompositionPixelFormat =
321 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
326 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
327 switch (tmpPrimaryDisplayOrientation) {
328 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800342
Sundong Ahn85131bd2019-02-18 15:51:53 +0900343 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 // debugging stuff...
346 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700349 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 property_get("debug.sf.showupdates", value, "0");
352 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700354 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000355
356 // DDMS debugging deprecated (b/120782499)
357 property_get("debug.sf.ddms", value, "0");
358 int debugDdms = atoi(value);
359 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700360
361 property_get("debug.sf.disable_backpressure", value, "0");
362 mPropagateBackpressure = !atoi(value);
363 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700364
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800365 property_get("debug.sf.enable_hwc_vds", value, "0");
366 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800367 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800368
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800369 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800370 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800371 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700372
Yiwei Zhang243b3782018-05-15 17:40:04 -0700373 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700374 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
375 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
376
Ana Krulecc2870422019-01-29 19:00:58 -0800377 property_get("debug.sf.use_90Hz", value, "0");
378 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800379
Ana Krulecba13ab32019-02-20 14:14:12 -0800380 property_get("debug.sf.use_smart_90_for_video", value, "0");
381 mUseSmart90ForVideo = atoi(value);
382
Dan Stozaec460082018-12-17 15:35:09 -0800383 property_get("debug.sf.luma_sampling", value, "1");
384 mLumaSampling = atoi(value);
385
Ana Krulec757f63a2019-01-25 10:46:18 -0800386 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
387 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700388
Romain Guy11d63f42017-07-20 12:47:14 -0700389 // We should be reading 'persist.sys.sf.color_saturation' here
390 // but since /data may be encrypted, we need to wait until after vold
391 // comes online to attempt to read the property. The property is
392 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800393
394 if (useTrebleTestingOverride()) {
395 // Without the override SurfaceFlinger cannot connect to HIDL
396 // services that are not listed in the manifests. Considered
397 // deriving the setting from the set service name, but it
398 // would be brittle if the name that's not 'default' is used
399 // for production purposes later on.
400 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
401 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402}
403
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404void SurfaceFlinger::onFirstRef()
405{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800406 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407}
408
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409SurfaceFlinger::~SurfaceFlinger()
410{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Dan Stozac7014012014-02-14 15:03:43 -0800413void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414{
415 // the window manager died on us. prepare its eulogy.
416
Andy McFadden13a082e2012-08-24 10:16:42 -0700417 // restore initial conditions (default device unblank, etc)
418 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419
420 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700421 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422}
423
Robert Carr1db73f62016-12-21 12:58:51 -0800424static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700425 status_t err = client->initCheck();
426 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428 }
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return nullptr;
430}
431
432sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
433 return initClient(new Client(this));
434}
435
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700436sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
437 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438{
439 class DisplayToken : public BBinder {
440 sp<SurfaceFlinger> flinger;
441 virtual ~DisplayToken() {
442 // no more references, this display must be terminated
443 Mutex::Autolock _l(flinger->mStateLock);
444 flinger->mCurrentState.displays.removeItem(this);
445 flinger->setTransactionFlags(eDisplayTransactionNeeded);
446 }
447 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700448 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449 : flinger(flinger) {
450 }
451 };
452
453 sp<BBinder> token = new DisplayToken(this);
454
455 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456 // Display ID is assigned when virtual display is allocated by HWC.
457 DisplayDeviceState state;
458 state.isSecure = secure;
459 state.displayName = displayName;
460 mCurrentState.displays.add(token, state);
461 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462 return token;
463}
464
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700465void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 Mutex::Autolock _l(mStateLock);
467
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
469 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700470 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700471 return;
472 }
473
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
475 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700476 ALOGE("destroyDisplay called for non-virtual display");
477 return;
478 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 mInterceptor->saveDisplayDeletion(state.sequenceId);
480 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 setTransactionFlags(eDisplayTransactionNeeded);
482}
483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800484std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
485 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487 const auto internalDisplayId = getInternalDisplayIdLocked();
488 if (!internalDisplayId) {
489 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 }
491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800492 std::vector<PhysicalDisplayId> displayIds;
493 displayIds.reserve(mPhysicalDisplayTokens.size());
494 displayIds.push_back(internalDisplayId->value);
495
496 for (const auto& [id, token] : mPhysicalDisplayTokens) {
497 if (id != *internalDisplayId) {
498 displayIds.push_back(id.value);
499 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 return displayIds;
503}
504
505sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
506 Mutex::Autolock lock(mStateLock);
507 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508}
509
Ady Abraham37965d42018-11-01 13:43:32 -0700510status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
511 if (!outGetColorManagement) {
512 return BAD_VALUE;
513 }
514 *outGetColorManagement = useColorManagement;
515 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700516}
517
Lloyd Pique441d5042018-10-18 16:49:51 -0700518HWComposer& SurfaceFlinger::getHwComposer() const {
519 return mCompositionEngine->getHwComposer();
520}
521
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700522renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
523 return mCompositionEngine->getRenderEngine();
524}
525
Lloyd Pique70d91362018-10-18 16:02:55 -0700526compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
527 return *mCompositionEngine.get();
528}
529
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530void SurfaceFlinger::bootFinished()
531{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700532 if (mStartPropertySetThread->join() != NO_ERROR) {
533 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535 const nsecs_t now = systemTime();
536 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000537 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538
539 // wait patiently for the window manager death
540 const String16 name("window");
541 sp<IBinder> window(defaultServiceManager()->getService(name));
542 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700543 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544 }
Robert Carr720e5062018-07-30 17:45:14 -0700545 sp<IBinder> input(defaultServiceManager()->getService(
546 String16("inputflinger")));
547 if (input == nullptr) {
548 ALOGE("Failed to link to input service");
549 } else {
550 mInputFlinger = interface_cast<IInputFlinger>(input);
551 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552
Steven Thomas050b2c82017-03-06 11:45:16 -0800553 if (mVrFlinger) {
554 mVrFlinger->OnBootFinished();
555 }
556
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700558 // formerly we would just kill the process, but we now ask it to exit so it
559 // can choose where to stop the animation.
560 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700561
562 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
563 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
564 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700565
Ana Krulecbd6654b2019-02-15 15:18:15 -0800566 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800567 readPersistentProperties();
568 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800569
570 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
571 // away and it should be controlled by flipping the switch in setting. The switch in
572 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
573 // The boot must be complete before we can set the active config.
574
575 if (mUse90Hz) {
576 mPhaseOffsets->setRefreshRateType(
577 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ady Abraham447052e2019-02-13 16:07:27 -0800578 setRefreshRateTo(RefreshRateType::PERFORMANCE, ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800579 } else {
580 mPhaseOffsets->setRefreshRateType(
581 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
Ady Abraham447052e2019-02-13 16:07:27 -0800582 setRefreshRateTo(RefreshRateType::DEFAULT, ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800583 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
617
Ana Krulec757f63a2019-01-25 10:46:18 -0800618 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800622 mScheduler =
623 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
624 auto resyncCallback =
625 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800626
Ana Krulecc2870422019-01-29 19:00:58 -0800627 mAppConnectionHandle =
628 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
629 resyncCallback,
630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
632 resyncCallback, [this](nsecs_t timestamp) {
633 mInterceptor->saveVSyncEvent(timestamp);
634 });
635
636 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
637 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
638 mSfConnectionHandle.get());
639
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700641 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700642 renderEngineFeature |= (useColorManagement ?
643 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700644 renderEngineFeature |= (useContextPriority ?
645 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700646
647 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800648 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700649 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700650 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800651 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700652
653 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
654 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700655 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
656 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800657 // Process any initial hotplug and resulting display changes.
658 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700659 const auto display = getDefaultDisplayDeviceLocked();
660 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700661 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700662 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800663
Steven Thomas050b2c82017-03-06 11:45:16 -0800664 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 // This callback is called from the vr flinger dispatch thread. We
667 // need to call signalTransaction(), which requires holding
668 // mStateLock when we're not on the main thread. Acquiring
669 // mStateLock from the vr flinger dispatch thread might trigger a
670 // deadlock in surface flinger (see b/66916578), so post a message
671 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700673 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
674 mVrFlingerRequestsDisplay = requestDisplay;
675 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700678 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
679 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700680 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 .value_or(0),
682 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (!mVrFlinger) {
684 ALOGE("Failed to start vrflinger");
685 }
686 }
687
Mathias Agopian92a979a2012-08-02 18:32:23 -0700688 // initialize our drawing state
689 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700690
Andy McFadden13a082e2012-08-24 10:16:42 -0700691 // set initial conditions (e.g. unblank default device)
692 initializeDisplays();
693
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700694 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700695
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700697
698 const bool presentFenceReliable =
699 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
700 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701
702 if (mStartPropertySetThread->Start() != NO_ERROR) {
703 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800704 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705
Kevin DuBois36233132019-02-19 14:08:55 -0800706 if (mUse90Hz) {
707 mScheduler->setExpiredIdleTimerCallback([this] {
708 Mutex::Autolock lock(mStateLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800709 setRefreshRateTo(RefreshRateType::DEFAULT, ConfigEvent::None);
Kevin DuBois36233132019-02-19 14:08:55 -0800710 });
711 mScheduler->setResetIdleTimerCallback([this] {
712 Mutex::Autolock lock(mStateLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800713 setRefreshRateTo(RefreshRateType::PERFORMANCE, ConfigEvent::None);
Kevin DuBois36233132019-02-19 14:08:55 -0800714 });
715 }
Ana Krulecc2870422019-01-29 19:00:58 -0800716 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
717 *display->getId()),
718 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800719
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700721}
722
Romain Guy11d63f42017-07-20 12:47:14 -0700723void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 Mutex::Autolock _l(mStateLock);
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726 char value[PROPERTY_VALUE_MAX];
727
728 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800729 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700730 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100732
733 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700734 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800735
736 property_get("persist.sys.sf.color_mode", value, "0");
737 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700751 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700755 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800793status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
794 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700795 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800799 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700800 if (!displayId) {
801 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700802 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804 // TODO: Not sure if display density should handled by SF any longer
805 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700806 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700808 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800809 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700810 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 }
812 return density;
813 }
814 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700815 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 return getDensityFromProperty("ro.sf.lcd_density"); }
819 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700820
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700822
Dominik Laskowski075d3172018-05-24 15:50:06 -0700823 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 DisplayInfo info = DisplayInfo();
825
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 float xdpi = hwConfig->getDpiX();
827 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700829 info.w = hwConfig->getWidth();
830 info.h = hwConfig->getHeight();
831 // Default display viewport to display width and height
832 info.viewportW = info.w;
833 info.viewportH = info.h;
834
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800835 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 // The density of the device is provided by a build property
837 float density = Density::getBuildDensity() / 160.0f;
838 if (density == 0) {
839 // the build doesn't provide a density -- this is wrong!
840 // use xdpi instead
841 ALOGE("ro.sf.lcd_density must be defined as a build property");
842 density = xdpi / 160.0f;
843 }
844 if (Density::getEmuDensity()) {
845 // if "qemu.sf.lcd_density" is specified, it overrides everything
846 xdpi = ydpi = density = Density::getEmuDensity();
847 density /= 160.0f;
848 }
849 info.density = density;
850
851 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700852 const auto display = getDefaultDisplayDeviceLocked();
853 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700854
855 // This is for screenrecord
856 const Rect viewport = display->getViewport();
857 if (viewport.isValid()) {
858 info.viewportW = uint32_t(viewport.getWidth());
859 info.viewportH = uint32_t(viewport.getHeight());
860 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 } else {
862 // TODO: where should this value come from?
863 static const int TV_DENSITY = 213;
864 info.density = TV_DENSITY / 160.0f;
865 info.orientation = 0;
866 }
867
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 info.xdpi = xdpi;
869 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800871 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872
Andy McFadden91b2ca82014-06-13 14:04:23 -0700873 // This is how far in advance a buffer must be queued for
874 // presentation at a given time. If you want a buffer to appear
875 // on the screen at time N, you must submit the buffer before
876 // (N - presentationDeadline).
877 //
878 // Normally it's one full refresh period (to give SF a chance to
879 // latch the buffer), but this can be reduced by configuring a
880 // DispSync offset. Any additional delays introduced by the hardware
881 // composer or panel must be accounted for here.
882 //
883 // We add an additional 1ms to allow for processing time and
884 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800885 info.presentationDeadline =
886 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700887
888 // All non-virtual displays are currently considered secure.
889 info.secure = true;
890
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800891 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700892 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800893 std::swap(info.w, info.h);
894 }
895
Michael Wright28f24d02016-07-12 13:30:53 -0700896 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700897 }
898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 return NO_ERROR;
900}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
903 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700904 return BAD_VALUE;
905 }
906
Ana Krulecc2870422019-01-29 19:00:58 -0800907 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700908 return NO_ERROR;
909}
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
912 const auto display = getDisplayDevice(displayToken);
913 if (!display) {
914 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800915 return BAD_VALUE;
916 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Ady Abraham447052e2019-02-13 16:07:27 -0800921void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
922 ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800923 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800924
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 // Lock is acquired by setRefreshRateTo.
927 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
929 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
930 return;
931 }
932
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 // Lock is acquired by setRefreshRateTo.
934 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935 if (!display) {
936 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
937 displayToken.get());
938 return;
939 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 ALOGW("Attempt to set active config %d for virtual display", mode);
942 return;
943 }
944 int currentDisplayPowerMode = display->getPowerMode();
945 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
946 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700947 return;
948 }
949
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800950 // Don't check against the current mode yet. Worst case we set the desired
951 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800952 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800953 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, event};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954
955 if (!mDesiredActiveConfigChanged) {
956 // This is the first time we set the desired
957 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
958
959 // This will trigger HWC refresh without resetting the idle timer.
960 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 mDesiredActiveConfigChanged = true;
963 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964}
965
966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
967 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800968
969 std::vector<int32_t> allowedConfig;
970 allowedConfig.push_back(mode);
971
972 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973}
974
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975void SurfaceFlinger::setActiveConfigInternal() {
976 ATRACE_CALL();
977
978 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800979 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980
981 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
982 display->setActiveConfig(mUpcomingActiveConfig.configId);
983
Ana Krulecc2870422019-01-29 19:00:58 -0800984 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ady Abraham447052e2019-02-13 16:07:27 -0800986 if (mUpcomingActiveConfig.event != ConfigEvent::None) {
987 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
988 mUpcomingActiveConfig.configId);
989 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990}
991
Ady Abrahamb838aed2019-02-12 15:30:16 -0800992bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -0800993 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800994 // we may be in the process of changing the active state
995 if (mWaitForNextInvalidate) {
996 mWaitForNextInvalidate = false;
997
998 repaintEverythingForHWC();
999 // We do not want to give another frame to HWC while we are transitioning.
1000 return true;
1001 }
1002
1003 if (mCheckPendingFence) {
1004 if (mPreviousPresentFence != Fence::NO_FENCE &&
1005 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1006 // fence has not signaled yet. wait for the next invalidate
1007 repaintEverythingForHWC();
1008 return true;
1009 }
1010
1011 // We received the present fence from the HWC, so we assume it successfully updated
1012 // the config, hence we update SF.
1013 mCheckPendingFence = false;
1014 setActiveConfigInternal();
1015 }
1016
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 // Store the local variable to release the lock.
1018 ActiveConfigInfo desiredActiveConfig;
1019 {
1020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001021 if (!mDesiredActiveConfigChanged) {
1022 return false;
1023 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 desiredActiveConfig = mDesiredActiveConfig;
1025 }
1026
1027 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1029 // display is not valid or we are already in the requested mode
1030 // on both cases there is nothing left to do
1031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1032 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1033 mDesiredActiveConfigChanged = false;
1034 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1035 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001036 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037
Ady Abraham838de062019-02-04 10:24:03 -08001038 // Desired active config was set, it is different than the config currently in use, however
1039 // allowed configs might have change by the time we process the refresh.
1040 // Make sure the desired config is still allowed
1041 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1042 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1043 mDesiredActiveConfig.configId = display->getActiveConfig();
1044 return false;
1045 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 mUpcomingActiveConfig = desiredActiveConfig;
1047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049
1050 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1051 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1052
1053 // we need to submit an empty frame to HWC to start the process
1054 mWaitForNextInvalidate = true;
1055 mCheckPendingFence = true;
1056
1057 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001058}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1061 Vector<ColorMode>* outColorModes) {
1062 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001063 return BAD_VALUE;
1064 }
1065
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001068 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1069
1070 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1071 if (!displayId) {
1072 return NAME_NOT_FOUND;
1073 }
1074
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001076 }
Michael Wright28f24d02016-07-12 13:30:53 -07001077 outColorModes->clear();
1078 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1079
1080 return NO_ERROR;
1081}
1082
Daniel Solomon42d04562019-01-20 21:03:19 -08001083status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1084 ui::DisplayPrimaries &primaries) {
1085 if (!displayToken) {
1086 return BAD_VALUE;
1087 }
1088
1089 // Currently we only support this API for a single internal display.
1090 if (getInternalDisplayToken() != displayToken) {
1091 return BAD_VALUE;
1092 }
1093
1094 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1099 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001100 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001102 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001103}
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 Vector<ColorMode> modes;
1108 getDisplayColorModes(displayToken, &modes);
1109 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1110 if (mode < ColorMode::NATIVE || !exists) {
1111 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1112 decodeColorMode(mode).c_str(), mode, displayToken.get());
1113 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 const auto display = getDisplayDevice(displayToken);
1116 if (!display) {
1117 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1118 decodeColorMode(mode).c_str(), mode, displayToken.get());
1119 } else if (display->isVirtual()) {
1120 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1121 decodeColorMode(mode).c_str(), mode);
1122 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001123 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1124 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125 }
1126 }));
1127
Michael Wright28f24d02016-07-12 13:30:53 -07001128 return NO_ERROR;
1129}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001130
Svetoslavd85084b2014-03-20 10:28:31 -07001131status_t SurfaceFlinger::clearAnimationFrameStats() {
1132 Mutex::Autolock _l(mStateLock);
1133 mAnimFrameTracker.clearStats();
1134 return NO_ERROR;
1135}
1136
1137status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1138 Mutex::Autolock _l(mStateLock);
1139 mAnimFrameTracker.getStats(outStats);
1140 return NO_ERROR;
1141}
1142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1144 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001145 Mutex::Autolock _l(mStateLock);
1146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 const auto display = getDisplayDeviceLocked(displayToken);
1148 if (!display) {
1149 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001150 return BAD_VALUE;
1151 }
1152
Peiyong Linfb069302018-04-25 14:34:31 -07001153 // At this point the DisplayDeivce should already be set up,
1154 // meaning the luminance information is already queried from
1155 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001157 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1158 capabilities.getDesiredMaxLuminance(),
1159 capabilities.getDesiredMaxAverageLuminance(),
1160 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001161
1162 return NO_ERROR;
1163}
1164
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001165status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1166 ui::PixelFormat* outFormat,
1167 ui::Dataspace* outDataspace,
1168 uint8_t* outComponentMask) const {
1169 if (!outFormat || !outDataspace || !outComponentMask) {
1170 return BAD_VALUE;
1171 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001172 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001173 if (!display || !display->getId()) {
1174 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1175 return BAD_VALUE;
1176 }
1177 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1178 outDataspace, outComponentMask);
1179}
1180
Kevin DuBois74e53772018-11-19 10:52:38 -08001181status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1182 bool enable, uint8_t componentMask,
1183 uint64_t maxFrames) const {
1184 const auto display = getDisplayDevice(displayToken);
1185 if (!display || !display->getId()) {
1186 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1187 return BAD_VALUE;
1188 }
1189
1190 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1191 componentMask, maxFrames);
1192}
1193
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001194status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1195 uint64_t maxFrames, uint64_t timestamp,
1196 DisplayedFrameStats* outStats) const {
1197 const auto display = getDisplayDevice(displayToken);
1198 if (!display || !display->getId()) {
1199 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1200 return BAD_VALUE;
1201 }
1202
1203 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1204 outStats);
1205}
1206
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001207status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1208 if (!outSupported) {
1209 return BAD_VALUE;
1210 }
1211 *outSupported = getRenderEngine().supportsProtectedContent();
1212 return NO_ERROR;
1213}
1214
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001215status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1216 bool* outIsWideColorDisplay) const {
1217 if (!displayToken || !outIsWideColorDisplay) {
1218 return BAD_VALUE;
1219 }
1220 Mutex::Autolock _l(mStateLock);
1221 const auto display = getDisplayDeviceLocked(displayToken);
1222 if (!display) {
1223 return BAD_VALUE;
1224 }
1225 *outIsWideColorDisplay = display->hasWideColorGamut();
1226 return NO_ERROR;
1227}
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001230 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 if (mInjectVSyncs == enable) {
1234 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236
Ana Krulecc2870422019-01-29 19:00:58 -08001237 auto resyncCallback =
1238 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001239
Ana Krulec98b5b242018-08-10 15:03:23 -07001240 // TODO(akrulec): Part of the Injector should be refactored, so that it
1241 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 if (enable) {
1243 ALOGV("VSync Injections enabled");
1244 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001245 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001246 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001248 impl::EventThread::InterceptVSyncsCallback(),
1249 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 } else {
1253 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001254 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1255 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 }
1257
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001259 }));
1260
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001261 return NO_ERROR;
1262}
1263
1264status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 Mutex::Autolock _l(mStateLock);
1266
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001267 if (!mInjectVSyncs) {
1268 ALOGE("VSync Injections not enabled");
1269 return BAD_VALUE;
1270 }
1271 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1272 ALOGV("Injecting VSync inside SurfaceFlinger");
1273 mVSyncInjector->onInjectSyncEvent(when);
1274 }
1275 return NO_ERROR;
1276}
1277
Lloyd Pique755e3192018-01-31 16:46:15 -08001278status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1279 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001280 // Try to acquire a lock for 1s, fail gracefully
1281 const status_t err = mStateLock.timedLock(s2ns(1));
1282 const bool locked = (err == NO_ERROR);
1283 if (!locked) {
1284 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1285 return TIMED_OUT;
1286 }
1287
1288 outLayers->clear();
1289 mCurrentState.traverseInZOrder([&](Layer* layer) {
1290 outLayers->push_back(layer->getLayerDebugInfo());
1291 });
1292
1293 mStateLock.unlock();
1294 return NO_ERROR;
1295}
1296
Peiyong Linc6780972018-10-28 15:24:08 -07001297status_t SurfaceFlinger::getCompositionPreference(
1298 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1299 Dataspace* outWideColorGamutDataspace,
1300 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001301 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001302 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001303 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001304 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001305 return NO_ERROR;
1306}
1307
Dan Stozaec460082018-12-17 15:35:09 -08001308status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1309 const sp<IBinder>& stopLayerHandle,
1310 const sp<IRegionSamplingListener>& listener) {
1311 if (!listener) {
1312 return BAD_VALUE;
1313 }
1314 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001315 return NO_ERROR;
1316}
1317
Dan Stozaec460082018-12-17 15:35:09 -08001318status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1319 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001320 return NO_ERROR;
1321}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001322// ----------------------------------------------------------------------------
1323
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001324sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1325 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001326 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 Mutex::Autolock lock(mStateLock);
1328 return getVsyncPeriod();
1329 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001330
Ana Krulecc2870422019-01-29 19:00:58 -08001331 const auto& handle =
1332 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001333
Ana Krulecc2870422019-01-29 19:00:58 -08001334 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001335}
1336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338
1339void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341}
1342
1343void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349}
1350
1351void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001352 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001357 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001358 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001359}
1360
1361status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001362 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001363 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364 if (res == NO_ERROR) {
1365 msg->wait();
1366 }
1367 return res;
1368}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001369
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001370void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001371 do {
1372 waitForEvent();
1373 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001374}
1375
Dominik Laskowski83b88212018-12-11 13:34:06 -08001376nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001377 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001378 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1379 return 0;
1380 }
1381
1382 const auto config = getHwComposer().getActiveConfig(*displayId);
1383 return config ? config->getVsyncPeriod() : 0;
1384}
1385
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001386void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1387 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001388 ATRACE_NAME("SF onVsync");
1389
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001392 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 return;
1394 }
1395
Dominik Laskowski075d3172018-05-24 15:50:06 -07001396 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001397 return;
1398 }
1399
Dominik Laskowski075d3172018-05-24 15:50:06 -07001400 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001401 // For now, we don't do anything with external display vsyncs.
1402 return;
1403 }
1404
Ana Krulecc2870422019-01-29 19:00:58 -08001405 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001406}
1407
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001409 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1410 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411}
1412
Ady Abraham838de062019-02-04 10:24:03 -08001413bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1414 std::lock_guard lock(mAllowedConfigsLock);
1415
1416 // if allowed configs are not set yet for this display, every config is considered allowed
1417 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1418 return true;
1419 }
1420
1421 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1422}
1423
Ady Abraham447052e2019-02-13 16:07:27 -08001424void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001425 mPhaseOffsets->setRefreshRateType(refreshRate);
1426
1427 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1428 mVsyncModulator.setPhaseOffsets(early, gl, late);
1429
1430 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001431 return;
1432 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001433
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1435 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1436 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1437 // refresh cycle.
1438
1439 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001440 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001441 if (currentVsyncPeriod == 0) {
1442 return;
1443 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001444
Ana Krulec7d1d6832018-12-27 11:10:09 -08001445 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1446 // floating numbers.
1447 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001448 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1449 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001450 if (std::abs(currentFps - newFps) <= 1) {
1451 return;
1452 }
1453
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001454 const auto displayId = getInternalDisplayIdLocked();
1455 LOG_ALWAYS_FATAL_IF(!displayId);
1456
1457 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001458 for (int i = 0; i < configs.size(); i++) {
Ady Abraham838de062019-02-04 10:24:03 -08001459 if (!isConfigAllowed(*displayId, i)) {
1460 ALOGV("Skipping config %d as it is not part of allowed configs", i);
1461 continue;
1462 }
1463
Ana Krulec7d1d6832018-12-27 11:10:09 -08001464 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1465 if (vsyncPeriod == 0) {
1466 continue;
1467 }
1468 const float fps = 1e9 / vsyncPeriod;
1469 // TODO(b/113612090): There should be a better way at determining which config
1470 // has the right refresh rate.
1471 if (std::abs(fps - newFps) <= 1) {
Ady Abraham447052e2019-02-13 16:07:27 -08001472 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001473 }
1474 }
1475}
1476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001478 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001479 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001480 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481
Lloyd Piqueba04e622017-12-14 17:11:26 -08001482 // Ignore events that do not have the right sequenceId.
1483 if (sequenceId != getBE().mComposerSequenceId) {
1484 return;
1485 }
1486
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 // Only lock if we're not on the main thread. This function is normally
1488 // called on a hwbinder thread, but for the primary display it's called on
1489 // the main thread with the state lock already held, so don't attempt to
1490 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001491 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001494
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001495 if (std::this_thread::get_id() == mMainThreadId) {
1496 // Process all pending hot plug events immediately if we are on the main thread.
1497 processDisplayHotplugEventsLocked();
1498 }
1499
Lloyd Piqueba04e622017-12-14 17:11:26 -08001500 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001501}
1502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001504 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001505 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001507 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001509}
1510
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001511void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001512 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001513 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001514 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001515 getHwComposer().setVsyncEnabled(*displayId,
1516 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1517 }
Mathias Agopian86303202012-07-24 22:46:10 -07001518}
1519
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001521void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001522 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001523 // Clear the drawing state so that the logic inside of
1524 // handleTransactionLocked will fire. It will determine the delta between
1525 // mCurrentState and mDrawingState and re-apply all changes when we make the
1526 // transition.
1527 mDrawingState.displays.clear();
1528 mDisplays.clear();
1529}
1530
Steven Thomas050b2c82017-03-06 11:45:16 -08001531void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001532 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001533 if (!mVrFlinger)
1534 return;
1535 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001536 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001537 return;
1538 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 ALOGE("Vr flinger is only supported for remote hardware composer"
1542 " service connections. Ignoring request to transition to vr"
1543 " flinger.");
1544 mVrFlingerRequestsDisplay = false;
1545 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001546 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001547
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001548 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomas0123ac62018-07-12 11:32:34 -07001550 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001551 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001552
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001553 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001554
1555 // Clear out all the output layers from the composition engine for all
1556 // displays before destroying the hardware composer interface. This ensures
1557 // any HWC layers are destroyed through that interface before it becomes
1558 // invalid.
1559 for (const auto& [token, displayDevice] : mDisplays) {
1560 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1561 compositionengine::Output::OutputLayers());
1562 }
1563
Steven Thomas0123ac62018-07-12 11:32:34 -07001564 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1565 // called below. Clear the reference now so we don't accidentally use it
1566 // later.
1567 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001568
Steven Thomasb02664d2017-07-26 18:48:28 -07001569 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001574 // Delete the current instance before creating the new one
1575 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1576 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1577 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1578 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001579
Lloyd Pique441d5042018-10-18 16:49:51 -07001580 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001581 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001582
1583 if (vrFlingerRequestsDisplay) {
1584 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001585 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001586
1587 mVisibleRegionsDirty = true;
1588 invalidateHwcGeometry();
1589
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001590 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001591 display = getDefaultDisplayDeviceLocked();
1592 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001593 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001594
Steven Thomasb02664d2017-07-26 18:48:28 -07001595 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001596 const nsecs_t vsyncPeriod = getVsyncPeriod();
1597 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001598
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001599 // The present fences returned from vr_hwc are not an accurate
1600 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001601 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001602
Steven Thomasb02664d2017-07-26 18:48:28 -07001603 // Use phase of 0 since phase is not known.
1604 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001605 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001606 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001607
Ana Krulecc2870422019-01-29 19:00:58 -08001608 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001609
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001610 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001611 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001612}
1613
Mathias Agopian4fec8732012-06-29 14:12:52 -07001614void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001615 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001616 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001617 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001618 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001619 break;
1620 }
1621
Ana Krulecba13ab32019-02-20 14:14:12 -08001622 if (mUse90Hz && mUseSmart90ForVideo) {
1623 // This call is made each time SF wakes up and creates a new frame. It is part
1624 // of video detection feature.
1625 mScheduler->incrementFrameCounter();
1626 }
Alec Mourife3dc942019-02-12 14:19:18 -08001627 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001628 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001629 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001630 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001631 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1632 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001633 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001634 }
1635 // For now, only propagate backpressure when missing a hwc frame.
1636 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001637 if (mPropagateBackpressure) {
1638 signalLayerUpdate();
1639 break;
1640 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001641 }
Dan Stoza50182882016-07-08 12:02:20 -07001642
Steven Thomas050b2c82017-03-06 11:45:16 -08001643 // Now that we're going to make it to the handleMessageTransaction()
1644 // call below it's safe to call updateVrFlinger(), which will
1645 // potentially trigger a display handoff.
1646 updateVrFlinger();
1647
Dan Stoza6b9454d2014-11-07 16:00:59 -08001648 bool refreshNeeded = handleMessageTransaction();
1649 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001650
1651 updateCursorAsync();
1652 updateInputFlinger();
1653
Dan Stoza58784442014-12-02 16:58:17 -08001654 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001655 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001656 // Signal a refresh if a transaction modified the window state,
1657 // a new buffer was latched, or if HWC has requested a full
1658 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001659 signalRefresh();
1660 }
1661 break;
1662 }
1663 case MessageQueue::REFRESH: {
1664 handleMessageRefresh();
1665 break;
1666 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001667 }
1668}
1669
Dan Stoza6b9454d2014-11-07 16:00:59 -08001670bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001671 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001672 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001673
1674 // Apply any ready transactions in the queues if there are still transactions that have not been
1675 // applied, wake up during the next vsync period and check again
1676 bool transactionNeeded = false;
1677 if (!flushTransactionQueues()) {
1678 transactionNeeded = true;
1679 }
1680
Mathias Agopian4fec8732012-06-29 14:12:52 -07001681 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001682 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001684
1685 if (transactionNeeded) {
1686 setTransactionFlags(eTransactionNeeded);
1687 }
1688
1689 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690}
1691
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001694
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001695 mRefreshPending = false;
1696
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001697 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001698 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001699 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001700 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 for (const auto& [token, display] : mDisplays) {
1702 beginFrame(display);
1703 prepareFrame(display);
1704 doDebugFlashRegions(display, repaintEverything);
1705 doComposition(display, repaintEverything);
1706 }
1707
Adrian Roos1e1a1282017-11-01 19:05:31 +01001708 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001709 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710
1711 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001712 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001713
Dan Stozabfbffeb2016-07-21 14:49:33 -07001714 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 for (const auto& [token, displayDevice] : mDisplays) {
1716 auto display = displayDevice->getCompositionDisplay();
1717 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001719 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001720 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001721
Jorim Jaggi90535212018-05-23 23:44:06 +02001722 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001723
David Sodman7e4ae112018-02-09 15:02:28 -08001724 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001725
1726 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001728
David Sodmanfa9b2af2017-12-24 13:28:59 -08001729
1730bool SurfaceFlinger::handleMessageInvalidate() {
1731 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001732 bool refreshNeeded = handlePageFlip();
1733
Vishnu Nair4351ad52019-02-11 14:13:02 -08001734 if (mVisibleRegionsDirty) {
1735 computeLayerBounds();
1736 }
1737
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001738 for (auto& layer : mLayersPendingRefresh) {
1739 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001740 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001741 invalidateLayerStack(layer, visibleReg);
1742 }
1743 mLayersPendingRefresh.clear();
1744 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001745}
1746
David Sodman79bba0e2018-08-05 18:07:49 -07001747void SurfaceFlinger::calculateWorkingSet() {
1748 ATRACE_CALL();
1749 ALOGV(__FUNCTION__);
1750
David Sodman79bba0e2018-08-05 18:07:49 -07001751 // build the h/w work list
1752 if (CC_UNLIKELY(mGeometryInvalid)) {
1753 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001754 for (const auto& [token, displayDevice] : mDisplays) {
1755 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001756 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 if (!displayId) {
1758 continue;
1759 }
David Sodman79bba0e2018-08-05 18:07:49 -07001760
Lloyd Pique32cbe282018-10-19 13:09:22 -07001761 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001762 for (size_t i = 0; i < currentLayers.size(); i++) {
1763 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001764
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001765 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001766 layer->forceClientComposition(displayDevice);
1767 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001768 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769
Lloyd Pique32cbe282018-10-19 13:09:22 -07001770 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001772 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 }
David Sodman79bba0e2018-08-05 18:07:49 -07001774 }
1775 }
1776 }
1777
1778 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001779 for (const auto& [token, displayDevice] : mDisplays) {
1780 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001781 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001783 continue;
1784 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001785 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001786
1787 if (mDrawingState.colorMatrixChanged) {
1788 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001789 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001791 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001792 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1794 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001795 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001796 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001797 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1798 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001799 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001800 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001801 }
1802
Peiyong Lind3788632018-09-18 16:01:31 -07001803 // TODO(b/111562338) remove when composer 2.3 is shipped.
1804 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001805 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001806 }
1807
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001808 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001809 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001810 }
1811
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001812 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001813 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001814 layer->setCompositionType(displayDevice,
1815 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 continue;
1817 }
1818
Lloyd Pique32cbe282018-10-19 13:09:22 -07001819 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001820 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001821 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001822 }
1823
Peiyong Lin13effd12018-07-24 17:01:47 -07001824 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001825 ColorMode colorMode;
1826 Dataspace dataSpace;
1827 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001828 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001830 }
1831 }
1832
1833 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001834
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001835 for (const auto& [token, displayDevice] : mDisplays) {
1836 auto display = displayDevice->getCompositionDisplay();
1837 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001838 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001839 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1840 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1841 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001842 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001843 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001844 }
1845 }
David Sodman79bba0e2018-08-05 18:07:49 -07001846}
1847
Lloyd Pique32cbe282018-10-19 13:09:22 -07001848void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1849 bool repaintEverything) {
1850 auto display = displayDevice->getCompositionDisplay();
1851 const auto& displayState = display->getState();
1852
Mathias Agopiancd60f992012-08-16 16:28:27 -07001853 // is debugging enabled
1854 if (CC_LIKELY(!mDebugRegion))
1855 return;
1856
Lloyd Pique32cbe282018-10-19 13:09:22 -07001857 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001858 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001859 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001860 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001861 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001862 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001863 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001865 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 }
1867 }
1868
Lloyd Pique32cbe282018-10-19 13:09:22 -07001869 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870
1871 if (mDebugRegion > 1) {
1872 usleep(mDebugRegion * 1000);
1873 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001874
Lloyd Pique32cbe282018-10-19 13:09:22 -07001875 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876}
1877
Adrian Roos1e1a1282017-11-01 19:05:31 +01001878void SurfaceFlinger::doTracing(const char* where) {
1879 ATRACE_CALL();
1880 ATRACE_NAME(where);
1881 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001882 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001883 }
1884}
1885
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001886void SurfaceFlinger::logLayerStats() {
1887 ATRACE_CALL();
1888 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001889 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001891 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001892 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001893 }
1894 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001895
1896 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001897 }
1898}
1899
David Sodman2b406362017-12-15 13:33:47 -08001900void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 ATRACE_CALL();
1903 ALOGV("preComposition");
1904
David Sodman2b406362017-12-15 13:33:47 -08001905 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1906
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001908 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001909 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910 needExtraInvalidate = true;
1911 }
Robert Carr2047fae2016-11-28 14:09:09 -08001912 });
1913
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914 if (needExtraInvalidate) {
1915 signalLayerUpdate();
1916 }
1917}
1918
Ana Krulece588e312018-09-18 12:32:24 -07001919void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1920 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Update queue of past composite+present times and determine the
1922 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001923 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001925 while (!getBE().mCompositePresentTimes.empty()) {
1926 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927 // Cached values should have been updated before calling this method,
1928 // which helps avoid duplicate syscalls.
1929 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1930 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1931 break;
1932 }
1933 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001934 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 }
1936
1937 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001938 while (getBE().mCompositePresentTimes.size() > 16) {
1939 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940 }
1941
Ana Krulece588e312018-09-18 12:32:24 -07001942 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001943}
1944
Ana Krulece588e312018-09-18 12:32:24 -07001945void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1946 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Integer division and modulo round toward 0 not -inf, so we need to
1948 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001949 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1950 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1951 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952
Ana Krulec757f63a2019-01-25 10:46:18 -08001953 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001954 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001955 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001956 }
1957
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 // Snap the latency to a value that removes scheduling jitter from the
1959 // composition and present times, which often have >1ms of jitter.
1960 // Reducing jitter is important if an app attempts to extrapolate
1961 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001962 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001964 nsecs_t bias = stats.vsyncPeriod / 2;
1965 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1966 nsecs_t snappedCompositeToPresentLatency =
1967 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968
David Sodman99974d22017-11-28 12:04:33 -08001969 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001970 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1971 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001972 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973}
1974
Ady Abraham8164d482019-01-11 14:47:59 -08001975// debug patch for b/119477596 - add stack guards to catch stack
1976// corruptions and disable clang optimizations.
1977// The code below is temporary and planned to be removed once stack
1978// corruptions are found.
1979#pragma clang optimize off
1980class StackGuard {
1981public:
1982 StackGuard(const char* name, const char* func, int line) {
1983 guarders.reserve(MIN_CAPACITY);
1984 guarders.push_back({this, name, func, line});
1985 validate();
1986 }
1987 ~StackGuard() {
1988 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1989 if (i->guard == this) {
1990 guarders.erase(i);
1991 break;
1992 }
1993 }
1994 }
1995
1996 static void validate() {
1997 for (const auto& guard : guarders) {
1998 if (guard.guard->cookie != COOKIE_VALUE) {
1999 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2000 CallStack stack(LOG_TAG);
2001 abort();
2002 }
2003 }
2004 }
2005
2006private:
2007 uint64_t cookie = COOKIE_VALUE;
2008 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2009 static constexpr size_t MIN_CAPACITY = 16;
2010
2011 struct GuarderElement {
2012 StackGuard* guard;
2013 const char* name;
2014 const char* func;
2015 int line;
2016 };
2017
2018 static std::vector<GuarderElement> guarders;
2019};
2020std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2021
2022#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2023
2024#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002025void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026{
Ady Abraham8164d482019-01-11 14:47:59 -08002027 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ATRACE_CALL();
2029 ALOGV("postComposition");
2030
Brian Anderson3546a3f2016-07-14 11:51:14 -07002031 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002032 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002033 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002034 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002035 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002036 }
Ady Abraham8164d482019-01-11 14:47:59 -08002037 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002038
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002039 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002040 const auto displayDevice = getDefaultDisplayDeviceLocked();
2041 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002045 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2046
Lloyd Pique32cbe282018-10-19 13:09:22 -07002047 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002048 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002049 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2050 ->getRenderSurface()
2051 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002052 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053 } else {
2054 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2055 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
2058
David Sodman73beded2017-11-15 11:56:06 -08002059 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2061 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002062 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002063 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002064 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065
Ana Krulece588e312018-09-18 12:32:24 -07002066 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002068 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069
Ady Abraham8164d482019-01-11 14:47:59 -08002070 ASSERT_ON_STACK_GUARD();
2071
David Sodman2b406362017-12-15 13:33:47 -08002072 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // when we started doing work for this frame, but that should be okay
2074 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002075 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002076 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002077 DEFINE_STACK_GUARD(compositorTiming);
2078
Brian Andersond0010582017-03-07 13:20:31 -08002079 {
David Sodman99974d22017-11-28 12:04:33 -08002080 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002082 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002083
2084 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002085 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002086
Robert Carr2047fae2016-11-28 14:09:09 -08002087 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002088 bool frameLatched =
2089 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2090 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002091 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002092 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002093 recordBufferingStats(layer->getName().string(),
2094 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002095 }
Ady Abraham8164d482019-01-11 14:47:59 -08002096 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002097 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002098
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002099 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002101 mScheduler->addPresentFence(presentFenceTime);
2102 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002103 }
2104
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002105 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002106 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2107 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002108 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002109 }
2110 }
2111
Ady Abraham8164d482019-01-11 14:47:59 -08002112 ASSERT_ON_STACK_GUARD();
2113
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002114 if (mAnimCompositionPending) {
2115 mAnimCompositionPending = false;
2116
Brian Anderson4e606e32017-03-16 15:34:57 -07002117 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002119 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002120
2121 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002122 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123 // The HWC doesn't support present fences, so use the refresh
2124 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002125 const nsecs_t presentTime =
2126 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002127 DEFINE_STACK_GUARD(presentTime);
2128
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002129 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002130 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002131 }
2132 mAnimFrameTracker.advanceFrame();
2133 }
Dan Stozab90cf072015-03-05 11:05:59 -08002134
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
2136
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002137 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002138 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002139 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002140 }
2141
Ady Abraham8164d482019-01-11 14:47:59 -08002142 ASSERT_ON_STACK_GUARD();
2143
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002144 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002145
Ady Abraham8164d482019-01-11 14:47:59 -08002146 ASSERT_ON_STACK_GUARD();
2147
Lloyd Pique32cbe282018-10-19 13:09:22 -07002148 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2149 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002150 return;
2151 }
2152
2153 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002155 if (mHasPoweredOff) {
2156 mHasPoweredOff = false;
2157 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002158 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002160 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002161 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002162 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2163 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002164 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002165 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002166 }
David Sodman4a36e932017-11-07 14:29:47 -08002167 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002168
2169 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002170 }
David Sodman4a36e932017-11-07 14:29:47 -08002171 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002173
2174 {
2175 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002176 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002177 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002179 if (refillCount > 0) {
2180 const size_t offset = mTexturePool.size();
2181 mTexturePool.resize(mTexturePoolSize);
2182 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2183 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2184 }
Ady Abraham8164d482019-01-11 14:47:59 -08002185 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002186 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002187
Marissa Wallfda30bb2018-10-12 11:34:28 -07002188 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002189 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002190
Dan Stozaec460082018-12-17 15:35:09 -08002191 if (mLumaSampling) {
2192 mRegionSamplingThread->sampleNow();
2193 }
2194
Ady Abraham8164d482019-01-11 14:47:59 -08002195 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196}
Ady Abraham8164d482019-01-11 14:47:59 -08002197#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002198
Vishnu Nair4351ad52019-02-11 14:13:02 -08002199void SurfaceFlinger::computeLayerBounds() {
2200 for (const auto& pair : mDisplays) {
2201 const auto& displayDevice = pair.second;
2202 const auto display = displayDevice->getCompositionDisplay();
2203 for (const auto& layer : mDrawingState.layersSortedByZ) {
2204 // only consider the layers on the given layer stack
2205 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002206 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002207 }
2208
2209 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2210 }
2211 }
2212}
2213
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 ATRACE_CALL();
2216 ALOGV("rebuildLayerStacks");
2217
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002218 // We need to clear these out now as these may be holding on to a
2219 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2220 // also holds a reference. When the set of visible layers is recomputed,
2221 // some layers may be destroyed if the only thing keeping them alive was
2222 // that list of visible layers associated with each display. The layer
2223 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2224 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2225 for (const auto& [token, display] : mDisplays) {
2226 getBE().mCompositionInfo[token].clear();
2227 }
2228
Mathias Agopiancd60f992012-08-16 16:28:27 -07002229 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002230 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002231 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002232 mVisibleRegionsDirty = false;
2233 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002234
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002235 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002236 const auto& displayDevice = pair.second;
2237 auto display = displayDevice->getCompositionDisplay();
2238 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 Region opaqueRegion;
2240 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002241 compositionengine::Output::OutputLayers layersSortedByZ;
2242 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002243 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002244 const ui::Transform& tr = displayState.transform;
2245 const Rect bounds = displayState.bounds;
2246 if (displayState.isEnabled) {
2247 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002248
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002250 auto compositionLayer = layer->getCompositionLayer();
2251 if (compositionLayer == nullptr) {
2252 return;
2253 }
2254
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002256 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2257 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2258
Lloyd Pique07e33212018-12-18 16:33:37 -08002259 bool needsOutputLayer = false;
2260
Lloyd Piqueef36b002019-01-23 17:52:04 -08002261 if (display->belongsInOutput(layer->getLayerStack(),
2262 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002263 Region drawRegion(tr.transform(
2264 layer->visibleNonTransparentRegion));
2265 drawRegion.andSelf(bounds);
2266 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002267 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002268 }
Chia-I Wu83806892017-11-16 10:50:20 -08002269 }
2270
Lloyd Pique07e33212018-12-18 16:33:37 -08002271 if (needsOutputLayer) {
2272 layersSortedByZ.emplace_back(
2273 display->getOrCreateOutputLayer(displayId, compositionLayer,
2274 layerFE));
2275 deprecated_layersSortedByZ.add(layer);
2276
2277 auto& outputLayerState = layersSortedByZ.back()->editState();
2278 outputLayerState.visibleRegion =
2279 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2280 } else if (displayId) {
2281 // For layers that are being removed from a HWC display,
2282 // and that have queued frames, add them to a a list of
2283 // released layers so we can properly set a fence.
2284 bool hasExistingOutputLayer =
2285 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2286 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2287 mLayersWithQueuedFrames.cend(),
2288 layer) != mLayersWithQueuedFrames.cend();
2289
2290 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002291 layersNeedingFences.add(layer);
2292 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002293 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002294 });
2295 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002296
2297 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2298
2299 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002300 displayDevice->setLayersNeedingFences(layersNeedingFences);
2301
2302 Region undefinedRegion{bounds};
2303 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2304
2305 display->editState().undefinedRegion = undefinedRegion;
2306 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002307 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002308 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002309}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002310
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002312// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002313// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002315// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002316// The returned HDR data space is one of
2317// - Dataspace::UNKNOWN
2318// - Dataspace::BT2020_HLG
2319// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2321 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002322 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323 *outHdrDataSpace = Dataspace::UNKNOWN;
2324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002326 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327 case Dataspace::V0_SCRGB:
2328 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002329 case Dataspace::BT2020:
2330 case Dataspace::BT2020_ITU:
2331 case Dataspace::BT2020_LINEAR:
2332 case Dataspace::DISPLAY_BT2020:
2333 bestDataSpace = Dataspace::DISPLAY_BT2020;
2334 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002336 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 case Dataspace::BT2020_PQ:
2339 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002340 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002343 case Dataspace::BT2020_HLG:
2344 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002345 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 // When there's mixed PQ content and HLG content, we set the HDR
2347 // data space to be BT2020_PQ and convert HLG to PQ.
2348 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2349 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002350 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 break;
2352 default:
2353 break;
2354 }
Romain Guy54f154a2017-10-24 21:40:32 +01002355 }
2356
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002358}
2359
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2362 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002363 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2364 *outMode = ColorMode::NATIVE;
2365 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002368 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002369
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002370 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002372
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002373 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2374
Peiyong Lina3ea5592019-02-10 14:45:00 -08002375 switch (mForceColorMode) {
2376 case ColorMode::SRGB:
2377 bestDataSpace = Dataspace::V0_SRGB;
2378 break;
2379 case ColorMode::DISPLAY_P3:
2380 bestDataSpace = Dataspace::DISPLAY_P3;
2381 break;
2382 default:
2383 break;
2384 }
2385
Peiyong Lindfde5112018-06-05 10:58:41 -07002386 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002387 const bool isHdr =
2388 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002389 if (isHdr) {
2390 bestDataSpace = hdrDataSpace;
2391 }
2392
Chia-I Wu0d711262018-05-21 15:19:35 -07002393 RenderIntent intent;
2394 switch (mDisplayColorSetting) {
2395 case DisplayColorSetting::MANAGED:
2396 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002397 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002398 break;
2399 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002400 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002401 break;
2402 default: // vendor display color setting
2403 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2404 break;
2405 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002406
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002407 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002408}
2409
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2411 auto display = displayDevice->getCompositionDisplay();
2412 const auto& displayState = display->getState();
2413
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002414 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2416 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002417
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // If nothing has changed (!dirty), don't recompose.
2419 // If something changed, but we don't currently have any visible layers,
2420 // and didn't when we last did a composition, then skip it this time.
2421 // The second rule does two things:
2422 // - When all layers are removed from a display, we'll emit one black
2423 // frame, then nothing more until we get new layers.
2424 // - When a display is created with a private layer stack, we won't
2425 // emit any black frames until a layer is added to the layer stack.
2426 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002427
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 const char flagPrefix[] = {'-', '+'};
2429 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002430 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2431 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2432 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2433 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002434
Lloyd Pique31cb2942018-10-19 17:23:03 -07002435 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002436
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002439 }
2440}
2441
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2443 auto display = displayDevice->getCompositionDisplay();
2444 const auto& displayState = display->getState();
2445
2446 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 return;
David Sodman2b406362017-12-15 13:33:47 -08002448 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002450 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002453}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002454
Lloyd Pique32cbe282018-10-19 13:09:22 -07002455void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002456 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 ALOGV("doComposition");
2458
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 auto display = displayDevice->getCompositionDisplay();
2460 const auto& displayState = display->getState();
2461
2462 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002463 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002464 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002465
David Sodmanfa9b2af2017-12-24 13:28:59 -08002466 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002468
Lloyd Pique32cbe282018-10-19 13:09:22 -07002469 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002470 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002471 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002472 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002473}
2474
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475void SurfaceFlinger::postFrame()
2476{
2477 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 const auto display = getDefaultDisplayDeviceLocked();
2479 if (display && getHwComposer().isConnected(*display->getId())) {
2480 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002481 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2482 logFrameStats();
2483 }
2484 }
2485}
2486
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002488 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002490
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 auto display = displayDevice->getCompositionDisplay();
2492 const auto& displayState = display->getState();
2493 const auto displayId = display->getId();
2494
David Sodmanfa9b2af2017-12-24 13:28:59 -08002495 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002496
Lloyd Pique32cbe282018-10-19 13:09:22 -07002497 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 if (displayId) {
2499 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002500 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002501 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002502 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002503 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002504
Chia-I Wu7b549592017-11-15 09:14:57 -08002505 // The layer buffer from the previous frame (if any) is released
2506 // by HWC only when the release fence from this frame (if any) is
2507 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002508 if (displayId && layer->hasHwcLayer(displayDevice)) {
2509 releaseFence =
2510 getHwComposer().getLayerReleaseFence(*displayId,
2511 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002512 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002513
2514 // If the layer was client composited in the previous frame, we
2515 // need to merge with the previous client target acquire fence.
2516 // Since we do not track that, always merge with the current
2517 // client target acquire fence when it is available, even though
2518 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002519 if (layer->getCompositionType(displayDevice) ==
2520 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002521 releaseFence =
2522 Fence::merge("LayerRelease", releaseFence,
2523 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002524 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002525
David Sodman15094112018-10-11 09:39:37 -07002526 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 }
Chia-I Wu83806892017-11-16 10:50:20 -08002528
2529 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002531 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002534 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002535 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002536 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002537 }
2538 }
2539
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (displayId) {
2541 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002542 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002543 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544}
2545
Mathias Agopian87baae12012-07-31 12:38:26 -07002546void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547{
Mathias Agopian841cde52012-03-01 15:44:37 -08002548 ATRACE_CALL();
2549
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002550 // here we keep a copy of the drawing state (that is the state that's
2551 // going to be overwritten by handleTransactionLocked()) outside of
2552 // mStateLock so that the side-effects of the State assignment
2553 // don't happen with mStateLock held (which can cause deadlocks).
2554 State drawingState(mDrawingState);
2555
Mathias Agopianca4d3602011-05-19 15:38:14 -07002556 Mutex::Autolock _l(mStateLock);
2557 const nsecs_t now = systemTime();
2558 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Mathias Agopianca4d3602011-05-19 15:38:14 -07002560 // Here we're guaranteed that some transaction flags are set
2561 // so we can call handleTransactionLocked() unconditionally.
2562 // We call getTransactionFlags(), which will also clear the flags,
2563 // with mStateLock held to guarantee that mCurrentState won't change
2564 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002565
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002566 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002567 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002568 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002569
Mathias Agopianca4d3602011-05-19 15:38:14 -07002570 mLastTransactionTime = systemTime() - now;
2571 mDebugInTransaction = 0;
2572 invalidateHwcGeometry();
2573 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002574}
2575
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2577 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 const std::optional<DisplayIdentificationInfo> info =
2579 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002580
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582 continue;
2583 }
2584
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002587 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 mPhysicalDisplayTokens[info->id] = new BBinder();
2589 DisplayDeviceState state;
2590 state.displayId = info->id;
2591 state.isSecure = true; // All physical displays are currently considered secure.
2592 state.displayName = info->name;
2593 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2594 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002595 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002597 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2600 if (index >= 0) {
2601 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2602 mInterceptor->saveDisplayDeletion(state.sequenceId);
2603 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002604 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 }
2607
2608 processDisplayChangesLocked();
2609 }
2610
2611 mPendingHotplugEvents.clear();
2612}
2613
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002614void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002615 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2616 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002617}
2618
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002621 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 const sp<IGraphicBufferProducer>& producer) {
2623 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002624 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002626 creationArgs.isSecure = state.isSecure;
2627 creationArgs.displaySurface = dispSurface;
2628 creationArgs.hasWideColorGamut = false;
2629 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002630
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002631 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 creationArgs.isPrimary = isInternalDisplay;
2633
2634 if (useColorManagement && displayId) {
2635 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002637 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002638 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002640
Dominik Laskowski7e045462018-05-30 13:02:02 -07002641 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002643 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 }
tangrobin6753a022018-08-10 10:58:54 +08002645 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 if (displayId) {
2648 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002651 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652
Lloyd Pique90c115d2018-09-18 21:39:42 -07002653 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002655 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657 // Make sure that composition can never be stalled by a virtual display
2658 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002659 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002660 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2662 }
2663
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 creationArgs.displayInstallOrientation =
2665 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002666
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002668 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
Lloyd Pique90c115d2018-09-18 21:39:42 -07002670 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671
2672 if (maxFrameBufferAcquiredBuffers >= 3) {
2673 nativeWindowSurface->preallocateBuffers();
2674 }
2675
2676 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002677 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002678 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002680 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002682 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2683 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002684 if (!state.isVirtual()) {
2685 LOG_ALWAYS_FATAL_IF(!displayId);
2686 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002687 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002688
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 display->setLayerStack(state.layerStack);
2690 display->setProjection(state.orientation, state.viewport, state.frame);
2691 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002692
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002694}
2695
Lloyd Pique347200f2017-12-14 17:00:15 -08002696void SurfaceFlinger::processDisplayChangesLocked() {
2697 // here we take advantage of Vector's copy-on-write semantics to
2698 // improve performance by skipping the transaction entirely when
2699 // know that the lists are identical
2700 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2701 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2702 if (!curr.isIdenticalTo(draw)) {
2703 mVisibleRegionsDirty = true;
2704 const size_t cc = curr.size();
2705 size_t dc = draw.size();
2706
2707 // find the displays that were removed
2708 // (ie: in drawing state but not in current state)
2709 // also handle displays that changed
2710 // (ie: displays that are in both lists)
2711 for (size_t i = 0; i < dc;) {
2712 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2713 if (j < 0) {
2714 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002716 // Save display ID before disconnecting.
2717 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002718 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002719
2720 if (!display->isVirtual()) {
2721 LOG_ALWAYS_FATAL_IF(!displayId);
2722 dispatchDisplayHotplugEvent(displayId->value, false);
2723 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002725
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002726 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 } else {
2728 // this display is in both lists. see if something changed.
2729 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2732 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2733 if (state_binder != draw_binder) {
2734 // changing the surface is like destroying and
2735 // recreating the DisplayDevice, so we just remove it
2736 // from the drawing state, so that it get re-added
2737 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002739 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 mDrawingState.displays.removeItemsAt(i);
2743 dc--;
2744 // at this point we must loop to the next item
2745 continue;
2746 }
2747
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752 if ((state.orientation != draw[i].orientation) ||
2753 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 }
2756 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 }
2759 }
2760 }
2761 ++i;
2762 }
2763
2764 // find displays that were added
2765 // (ie: in current state but not in drawing state)
2766 for (size_t i = 0; i < cc; i++) {
2767 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2768 const DisplayDeviceState& state(curr[i]);
2769
Lloyd Pique542307f2018-10-19 13:24:08 -07002770 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 sp<IGraphicBufferProducer> producer;
2772 sp<IGraphicBufferProducer> bqProducer;
2773 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002774 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002777 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 // Virtual displays without a surface are dormant:
2779 // they have external state (layer stack, projection,
2780 // etc.) but no internal state (i.e. a DisplayDevice).
2781 if (state.surface != nullptr) {
2782 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 int width = 0;
2785 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2786 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2787 int height = 0;
2788 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2789 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2790 int intFormat = 0;
2791 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2792 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002793 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002794
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 displayId =
2796 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002797 }
2798
2799 // TODO: Plumb requested format back up to consumer
2800
2801 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002802 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002803 bqProducer, bqConsumer,
2804 state.displayName);
2805
2806 dispSurface = vds;
2807 producer = vds;
2808 }
2809 } else {
2810 ALOGE_IF(state.surface != nullptr,
2811 "adding a supported display, but rendering "
2812 "surface is provided (%p), ignoring it",
2813 state.surface.get());
2814
Dominik Laskowski075d3172018-05-24 15:50:06 -07002815 displayId = state.displayId;
2816 LOG_ALWAYS_FATAL_IF(!displayId);
2817 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002818 producer = bqProducer;
2819 }
2820
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002821 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002824 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002825 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002826 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002827 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002828 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002829 }
2830 }
2831 }
2832 }
2833 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002834
2835 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002836}
2837
Mathias Agopian87baae12012-07-31 12:38:26 -07002838void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002839{
Dan Stoza7dde5992015-05-22 09:51:44 -07002840 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002841 mCurrentState.traverseInZOrder([](Layer* layer) {
2842 layer->notifyAvailableFrames();
2843 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002844
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 /*
2846 * Traversal of the children
2847 * (perform the transaction for each of them if needed)
2848 */
2849
Mathias Agopian3559b072012-08-15 13:46:03 -07002850 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002851 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002853 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854
2855 const uint32_t flags = layer->doTransaction(0);
2856 if (flags & Layer::eVisibleRegion)
2857 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002858
2859 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002860 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002861 }
Robert Carr2047fae2016-11-28 14:09:09 -08002862 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 }
2864
2865 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 */
2868
Mathias Agopiane57f2922012-08-09 16:29:12 -07002869 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002870 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002871 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002874 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002875 // The transform hint might have changed for some layers
2876 // (either because a display has changed, or because a layer
2877 // as changed).
2878 //
2879 // Walk through all the layers in currentLayers,
2880 // and update their transform hint.
2881 //
2882 // If a layer is visible only on a single display, then that
2883 // display is used to calculate the hint, otherwise we use the
2884 // default display.
2885 //
2886 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2887 // the hint is set before we acquire a buffer from the surface texture.
2888 //
2889 // NOTE: layer transactions have taken place already, so we use their
2890 // drawing state. However, SurfaceFlinger's own transaction has not
2891 // happened yet, so we must use the current state layer list
2892 // (soon to become the drawing state list).
2893 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002894 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002895 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002896 bool first = true;
2897 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002898 // NOTE: we rely on the fact that layers are sorted by
2899 // layerStack first (so we don't have to traverse the list
2900 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002902 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002903 currentlayerStack = layerStack;
2904 // figure out if this layerstack is mirrored
2905 // (more than one display) if so, pick the default display,
2906 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 hintDisplay = nullptr;
2908 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002909 if (display->getCompositionDisplay()
2910 ->belongsInOutput(layer->getLayerStack(),
2911 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 if (hintDisplay) {
2913 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002914 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002915 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002917 }
2918 }
2919 }
2920 }
Chet Haase91d25932013-04-11 15:24:55 -07002921
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002922 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002923 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2924 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002925
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002926 // could be null when this layer is using a layerStack
2927 // that is not visible on any display. Also can occur at
2928 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002929 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002930 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002931
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002933 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 if (hintDisplay) {
2935 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002936 }
Robert Carr2047fae2016-11-28 14:09:09 -08002937
2938 first = false;
2939 });
Mathias Agopian84300952012-11-21 16:02:13 -08002940 }
2941
2942
Mathias Agopian3559b072012-08-15 13:46:03 -07002943 /*
2944 * Perform our own transaction if needed
2945 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002946
2947 if (mLayersAdded) {
2948 mLayersAdded = false;
2949 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002950 mVisibleRegionsDirty = true;
2951 }
2952
2953 // some layers might have been removed, so
2954 // we need to update the regions they're exposing.
2955 if (mLayersRemoved) {
2956 mLayersRemoved = false;
2957 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002958 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002960 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002961 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002962 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002963 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002964 }
Robert Carr2047fae2016-11-28 14:09:09 -08002965 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 }
2967
Vishnu Nairec0ab382019-02-13 15:32:56 -08002968 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002970}
2971
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002972void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002973 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002974 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002975 return;
2976 }
2977
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002978 if (mVisibleRegionsDirty || mInputInfoChanged) {
2979 mInputInfoChanged = false;
2980 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002981 } else if (mInputWindowCommands.syncInputWindows) {
2982 // If the caller requested to sync input windows, but there are no
2983 // changes to input windows, notify immediately.
2984 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002985 }
2986
2987 executeInputWindowCommands();
2988}
2989
2990void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002991 Vector<InputWindowInfo> inputHandles;
2992
2993 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2994 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002995 // When calculating the screen bounds we ignore the transparent region since it may
2996 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002997 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002998 }
2999 });
chaviw291d88a2019-02-14 10:33:58 -08003000
3001 mInputFlinger->setInputWindows(inputHandles,
3002 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3003 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003004}
3005
Vishnu Nairec0ab382019-02-13 15:32:56 -08003006void SurfaceFlinger::commitInputWindowCommands() {
3007 mInputWindowCommands.merge(mPendingInputWindowCommands);
3008 mPendingInputWindowCommands.clear();
3009}
3010
chaviwfbe5d9c2018-12-26 12:23:37 -08003011void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003012 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3013 if (transferTouchFocusCommand.fromToken != nullptr &&
3014 transferTouchFocusCommand.toToken != nullptr &&
3015 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3016 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3017 transferTouchFocusCommand.toToken);
3018 }
3019 }
3020
3021 mInputWindowCommands.clear();
3022}
3023
Riley Andrews03414a12014-07-01 14:22:59 -07003024void SurfaceFlinger::updateCursorAsync()
3025{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003026 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003027 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003028 continue;
3029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3032 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003033 }
3034 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003035}
3036
chaviw61626f22018-11-15 16:26:27 -08003037void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3038 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003039 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003040 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003041 }
3042 layer->releasePendingBuffer(systemTime());
3043}
3044
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045void SurfaceFlinger::commitTransaction()
3046{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003047 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 for (const auto& l : mLayersPendingRemoval) {
3050 recordBufferingStats(l->getName().string(),
3051 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003052
Lloyd Pique07e33212018-12-18 16:33:37 -08003053 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003054 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003055 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003056 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057 }
3058 mLayersPendingRemoval.clear();
3059 }
3060
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003061 // If this transaction is part of a window animation then the next frame
3062 // we composite should be considered an animation as well.
3063 mAnimCompositionPending = mAnimTransactionPending;
3064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003066 // clear the "changed" flags in current state
3067 mCurrentState.colorMatrixChanged = false;
3068
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 mDrawingState.traverseInZOrder([](Layer* layer) {
3070 layer->commitChildList();
3071 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003072 mTransactionPending = false;
3073 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003074 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Lloyd Pique32cbe282018-10-19 13:09:22 -07003077void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003078 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003079 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003080 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003081
Lloyd Pique32cbe282018-10-19 13:09:22 -07003082 auto display = displayDevice->getCompositionDisplay();
3083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 Region aboveOpaqueLayers;
3085 Region aboveCoveredLayers;
3086 Region dirty;
3087
Mathias Agopian87baae12012-07-31 12:38:26 -07003088 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089
Robert Carr2047fae2016-11-28 14:09:09 -08003090 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003091 // start with the whole surface at its current location
3092 const Layer::State& s(layer->getDrawingState());
3093
Jesse Hall01e29052013-02-19 16:13:35 -08003094 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003095 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003096 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003097 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003098
Mathias Agopianab028732010-03-16 16:41:46 -07003099 /*
3100 * opaqueRegion: area of a surface that is fully opaque.
3101 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003103
3104 /*
3105 * visibleRegion: area of a surface that is visible on screen
3106 * and not fully transparent. This is essentially the layer's
3107 * footprint minus the opaque regions above it.
3108 * Areas covered by a translucent surface are considered visible.
3109 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003111
3112 /*
3113 * coveredRegion: area of a surface that is covered by all
3114 * visible regions above it (which includes the translucent areas).
3115 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003117
Jesse Halla8026d22012-09-25 13:25:04 -07003118 /*
3119 * transparentRegion: area of a surface that is hinted to be completely
3120 * transparent. This is only used to tell when the layer has no visible
3121 * non-transparent regions and can be removed from the layer list. It
3122 * does not affect the visibleRegion of this layer or any layers
3123 * beneath it. The hint may not be correct if apps don't respect the
3124 * SurfaceView restrictions (which, sadly, some don't).
3125 */
3126 Region transparentRegion;
3127
Mathias Agopianab028732010-03-16 16:41:46 -07003128
3129 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003130 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003131 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003132 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003135 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003136 if (!visibleRegion.isEmpty()) {
3137 // Remove the transparent area from the visible region
3138 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003139 if (tr.preserveRects()) {
3140 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003141 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003142 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003143 // transformation too complex, can't do the
3144 // transparent region optimization.
3145 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003146 }
Mathias Agopianab028732010-03-16 16:41:46 -07003147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148
Mathias Agopianab028732010-03-16 16:41:46 -07003149 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003151 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003152 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003153 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003154 // the opaque region is the layer's footprint
3155 opaqueRegion = visibleRegion;
3156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 }
3159
Robert Carre5f4f692018-01-12 13:12:28 -08003160 if (visibleRegion.isEmpty()) {
3161 layer->clearVisibilityRegions();
3162 return;
3163 }
3164
Mathias Agopianab028732010-03-16 16:41:46 -07003165 // Clip the covered region to the visible region
3166 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3167
3168 // Update aboveCoveredLayers for next (lower) layer
3169 aboveCoveredLayers.orSelf(visibleRegion);
3170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 // subtract the opaque region covered by the layers above us
3172 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173
3174 // compute this layer's dirty region
3175 if (layer->contentDirty) {
3176 // we need to invalidate the whole region
3177 dirty = visibleRegion;
3178 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003179 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 layer->contentDirty = false;
3181 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003182 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003183 * the exposed region consists of two components:
3184 * 1) what's VISIBLE now and was COVERED before
3185 * 2) what's EXPOSED now less what was EXPOSED before
3186 *
3187 * note that (1) is conservative, we start with the whole
3188 * visible region but only keep what used to be covered by
3189 * something -- which mean it may have been exposed.
3190 *
3191 * (2) handles areas that were not covered by anything but got
3192 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003193 */
Mathias Agopianab028732010-03-16 16:41:46 -07003194 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003195 const Region oldVisibleRegion = layer->visibleRegion;
3196 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003197 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3198 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 }
3200 dirty.subtractSelf(aboveOpaqueLayers);
3201
3202 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003203 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204
Mathias Agopianab028732010-03-16 16:41:46 -07003205 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003207
Jesse Halla8026d22012-09-25 13:25:04 -07003208 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209 layer->setVisibleRegion(visibleRegion);
3210 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003211 layer->setVisibleNonTransparentRegion(
3212 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003213 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214
Mathias Agopian87baae12012-07-31 12:38:26 -07003215 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216}
3217
Chia-I Wuab0c3192017-08-01 11:29:00 -07003218void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003219 for (const auto& [token, displayDevice] : mDisplays) {
3220 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003221 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003222 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003223 }
3224 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003225}
3226
Dan Stoza6b9454d2014-11-07 16:00:59 -08003227bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003229 ALOGV("handlePageFlip");
3230
Brian Andersond6927fb2016-07-23 23:37:30 -07003231 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232
Mathias Agopian4fec8732012-06-29 14:12:52 -07003233 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003234 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003235 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003236
3237 // Store the set of layers that need updates. This set must not change as
3238 // buffers are being latched, as this could result in a deadlock.
3239 // Example: Two producers share the same command stream and:
3240 // 1.) Layer 0 is latched
3241 // 2.) Layer 0 gets a new frame
3242 // 2.) Layer 1 gets a new frame
3243 // 3.) Layer 1 is latched.
3244 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3245 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003246 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003247 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003248 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003249 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003250 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003251 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003252 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003253 } else {
3254 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003256 } else {
3257 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258 }
Robert Carr2047fae2016-11-28 14:09:09 -08003259 });
3260
Lloyd Piquef2c79392018-12-20 16:23:33 -08003261 if (!mLayersWithQueuedFrames.empty()) {
3262 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3263 // writes to Layer current state. See also b/119481871
3264 Mutex::Autolock lock(mStateLock);
3265
3266 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003267 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003268 mLayersPendingRefresh.push_back(layer);
3269 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003270 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003271 if (layer->isBufferLatched()) {
3272 newDataLatched = true;
3273 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003274 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003275 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003276
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003277 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003278
3279 // If we will need to wake up at some time in the future to deal with a
3280 // queued frame that shouldn't be displayed during this vsync period, wake
3281 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003282 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003283 signalLayerUpdate();
3284 }
3285
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003286 // enter boot animation on first buffer latch
3287 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3288 ALOGI("Enter boot animation");
3289 mBootStage = BootStage::BOOTANIMATION;
3290 }
3291
Dan Stoza6b9454d2014-11-07 16:00:59 -08003292 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003293 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294}
3295
Mathias Agopianad456f92011-01-13 17:53:01 -08003296void SurfaceFlinger::invalidateHwcGeometry()
3297{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003299}
3300
Lloyd Pique32cbe282018-10-19 13:09:22 -07003301void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003302 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003304 // We only need to actually compose the display if:
3305 // 1) It is being handled by hardware composer, which may need this to
3306 // keep its virtual display state machine in sync, or
3307 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003309 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003310 return;
3311 }
3312
Dan Stoza9e56aa02015-11-02 13:00:03 -08003313 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003314 base::unique_fd readyFence;
3315 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003316
3317 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003318 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319}
3320
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003321bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3322 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003323 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003324 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003325
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326 auto display = displayDevice->getCompositionDisplay();
3327 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003328 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329
3330 const Region bounds(displayState.bounds);
3331 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003332 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003333 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003334
Peiyong Lind3788632018-09-18 16:01:31 -07003335 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003336 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003337
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003338 renderengine::DisplaySettings clientCompositionDisplay;
3339 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3340 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003341 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 if (hasClientComposition) {
3344 ALOGV("hasClientComposition");
3345
Alec Mouri6338c9d2019-02-07 16:57:51 -08003346 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003347 if (buf == nullptr) {
3348 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3349 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003350 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003351 return false;
3352 }
3353
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003354 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3355 clientCompositionDisplay.clip = displayState.scissor;
3356 const ui::Transform& displayTransform = displayState.transform;
3357 mat4 m;
3358 m[0][0] = displayTransform[0][0];
3359 m[0][1] = displayTransform[0][1];
3360 m[0][3] = displayTransform[0][2];
3361 m[1][0] = displayTransform[1][0];
3362 m[1][1] = displayTransform[1][1];
3363 m[1][3] = displayTransform[1][2];
3364 m[3][0] = displayTransform[2][0];
3365 m[3][1] = displayTransform[2][1];
3366 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003367 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003368
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003369 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003370 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003371 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003373 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003374 clientCompositionDisplay.outputDataspace = outputDataspace;
3375 clientCompositionDisplay.maxLuminance =
3376 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003377
Lloyd Pique441d5042018-10-18 16:49:51 -07003378 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003379 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003380 getHwComposer()
3381 .hasDisplayCapability(displayId,
3382 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003383
Peiyong Lind3788632018-09-18 16:01:31 -07003384 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003385 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3386 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003387 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003388 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003389 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003390
Mathias Agopian85d751c2012-08-29 16:59:24 -07003391 /*
3392 * and then, render the layers targeted at the framebuffer
3393 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003394
Dan Stoza9e56aa02015-11-02 13:00:03 -08003395 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003396 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003397 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003398 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003399 const Region viewportRegion(displayState.viewport);
3400 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003401 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003402 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003404 switch (layer->getCompositionType(displayDevice)) {
3405 case Hwc2::IComposerClient::Composition::CURSOR:
3406 case Hwc2::IComposerClient::Composition::DEVICE:
3407 case Hwc2::IComposerClient::Composition::SIDEBAND:
3408 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003409 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003410 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003411 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003412 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003413 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 // never clear the very first layer since we're
3415 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003416 renderengine::LayerSettings layerSettings;
3417 Region dummyRegion;
3418 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3419 layerSettings);
3420
3421 if (prepared) {
3422 layerSettings.source.buffer.buffer = nullptr;
3423 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3424 layerSettings.alpha = half(0.0);
3425 layerSettings.disableBlending = true;
3426 clientCompositionLayers.push_back(layerSettings);
3427 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003428 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003430 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003431 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003432 renderengine::LayerSettings layerSettings;
3433 bool prepared =
3434 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3435 if (prepared) {
3436 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003437 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003438 break;
3439 }
3440 default:
3441 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003442 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003443 } else {
3444 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003445 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003446 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003447 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003448
Alec Mouri820c7402019-01-23 13:02:39 -08003449 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003450 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003451 clientCompositionDisplay.clearRegion = clearRegion;
3452 if (!debugRegion.isEmpty()) {
3453 Region::const_iterator it = debugRegion.begin();
3454 Region::const_iterator end = debugRegion.end();
3455 while (it != end) {
3456 const Rect& rect = *it++;
3457 renderengine::LayerSettings layerSettings;
3458 layerSettings.source.buffer.buffer = nullptr;
3459 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3460 layerSettings.geometry.boundaries = rect.toFloatRect();
3461 layerSettings.alpha = half(1.0);
3462 clientCompositionLayers.push_back(layerSettings);
3463 }
3464 }
3465 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003466 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003467 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003468 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469}
3470
Chia-I Wu28e3a252018-09-07 12:05:02 -07003471void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003472 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003473 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003474}
3475
Dan Stoza7d89d062015-04-30 13:29:25 -07003476status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003477 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003478 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003480 const sp<Layer>& parent,
3481 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003482{
Dan Stoza7d89d062015-04-30 13:29:25 -07003483 // add this layer to the current state list
3484 {
3485 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003486 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003487 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3488 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003489 return NO_MEMORY;
3490 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003491 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003492 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003493 } else if (parent == nullptr) {
3494 lbc->onRemovedFromCurrentState();
3495 } else if (parent->isRemovedFromCurrentState()) {
3496 parent->addChild(lbc);
3497 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003498 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003499 parent->addChild(lbc);
3500 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003501
Yiwei Zhang243b3782018-05-15 17:40:04 -07003502 if (gbc != nullptr) {
3503 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3504 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3505 mMaxGraphicBufferProducerListSize,
3506 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3507 mGraphicBufferProducerList.size(),
3508 mMaxGraphicBufferProducerListSize, mNumLayers);
3509 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003510 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 }
3512
Mathias Agopian96f08192010-06-02 23:28:45 -07003513 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003514 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003515
Dan Stoza7d89d062015-04-30 13:29:25 -07003516 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003517}
3518
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003519uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003520 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003521}
3522
Mathias Agopian3f844832013-08-07 21:24:32 -07003523uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003524 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525}
3526
Mathias Agopian3f844832013-08-07 21:24:32 -07003527uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003528 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003529}
3530
3531uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003532 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003533 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003534 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003536 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 }
3538 return old;
3539}
3540
Marissa Wall713b63f2018-10-17 15:42:43 -07003541bool SurfaceFlinger::flushTransactionQueues() {
3542 Mutex::Autolock _l(mStateLock);
3543 auto it = mTransactionQueues.begin();
3544 while (it != mTransactionQueues.end()) {
3545 auto& [applyToken, transactionQueue] = *it;
3546
3547 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003548 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3549 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003550 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003551 break;
3552 }
Robert Carr14167e02019-02-13 13:50:55 -08003553 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003554 transactionQueue.pop();
3555 }
3556
3557 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3558 }
3559 return mTransactionQueues.empty();
3560}
3561
chaviwca27f252018-02-06 16:46:39 -08003562bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3563 for (const ComposerState& state : states) {
3564 // Here we need to check that the interface we're given is indeed
3565 // one of our own. A malicious client could give us a nullptr
3566 // IInterface, or one of its own or even one of our own but a
3567 // different type. All these situations would cause us to crash.
3568 if (state.client == nullptr) {
3569 return true;
3570 }
3571
3572 sp<IBinder> binder = IInterface::asBinder(state.client);
3573 if (binder == nullptr) {
3574 return true;
3575 }
3576
3577 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3578 return true;
3579 }
3580 }
3581 return false;
3582}
3583
Marissa Wall17b4e452018-12-26 16:32:34 -08003584bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3585 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003586 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003587 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3588 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3589 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3590 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3591 return false;
3592 }
3593
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 for (const ComposerState& state : states) {
3595 const layer_state_t& s = state.state;
3596 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3597 continue;
3598 }
3599 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003600 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 }
3602 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003604}
3605
3606void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3607 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003608 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003609 const InputWindowCommands& inputWindowCommands,
3610 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003611 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003612
3613 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3614
Mathias Agopian698c0872011-06-28 19:09:31 -07003615 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003616
chaviwca27f252018-02-06 16:46:39 -08003617 if (containsAnyInvalidClientState(states)) {
3618 return;
3619 }
3620
Marissa Wall713b63f2018-10-17 15:42:43 -07003621 // If its TransactionQueue already has a pending TransactionState or if it is pending
3622 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003623 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003624 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3625 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003626 setTransactionFlags(eTransactionNeeded);
3627 return;
3628 }
3629
Robert Carr14167e02019-02-13 13:50:55 -08003630 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003631}
3632
3633void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003634 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003635 const InputWindowCommands& inputWindowCommands,
3636 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003637 uint32_t transactionFlags = 0;
3638
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003639 if (flags & eAnimation) {
3640 // For window updates that are part of an animation we must wait for
3641 // previous animation "frames" to be handled.
3642 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003643 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003644 if (CC_UNLIKELY(err != NO_ERROR)) {
3645 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003646 // caller after a few seconds.
3647 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3648 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003649 mAnimTransactionPending = false;
3650 break;
3651 }
3652 }
3653 }
3654
chaviwca27f252018-02-06 16:46:39 -08003655 for (const DisplayState& display : displays) {
3656 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003657 }
3658
Marissa Walle2ffb422018-10-12 11:33:52 -07003659 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003660 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003661 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003662 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003663 // If the state doesn't require a traversal and there are callbacks, send them now
3664 if (!(clientStateFlags & eTraversalNeeded)) {
3665 mTransactionCompletedThread.sendCallbacks();
3666 }
3667 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003668
chaviw273171b2018-12-26 11:46:30 -08003669 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3670
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003671 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3672 // anyway. This can be used as a flush mechanism for previous async transactions.
3673 // Empty animation transaction can be used to simulate back-pressure, so also force a
3674 // transaction for empty animation transactions.
3675 if (transactionFlags == 0 &&
3676 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003677 transactionFlags = eTransactionNeeded;
3678 }
3679
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003681 if (mInterceptor->isEnabled()) {
3682 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003683 }
Irvel468051e2016-06-13 16:44:44 -07003684
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003686 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3687 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003688 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003689
3690 // if this is a synchronous transaction, wait for it to take effect
3691 // before returning.
3692 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003693 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003694 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003695 if (flags & eAnimation) {
3696 mAnimTransactionPending = true;
3697 }
chaviw95ef3c42019-02-14 10:55:09 -08003698
3699 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3700 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003701 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3702 if (CC_UNLIKELY(err != NO_ERROR)) {
3703 // just in case something goes wrong in SF, return to the
3704 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003705 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3706 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003707 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003708 break;
3709 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003710 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711 }
3712}
3713
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003714uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3715 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3716 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003717
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003719 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3720
3721 const uint32_t what = s.what;
3722 if (what & DisplayState::eSurfaceChanged) {
3723 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3724 state.surface = s.surface;
3725 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003726 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003727 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003728 if (what & DisplayState::eLayerStackChanged) {
3729 if (state.layerStack != s.layerStack) {
3730 state.layerStack = s.layerStack;
3731 flags |= eDisplayTransactionNeeded;
3732 }
3733 }
3734 if (what & DisplayState::eDisplayProjectionChanged) {
3735 if (state.orientation != s.orientation) {
3736 state.orientation = s.orientation;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 if (state.frame != s.frame) {
3740 state.frame = s.frame;
3741 flags |= eDisplayTransactionNeeded;
3742 }
3743 if (state.viewport != s.viewport) {
3744 state.viewport = s.viewport;
3745 flags |= eDisplayTransactionNeeded;
3746 }
3747 }
3748 if (what & DisplayState::eDisplaySizeChanged) {
3749 if (state.width != s.width) {
3750 state.width = s.width;
3751 flags |= eDisplayTransactionNeeded;
3752 }
3753 if (state.height != s.height) {
3754 state.height = s.height;
3755 flags |= eDisplayTransactionNeeded;
3756 }
3757 }
3758
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 return flags;
3760}
3761
Robert Carr14167e02019-02-13 13:50:55 -08003762bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003763 IPCThreadState* ipc = IPCThreadState::self();
3764 const int pid = ipc->getCallingPid();
3765 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003766 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003767 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003768 return false;
3769 }
3770 return true;
3771}
3772
Robert Carr14167e02019-02-13 13:50:55 -08003773uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3774 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003775 const layer_state_t& s = composerState.state;
3776 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3777
Mathias Agopian13127d82013-03-05 17:47:11 -08003778 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003779 if (layer == nullptr) {
3780 return 0;
3781 }
3782
chaviw8b3871a2017-11-01 17:41:01 -07003783 uint32_t flags = 0;
3784
Garfield Tan8a3083e2018-12-03 13:21:07 -08003785 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003786 bool geometryAppliesWithResize =
3787 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003788
3789 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3790 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003791 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003792 layer->pushPendingState();
3793 }
3794
chaviw8b3871a2017-11-01 17:41:01 -07003795 if (what & layer_state_t::ePositionChanged) {
3796 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3797 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003798 }
chaviw8b3871a2017-11-01 17:41:01 -07003799 }
3800 if (what & layer_state_t::eLayerChanged) {
3801 // NOTE: index needs to be calculated before we update the state
3802 const auto& p = layer->getParent();
3803 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003804 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003805 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003806 mCurrentState.layersSortedByZ.removeAt(idx);
3807 mCurrentState.layersSortedByZ.add(layer);
3808 // we need traversal (state changed)
3809 // AND transaction (list changed)
3810 flags |= eTransactionNeeded|eTraversalNeeded;
3811 }
chaviw8b3871a2017-11-01 17:41:01 -07003812 } else {
3813 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003814 flags |= eTransactionNeeded|eTraversalNeeded;
3815 }
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 }
3818 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003819 // NOTE: index needs to be calculated before we update the state
3820 const auto& p = layer->getParent();
3821 if (p == nullptr) {
3822 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3823 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3824 mCurrentState.layersSortedByZ.removeAt(idx);
3825 mCurrentState.layersSortedByZ.add(layer);
3826 // we need traversal (state changed)
3827 // AND transaction (list changed)
3828 flags |= eTransactionNeeded|eTraversalNeeded;
3829 }
3830 } else {
3831 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3832 flags |= eTransactionNeeded|eTraversalNeeded;
3833 }
chaviw8b3871a2017-11-01 17:41:01 -07003834 }
3835 }
3836 if (what & layer_state_t::eSizeChanged) {
3837 if (layer->setSize(s.w, s.h)) {
3838 flags |= eTraversalNeeded;
3839 }
3840 }
3841 if (what & layer_state_t::eAlphaChanged) {
3842 if (layer->setAlpha(s.alpha))
3843 flags |= eTraversalNeeded;
3844 }
3845 if (what & layer_state_t::eColorChanged) {
3846 if (layer->setColor(s.color))
3847 flags |= eTraversalNeeded;
3848 }
Peiyong Lind3788632018-09-18 16:01:31 -07003849 if (what & layer_state_t::eColorTransformChanged) {
3850 if (layer->setColorTransform(s.colorTransform)) {
3851 flags |= eTraversalNeeded;
3852 }
3853 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003854 if (what & layer_state_t::eBackgroundColorChanged) {
3855 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3856 flags |= eTraversalNeeded;
3857 }
3858 }
chaviw8b3871a2017-11-01 17:41:01 -07003859 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003860 // TODO: b/109894387
3861 //
3862 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3863 // rotation. To see the problem observe that if we have a square parent, and a child
3864 // of the same size, then we rotate the child 45 degrees around it's center, the child
3865 // must now be cropped to a non rectangular 8 sided region.
3866 //
3867 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3868 // private API, and the WindowManager only uses rotation in one case, which is on a top
3869 // level layer in which cropping is not an issue.
3870 //
3871 // However given that abuse of rotation matrices could lead to surfaces extending outside
3872 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3873 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3874 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003875 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003876 flags |= eTraversalNeeded;
3877 }
3878 if (what & layer_state_t::eTransparentRegionChanged) {
3879 if (layer->setTransparentRegionHint(s.transparentRegion))
3880 flags |= eTraversalNeeded;
3881 }
3882 if (what & layer_state_t::eFlagsChanged) {
3883 if (layer->setFlags(s.flags, s.mask))
3884 flags |= eTraversalNeeded;
3885 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003886 if (what & layer_state_t::eCropChanged_legacy) {
3887 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003888 flags |= eTraversalNeeded;
3889 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003890 if (what & layer_state_t::eCornerRadiusChanged) {
3891 if (layer->setCornerRadius(s.cornerRadius))
3892 flags |= eTraversalNeeded;
3893 }
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (what & layer_state_t::eLayerStackChanged) {
3895 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3896 // We only allow setting layer stacks for top level layers,
3897 // everything else inherits layer stack from its parent.
3898 if (layer->hasParent()) {
3899 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3900 layer->getName().string());
3901 } else if (idx < 0) {
3902 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3903 "that also does not appear in the top level layer list. Something"
3904 " has gone wrong.", layer->getName().string());
3905 } else if (layer->setLayerStack(s.layerStack)) {
3906 mCurrentState.layersSortedByZ.removeAt(idx);
3907 mCurrentState.layersSortedByZ.add(layer);
3908 // we need traversal (state changed)
3909 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003910 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003911 }
3912 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003913 if (what & layer_state_t::eDeferTransaction_legacy) {
3914 if (s.barrierHandle_legacy != nullptr) {
3915 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3916 } else if (s.barrierGbp_legacy != nullptr) {
3917 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003918 if (authenticateSurfaceTextureLocked(gbp)) {
3919 const auto& otherLayer =
3920 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003921 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003922 } else {
3923 ALOGE("Attempt to defer transaction to to an"
3924 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003925 }
3926 }
chaviw8b3871a2017-11-01 17:41:01 -07003927 // We don't trigger a traversal here because if no other state is
3928 // changed, we don't want this to cause any more work
3929 }
3930 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003931 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003932 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003933 if (!hadParent) {
3934 mCurrentState.layersSortedByZ.remove(layer);
3935 }
chaviw8b3871a2017-11-01 17:41:01 -07003936 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003937 }
chaviw8b3871a2017-11-01 17:41:01 -07003938 }
3939 if (what & layer_state_t::eReparentChildren) {
3940 if (layer->reparentChildren(s.reparentHandle)) {
3941 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003942 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003943 }
chaviw8b3871a2017-11-01 17:41:01 -07003944 if (what & layer_state_t::eDetachChildren) {
3945 layer->detachChildren();
3946 }
3947 if (what & layer_state_t::eOverrideScalingModeChanged) {
3948 layer->setOverrideScalingMode(s.overrideScalingMode);
3949 // We don't trigger a traversal here because if no other state is
3950 // changed, we don't want this to cause any more work
3951 }
Marissa Wall61c58622018-07-18 10:12:20 -07003952 if (what & layer_state_t::eTransformChanged) {
3953 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3954 }
3955 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3956 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3957 flags |= eTraversalNeeded;
3958 }
3959 if (what & layer_state_t::eCropChanged) {
3960 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3961 }
Marissa Wall861616d2018-10-22 12:52:23 -07003962 if (what & layer_state_t::eFrameChanged) {
3963 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3964 }
Marissa Wall61c58622018-07-18 10:12:20 -07003965 if (what & layer_state_t::eAcquireFenceChanged) {
3966 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3967 }
3968 if (what & layer_state_t::eDataspaceChanged) {
3969 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3970 }
3971 if (what & layer_state_t::eHdrMetadataChanged) {
3972 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3973 }
3974 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3975 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3976 }
3977 if (what & layer_state_t::eApiChanged) {
3978 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eSidebandStreamChanged) {
3981 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3982 }
Robert Carr720e5062018-07-30 17:45:14 -07003983 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003984 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3985 layer->setInputInfo(s.inputInfo);
3986 flags |= eTraversalNeeded;
3987 } else {
3988 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3989 }
Robert Carr720e5062018-07-30 17:45:14 -07003990 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003991 if (what & layer_state_t::eMetadataChanged) {
3992 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3993 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003994 std::vector<sp<CallbackHandle>> callbackHandles;
3995 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3996 mTransactionCompletedThread.run();
3997 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3998 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3999 }
4000 }
Marissa Wall73411622019-01-25 10:45:41 -08004001
4002 if (what & layer_state_t::eBufferChanged) {
4003 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4004 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4005 s.buffer);
4006 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004007 if (what & layer_state_t::eCachedBufferChanged) {
4008 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004009 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4010 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004011 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4012 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004013 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4014 // Do not put anything that updates layer state or modifies flags after
4015 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004016 return flags;
4017}
4018
chaviw273171b2018-12-26 11:46:30 -08004019uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4020 uint32_t flags = 0;
4021 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4022 flags |= eTraversalNeeded;
4023 }
4024
chaviwa911b102019-02-14 10:18:33 -08004025 if (inputWindowCommands.syncInputWindows) {
4026 flags |= eTraversalNeeded;
4027 }
4028
Vishnu Nairec0ab382019-02-13 15:32:56 -08004029 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004030 return flags;
4031}
4032
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004033status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4034 uint32_t h, PixelFormat format, uint32_t flags,
4035 LayerMetadata metadata, sp<IBinder>* handle,
4036 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004037 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004038 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004039 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004040 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004041 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004042
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004043 status_t result = NO_ERROR;
4044
4045 sp<Layer> layer;
4046
Cody Northropbc755282017-03-31 12:00:08 -06004047 String8 uniqueName = getUniqueLayerName(name);
4048
Mathias Agopian3165cc22012-08-08 19:42:09 -07004049 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004050 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004051 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4052 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004053
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004055 case ISurfaceComposerClient::eFXSurfaceBufferState:
4056 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4057 break;
chaviw13fdc492017-06-27 12:40:18 -07004058 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004059 // check if buffer size is set for color layer.
4060 if (w > 0 || h > 0) {
4061 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4062 int(w), int(h));
4063 return BAD_VALUE;
4064 }
4065
chaviw13fdc492017-06-27 12:40:18 -07004066 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004067 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004068 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004069 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004070 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004071 // check if buffer size is set for container layer.
4072 if (w > 0 || h > 0) {
4073 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4074 int(w), int(h));
4075 return BAD_VALUE;
4076 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004077 result = createContainerLayer(client,
4078 uniqueName, w, h, flags,
4079 handle, &layer);
4080 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004081 default:
4082 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 break;
4084 }
4085
Dan Stoza7d89d062015-04-30 13:29:25 -07004086 if (result != NO_ERROR) {
4087 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004089
Chia-I Wuab0c3192017-08-01 11:29:00 -07004090 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4091 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004092 if (metadata.has(METADATA_WINDOW_TYPE)) {
4093 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4094 if (windowType == 441731) {
4095 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4096 layer->setPrimaryDisplayOnly();
4097 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004098 }
4099
Evan Roskyef876c92019-01-25 17:46:06 -08004100 layer->setMetadata(metadata);
Albert Chaulk479c60c2017-01-27 14:21:34 -05004101
Robert Carrb89ea9d2018-12-10 13:01:14 -08004102 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4103 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4104 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004105 if (result != NO_ERROR) {
4106 return result;
4107 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004108 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004109
4110 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004111 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112}
4113
Cody Northropbc755282017-03-31 12:00:08 -06004114String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4115{
4116 bool matchFound = true;
4117 uint32_t dupeCounter = 0;
4118
4119 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4120 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4121
Dan Stoza436ccf32018-06-21 12:10:12 -07004122 // Grab the state lock since we're accessing mCurrentState
4123 Mutex::Autolock lock(mStateLock);
4124
Cody Northropbc755282017-03-31 12:00:08 -06004125 // Loop over layers until we're sure there is no matching name
4126 while (matchFound) {
4127 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004128 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004129 if (layer->getName() == uniqueName) {
4130 matchFound = true;
4131 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4132 }
4133 });
4134 }
4135
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004136 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4137 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004138
4139 return uniqueName;
4140}
4141
Marissa Wallfd668622018-05-10 10:21:13 -07004142status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4143 uint32_t w, uint32_t h, uint32_t flags,
4144 PixelFormat& format, sp<IBinder>* handle,
4145 sp<IGraphicBufferProducer>* gbp,
4146 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004148 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 case PIXEL_FORMAT_TRANSPARENT:
4150 case PIXEL_FORMAT_TRANSLUCENT:
4151 format = PIXEL_FORMAT_RGBA_8888;
4152 break;
4153 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004154 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 break;
4156 }
4157
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004158 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004159 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004160 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004162 *handle = layer->getHandle();
4163 *gbp = layer->getProducer();
4164 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004165 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166
Marissa Wallfd668622018-05-10 10:21:13 -07004167 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004168 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169}
4170
Marissa Wall61c58622018-07-18 10:12:20 -07004171status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4172 uint32_t w, uint32_t h, uint32_t flags,
4173 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004174 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004175 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004176 *handle = layer->getHandle();
4177 *outLayer = layer;
4178
4179 return NO_ERROR;
4180}
4181
chaviw13fdc492017-06-27 12:40:18 -07004182status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004183 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004184 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004186 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004187 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004189}
4190
Robert Carr6b3f6c52018-08-13 13:05:17 -07004191status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4192 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4193 sp<IBinder>* handle, sp<Layer>* outLayer)
4194{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004195 *outLayer =
4196 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004197 *handle = (*outLayer)->getHandle();
4198 return NO_ERROR;
4199}
4200
4201
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004202void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004203 mLayersPendingRemoval.add(layer);
4204 mLayersRemoved = true;
4205 setTransactionFlags(eTransactionNeeded);
4206}
4207
Robert Carr695d5282018-12-18 15:27:58 -08004208void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004209{
Robert Carr2e102c92018-10-23 12:11:15 -07004210 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004211 // If a layer has a parent, we allow it to out-live it's handle
4212 // with the idea that the parent holds a reference and will eventually
4213 // be cleaned up. However no one cleans up the top-level so we do so
4214 // here.
4215 if (layer->getParent() == nullptr) {
4216 mCurrentState.layersSortedByZ.remove(layer);
4217 }
4218 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004219 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004220}
4221
Mathias Agopianb60314a2012-04-10 22:09:54 -07004222// ---------------------------------------------------------------------------
4223
Andy McFadden13a082e2012-08-24 10:16:42 -07004224void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004225 const auto display = getDefaultDisplayDeviceLocked();
4226 if (!display) return;
4227
4228 const sp<IBinder> token = display->getDisplayToken().promote();
4229 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004230
Jesse Hall01e29052013-02-19 16:13:35 -08004231 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004232 Vector<ComposerState> state;
4233 Vector<DisplayState> displays;
4234 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004235 d.what = DisplayState::eDisplayProjectionChanged |
4236 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004237 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004238 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004239 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004240 d.frame.makeInvalid();
4241 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004242 d.width = 0;
4243 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004244 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004245 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004246
Dominik Laskowskie9774092018-12-11 10:04:24 -08004247 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004248
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 const nsecs_t vsyncPeriod = getVsyncPeriod();
4250 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004251
Brian Andersond0010582017-03-07 13:20:31 -08004252 // Use phase of 0 since phase is not known.
4253 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004254 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004255 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004256}
4257
4258void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004259 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 postMessageAsync(
4261 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004262}
4263
Dominik Laskowskie9774092018-12-11 10:04:24 -08004264void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 if (display->isVirtual()) {
4266 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004267 return;
4268 }
4269
Dominik Laskowski075d3172018-05-24 15:50:06 -07004270 const auto displayId = display->getId();
4271 LOG_ALWAYS_FATAL_IF(!displayId);
4272
Dominik Laskowski34157762018-10-31 13:07:19 -07004273 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274
4275 int currentMode = display->getPowerMode();
4276 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 return;
4278 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004279
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280 display->setPowerMode(mode);
4281
Lloyd Pique4dccc412018-01-22 17:21:36 -08004282 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004283 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004284 }
4285
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004286 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004287 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004290 mScheduler->onScreenAcquired(mAppConnectionHandle);
4291 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004292 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004293
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004295 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004296 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004297
4298 struct sched_param param = {0};
4299 param.sched_priority = 1;
4300 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4301 ALOGW("Couldn't set SCHED_FIFO on display on");
4302 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004303 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004304 // Turn off the display
4305 struct sched_param param = {0};
4306 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4307 ALOGW("Couldn't set SCHED_OTHER on display off");
4308 }
4309
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004311 mScheduler->disableHardwareVsync(true);
4312 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004313 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314
Dominik Laskowski075d3172018-05-24 15:50:06 -07004315 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004316 mVisibleRegionsDirty = true;
4317 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004318 } else if (mode == HWC_POWER_MODE_DOZE ||
4319 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004320 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004322 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004323 mScheduler->onScreenAcquired(mAppConnectionHandle);
4324 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004325 }
4326 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4327 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004329 mScheduler->disableHardwareVsync(true);
4330 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004331 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004332 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004333 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004334 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004335 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004336 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004337
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004338 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004339 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004340 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004341 // Update refresh rate stats.
4342 mRefreshRateStats->setPowerMode(mode);
4343 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004344 }
4345
Dominik Laskowski34157762018-10-31 13:07:19 -07004346 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004347}
4348
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004349void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004350 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004351 const auto display = getDisplayDevice(displayToken);
4352 if (!display) {
4353 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4354 displayToken.get());
4355 } else if (display->isVirtual()) {
4356 ALOGW("Attempt to set power mode %d for virtual display", mode);
4357 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004358 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004359 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004360 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004361}
4362
4363// ---------------------------------------------------------------------------
4364
Dominik Laskowskic2867142019-01-21 11:33:38 -08004365status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4366 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004367 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004368
Mathias Agopianbd115332013-04-18 16:41:04 -07004369 IPCThreadState* ipc = IPCThreadState::self();
4370 const int pid = ipc->getCallingPid();
4371 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004372
Mathias Agopianbd115332013-04-18 16:41:04 -07004373 if ((uid != AID_SHELL) &&
4374 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4376 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004377 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004378 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004379 // (this would indicate SF is stuck, but we want to be able to
4380 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004381 status_t err = mStateLock.timedLock(s2ns(1));
4382 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004383 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004384 StringAppendF(&result,
4385 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4386 "(no locks held)\n",
4387 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004388 }
4389
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004391
Dominik Laskowskic2867142019-01-21 11:33:38 -08004392 static const std::unordered_map<std::string, Dumper> dumpers = {
4393 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4394 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4395 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004396 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004397 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004398 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004399 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4400 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004401 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4402 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4403 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4404 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4405 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4406 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004407 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4409 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004410
Dominik Laskowskic2867142019-01-21 11:33:38 -08004411 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004412
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4414 (it->second)(args, asProto, result);
4415 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004416 if (asProto) {
4417 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4418 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4419 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004420 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004421 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004422 }
4423
Mathias Agopian9795c422009-08-26 16:36:26 -07004424 if (locked) {
4425 mStateLock.unlock();
4426 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004427 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004429 return NO_ERROR;
4430}
4431
Dominik Laskowskic2867142019-01-21 11:33:38 -08004432void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 mCurrentState.traverseInZOrder(
4434 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004435}
4436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004438 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004439
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440 if (args.size() > 1) {
4441 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004442 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004443 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004444 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004445 }
Robert Carr2047fae2016-11-28 14:09:09 -08004446 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004447 } else {
4448 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 }
4450}
4451
Dominik Laskowskic2867142019-01-21 11:33:38 -08004452void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004453 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004454 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004455 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004456 }
Robert Carr2047fae2016-11-28 14:09:09 -08004457 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004458
Svetoslavd85084b2014-03-20 10:28:31 -07004459 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004460}
4461
Dominik Laskowskic2867142019-01-21 11:33:38 -08004462void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4463 mTimeStats->parseArgs(asProto, args, result);
4464}
4465
Jamie Gennis6547ff42013-07-16 20:12:42 -07004466// This should only be called from the main thread. Otherwise it would need
4467// the lock and should use mCurrentState rather than mDrawingState.
4468void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004469 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004470 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004471 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004472
4473 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4474}
4475
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004477 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004478
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004479 if (isLayerTripleBufferingDisabled())
4480 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004481
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4483 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4484 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4485 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4486 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4487 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004488 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004489}
4490
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004491void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004492 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004493 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004494 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004495 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004496
Ana Krulecba13ab32019-02-20 14:14:12 -08004497 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4498 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4499 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004500 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004501}
4502
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4504 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004505 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4506 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004507 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004508 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004510 }
David Sodman4a36e932017-11-07 14:29:47 -08004511 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004512 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004513 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4515 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004516}
4517
Dan Stozae77c7662016-05-13 11:37:28 -07004518void SurfaceFlinger::recordBufferingStats(const char* layerName,
4519 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004520 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4521 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004522 for (const auto& segment : history) {
4523 if (!segment.usedThirdBuffer) {
4524 stats.twoBufferTime += segment.totalTime;
4525 }
4526 if (segment.occupancyAverage < 1.0f) {
4527 stats.doubleBufferedTime += segment.totalTime;
4528 } else if (segment.occupancyAverage < 2.0f) {
4529 stats.tripleBufferedTime += segment.totalTime;
4530 }
4531 ++stats.numSegments;
4532 stats.totalTime += segment.totalTime;
4533 }
4534}
4535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4537 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004538
4539 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4540 const size_t count = currentLayers.size();
4541 for (size_t i=0 ; i<count ; i++) {
4542 currentLayers[i]->dumpFrameEvents(result);
4543 }
4544}
4545
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004547 result.append("Buffering stats:\n");
4548 result.append(" [Layer name] <Active time> <Two buffer> "
4549 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004550 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004551 typedef std::tuple<std::string, float, float, float> BufferTuple;
4552 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004553 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004554 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004555 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004556 if (stats.numSegments == 0) {
4557 continue;
4558 }
4559 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4560 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4561 stats.totalTime;
4562 float doubleBufferRatio = static_cast<float>(
4563 stats.doubleBufferedTime) / stats.totalTime;
4564 float tripleBufferRatio = static_cast<float>(
4565 stats.tripleBufferedTime) / stats.totalTime;
4566 sorted.insert({activeTime, {name, twoBufferRatio,
4567 doubleBufferRatio, tripleBufferRatio}});
4568 }
4569 for (const auto& sortedPair : sorted) {
4570 float activeTime = sortedPair.first;
4571 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4573 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004574 }
4575 result.append("\n");
4576}
4577
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004579 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004580 const auto displayId = display->getId();
4581 if (!displayId) {
4582 continue;
4583 }
4584 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004585 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004586 continue;
4587 }
4588
Yiwei Zhang5434a782018-12-05 18:06:32 -08004589 StringAppendF(&result,
4590 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4591 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 uint8_t port;
4593 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004594 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004595 result.append("no identification data\n");
4596 continue;
4597 }
4598
4599 if (!isEdid(data)) {
4600 result.append("unknown identification data: ");
4601 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004603 }
4604 result.append("\n");
4605 continue;
4606 }
4607
4608 const auto edid = parseEdid(data);
4609 if (!edid) {
4610 result.append("invalid EDID: ");
4611 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004613 }
4614 result.append("\n");
4615 continue;
4616 }
4617
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 result.append(edid->displayName.data(), edid->displayName.length());
4620 result.append("\"\n");
4621 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004622}
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4625 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4626 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4627 StringAppendF(&result, "DisplayColorSetting: %s\n",
4628 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004629
4630 // TODO: print out if wide-color mode is active or not
4631
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004632 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004633 const auto displayId = display->getId();
4634 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635 continue;
4636 }
4637
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004639 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004640 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004642 }
4643
Lloyd Pique32cbe282018-10-19 13:09:22 -07004644 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004645 StringAppendF(&result, " Current color mode: %s (%d)\n",
4646 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004647 }
4648 result.append("\n");
4649}
4650
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004651LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004652 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004653 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4654 const State& state = useDrawing ? mDrawingState : mCurrentState;
4655 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004656 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004657 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004658 });
4659
4660 return layersProto;
4661}
4662
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004663LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4664 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004665 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004666
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004667 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004668 resolution->set_w(displayDevice->getWidth());
4669 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004670
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004671 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004672 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004673
Lloyd Pique32cbe282018-10-19 13:09:22 -07004674 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4675 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4676 layersProto.set_global_transform(displayState.orientation);
4677
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004678 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004679 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004680 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004681 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004682 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004683 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004684 }
4685 });
4686
4687 return layersProto;
4688}
4689
Dominik Laskowskic2867142019-01-21 11:33:38 -08004690void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4691 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 Colorizer colorizer(colorize);
4693
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694 // figure out if we're stuck somewhere
4695 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4698
4699 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004700 * Dump library configuration.
4701 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702
4703 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004704 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004706 appendSfConfigString(result);
4707 appendUiConfigString(result);
4708 appendGuiConfigString(result);
4709 result.append("\n");
4710
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004711 result.append("\nDisplay identification data:\n");
4712 dumpDisplayIdentificationData(result);
4713
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004714 result.append("\nWide-Color information:\n");
4715 dumpWideColorInfo(result);
4716
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004718 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004720 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004721 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004722
Andy McFadden41d67d72014-04-25 16:58:34 -07004723 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004724 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004725 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004726 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004727 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004728
Dan Stozab90cf072015-03-05 11:05:59 -08004729 dumpStaticScreenStats(result);
4730 result.append("\n");
4731
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004733
Dan Stozae77c7662016-05-13 11:37:28 -07004734 dumpBufferingStats(result);
4735
Andy McFadden4803b742012-09-24 19:07:20 -07004736 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737 * Dump the visible layer list
4738 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4741 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4742 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004743 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004744
Chia-I Wu2f884132018-09-13 15:17:58 -07004745 {
4746 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4747 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004749 result.append("\n");
4750 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751
4752 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004753 * Dump Display state
4754 */
4755
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004758 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004759 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004760 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004761 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004762 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004763
4764 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765 * Dump SurfaceFlinger global state
4766 */
4767
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004769 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004772 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773
Dominik Laskowski075d3172018-05-24 15:50:06 -07004774 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004775 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4776 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4778 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004779 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004780 StringAppendF(&result,
4781 " transaction-flags : %08x\n"
4782 " gpu_to_cpu_unsupported : %d\n",
4783 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004785 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 displayId && getHwComposer().isConnected(*displayId)) {
4787 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result,
4789 " refresh-rate : %f fps\n"
4790 " x-dpi : %f\n"
4791 " y-dpi : %f\n",
4792 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4793 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004794 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004795
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797
Dan Stozae22aec72016-08-01 13:20:59 -07004798 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004799 * Tracing state
4800 */
4801 mTracing.dump(result);
4802 result.append("\n");
4803
4804 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004805 * HWC layer minidump
4806 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004807 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004808 const auto displayId = display->getId();
4809 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004810 continue;
4811 }
4812
Yiwei Zhang5434a782018-12-05 18:06:32 -08004813 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004814 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004815 const sp<DisplayDevice> displayDevice = display;
4816 mCurrentState.traverseInZOrder(
4817 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004818 result.append("\n");
4819 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
4821 /*
4822 * Dump HWComposer state
4823 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004824 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004825 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004826 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004827 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
4831 /*
4832 * Dump gralloc state
4833 */
4834 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4835 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004836
4837 /*
4838 * Dump VrFlinger state if in use.
4839 */
4840 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4841 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004843 result.append("\n");
4844 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004845
4846 /**
4847 * Scheduler dump state.
4848 */
Ana Krulecc2870422019-01-29 19:00:58 -08004849 result.append("\nScheduler state:\n");
4850 result.append(mScheduler->doDump() + "\n");
4851 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852}
4853
Dominik Laskowski075d3172018-05-24 15:50:06 -07004854const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004855 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004856 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004857 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004858 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004859 }
4860 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004861
Dominik Laskowski34157762018-10-31 13:07:19 -07004862 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004863 static const Vector<sp<Layer>> empty;
4864 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004865}
4866
Chia-I Wu28f320b2018-05-03 11:02:56 -07004867void SurfaceFlinger::updateColorMatrixLocked() {
4868 mat4 colorMatrix;
4869 if (mGlobalSaturationFactor != 1.0f) {
4870 // Rec.709 luma coefficients
4871 float3 luminance{0.213f, 0.715f, 0.072f};
4872 luminance *= 1.0f - mGlobalSaturationFactor;
4873 mat4 saturationMatrix = mat4(
4874 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4875 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4876 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4877 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4878 );
4879 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4880 } else {
4881 colorMatrix = mClientColorMatrix * mDaltonizer();
4882 }
4883
4884 if (mCurrentState.colorMatrix != colorMatrix) {
4885 mCurrentState.colorMatrix = colorMatrix;
4886 mCurrentState.colorMatrixChanged = true;
4887 setTransactionFlags(eTransactionNeeded);
4888 }
4889}
4890
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004891status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004892#pragma clang diagnostic push
4893#pragma clang diagnostic error "-Wswitch-enum"
4894 switch (static_cast<ISurfaceComposerTag>(code)) {
4895 // These methods should at minimum make sure that the client requested
4896 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004897 case BOOT_FINISHED:
4898 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004899 case CREATE_DISPLAY:
4900 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004901 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004902 case GET_ACTIVE_COLOR_MODE:
4903 case GET_ANIMATION_FRAME_STATS:
4904 case GET_HDR_CAPABILITIES:
4905 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004906 case SET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004908 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004909 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004910 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004911 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4912 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004913 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4914 IPCThreadState* ipc = IPCThreadState::self();
4915 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4916 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004917 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 }
Robert Carr1db73f62016-12-21 12:58:51 -08004919 return OK;
4920 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004922 IPCThreadState* ipc = IPCThreadState::self();
4923 const int pid = ipc->getCallingPid();
4924 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4926 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004927 return PERMISSION_DENIED;
4928 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 // Used by apps to hook Choreographer to SurfaceFlinger.
4932 case CREATE_DISPLAY_EVENT_CONNECTION:
4933 // The following calls are currently used by clients that do not
4934 // request necessary permissions. However, they do not expose any secret
4935 // information, so it is OK to pass them.
4936 case AUTHENTICATE_SURFACE:
4937 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004938 case GET_PHYSICAL_DISPLAY_IDS:
4939 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004941 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 case GET_DISPLAY_CONFIGS:
4943 case GET_DISPLAY_STATS:
4944 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4945 // Calling setTransactionState is safe, because you need to have been
4946 // granted a reference to Client* and Handle* to do anything with it.
4947 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004948 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004949 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004950 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004951 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004952 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004953 return OK;
4954 }
4955 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004956 case CAPTURE_SCREEN:
4957 case ADD_REGION_SAMPLING_LISTENER:
4958 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004960 IPCThreadState* ipc = IPCThreadState::self();
4961 const int pid = ipc->getCallingPid();
4962 const int uid = ipc->getCallingUid();
4963 if ((uid != AID_GRAPHICS) &&
4964 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4965 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4966 return PERMISSION_DENIED;
4967 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004968 return OK;
4969 }
4970 // The following codes are deprecated and should never be allowed to access SF.
4971 case CONNECT_DISPLAY_UNUSED:
4972 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4973 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4974 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004975 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004976 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977
4978 // These codes are used for the IBinder protocol to either interrogate the recipient
4979 // side of the transaction for its canonical interface descriptor or to dump its state.
4980 // We let them pass by default.
4981 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4982 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4983 code == IBinder::SYSPROPS_TRANSACTION) {
4984 return OK;
4985 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004986 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004987 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004988 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004989 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4990 return OK;
4991 }
4992 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4993 return PERMISSION_DENIED;
4994#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004995}
4996
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4998 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004999 status_t credentialCheck = CheckTransactCodeCredentials(code);
5000 if (credentialCheck != OK) {
5001 return credentialCheck;
5002 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5005 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005006 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005007 IPCThreadState* ipc = IPCThreadState::self();
5008 const int uid = ipc->getCallingUid();
5009 if (CC_UNLIKELY(uid != AID_SYSTEM
5010 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005011 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005012 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005013 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 return PERMISSION_DENIED;
5015 }
5016 int n;
5017 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005018 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005019 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 return NO_ERROR;
5021 case 1002: // SHOW_UPDATES
5022 n = data.readInt32();
5023 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005024 invalidateHwcGeometry();
5025 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005026 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005027 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005028 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005029 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005031 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005032 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005033 setTransactionFlags(
5034 eTransactionNeeded|
5035 eDisplayTransactionNeeded|
5036 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005037 return NO_ERROR;
5038 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005039 case 1006:{ // send empty update
5040 signalRefresh();
5041 return NO_ERROR;
5042 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005043 case 1008: // toggle use of hw composer
5044 n = data.readInt32();
5045 mDebugDisableHWC = n ? 1 : 0;
5046 invalidateHwcGeometry();
5047 repaintEverything();
5048 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005049 case 1009: // toggle use of transform hint
5050 n = data.readInt32();
5051 mDebugDisableTransformHint = n ? 1 : 0;
5052 invalidateHwcGeometry();
5053 repaintEverything();
5054 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005055 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005056 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005057 reply->writeInt32(0);
5058 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005059 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005060 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 return NO_ERROR;
5062 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005063 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005064 if (!display) {
5065 return NAME_NOT_FOUND;
5066 }
5067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005068 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005069 return NO_ERROR;
5070 }
5071 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005073 // daltonize
5074 n = data.readInt32();
5075 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005076 case 1:
5077 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5078 break;
5079 case 2:
5080 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5081 break;
5082 case 3:
5083 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5084 break;
5085 default:
5086 mDaltonizer.setType(ColorBlindnessType::None);
5087 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005088 }
5089 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005090 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005091 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005092 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005093 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005094
5095 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 // apply a color matrix
5101 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005103 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005104 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005105 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005106 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005107 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005108 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005109 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005112
5113 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5114 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005115 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005116 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5117 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5118 }
5119
Chia-I Wu28f320b2018-05-03 11:02:56 -07005120 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005121 return NO_ERROR;
5122 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005123 // This is an experimental interface
5124 // Needs to be shifted to proper binder interface when we productize
5125 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005126 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005127 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005128 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005129 return NO_ERROR;
5130 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005131 case 1017: {
5132 n = data.readInt32();
5133 mForceFullDamage = static_cast<bool>(n);
5134 return NO_ERROR;
5135 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005136 case 1018: { // Modify Choreographer's phase offset
5137 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005138 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005139 return NO_ERROR;
5140 }
5141 case 1019: { // Modify SurfaceFlinger's phase offset
5142 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005143 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005144 return NO_ERROR;
5145 }
Irvel468051e2016-06-13 16:44:44 -07005146 case 1020: { // Layer updates interceptor
5147 n = data.readInt32();
5148 if (n) {
5149 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005150 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005151 }
5152 else{
5153 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005154 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005155 }
5156 return NO_ERROR;
5157 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005158 case 1021: { // Disable HWC virtual displays
5159 n = data.readInt32();
5160 mUseHwcVirtualDisplays = !n;
5161 return NO_ERROR;
5162 }
Romain Guy0147a172017-06-01 13:53:56 -07005163 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005165 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005166
Chia-I Wu28f320b2018-05-03 11:02:56 -07005167 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005168 return NO_ERROR;
5169 }
Romain Guy54f154a2017-10-24 21:40:32 +01005170 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005171 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005172 invalidateHwcGeometry();
5173 repaintEverything();
5174 return NO_ERROR;
5175 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005176 // Deprecate, use 1030 to check whether the device is color managed.
5177 case 1024: {
5178 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005179 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005180 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005181 n = data.readInt32();
5182 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005183 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005184 mTracing.enable();
5185 doTracing("tracing.enable");
5186 reply->writeInt32(NO_ERROR);
5187 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005188 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005189 status_t err = mTracing.disable();
5190 reply->writeInt32(err);
5191 }
5192 return NO_ERROR;
5193 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005194 case 1026: { // Get layer tracing status
5195 reply->writeBool(mTracing.isEnabled());
5196 return NO_ERROR;
5197 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005198 // Is a DisplayColorSetting supported?
5199 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005200 const auto display = getDefaultDisplayDevice();
5201 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005202 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005204
5205 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5206 switch (setting) {
5207 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005208 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005209 break;
5210 case DisplayColorSetting::UNMANAGED:
5211 reply->writeBool(true);
5212 break;
5213 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005214 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005215 break;
5216 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005217 reply->writeBool(
5218 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005219 break;
5220 }
5221 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005222 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005223 // Is VrFlinger active?
5224 case 1028: {
5225 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005226 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005227 return NO_ERROR;
5228 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005229 // Is device color managed?
5230 case 1030: {
5231 reply->writeBool(useColorManagement);
5232 return NO_ERROR;
5233 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005234 // Override default composition data space
5235 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5236 // && adb shell stop zygote && adb shell start zygote
5237 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5238 // adb shell stop zygote && adb shell start zygote
5239 case 1031: {
5240 Mutex::Autolock _l(mStateLock);
5241 n = data.readInt32();
5242 if (n) {
5243 n = data.readInt32();
5244 if (n) {
5245 Dataspace dataspace = static_cast<Dataspace>(n);
5246 if (!validateCompositionDataspace(dataspace)) {
5247 return BAD_VALUE;
5248 }
5249 mDefaultCompositionDataspace = dataspace;
5250 }
5251 n = data.readInt32();
5252 if (n) {
5253 Dataspace dataspace = static_cast<Dataspace>(n);
5254 if (!validateCompositionDataspace(dataspace)) {
5255 return BAD_VALUE;
5256 }
5257 mWideColorGamutCompositionDataspace = dataspace;
5258 }
5259 } else {
5260 // restore composition data space.
5261 mDefaultCompositionDataspace = defaultCompositionDataspace;
5262 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5263 }
5264 return NO_ERROR;
5265 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005266 }
5267 }
5268 return err;
5269}
5270
Steven Thomas6d8110b2017-08-31 18:24:21 -07005271void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005272 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005273 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005274}
5275
Ana Krulec7d1d6832018-12-27 11:10:09 -08005276void SurfaceFlinger::repaintEverythingForHWC() {
5277 mRepaintEverything = true;
5278 mEventQueue->invalidateForHWC();
5279}
5280
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5282class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005283public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005284 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5285 ~WindowDisconnector() {
5286 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005287 }
5288
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289private:
5290 ANativeWindow* mWindow;
5291 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005292};
5293
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005294status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005295 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5296 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005297 uint32_t reqWidth, uint32_t reqHeight,
5298 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005299 ISurfaceComposer::Rotation rotation,
5300 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005301 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005302
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005303 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005304
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005305 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5306
Chia-I Wu20261cb2018-08-23 12:55:44 -07005307 sp<DisplayDevice> display;
5308 {
5309 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005310
Chia-I Wu20261cb2018-08-23 12:55:44 -07005311 display = getDisplayDeviceLocked(displayToken);
5312 if (!display) return BAD_VALUE;
5313
Chia-I Wucb023152018-08-28 12:57:23 -07005314 // set the requested width/height to the logical display viewport size
5315 // by default
5316 if (reqWidth == 0 || reqHeight == 0) {
5317 reqWidth = uint32_t(display->getViewport().width());
5318 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005319 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005320 }
5321
Peiyong Lin0e003c92018-09-17 11:09:51 -07005322 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005323 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005324
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005325 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5326 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005327 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5328 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005329}
5330
5331status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005332 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5333 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005334 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005335 ATRACE_CALL();
5336
5337 class LayerRenderArea : public RenderArea {
5338 public:
Robert Carr578038f2018-03-09 12:25:24 -08005339 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005340 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5341 bool childrenOnly)
5342 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005343 mLayer(layer),
5344 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005345 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005346 mFlinger(flinger),
5347 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005348 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005349 Rect getBounds() const override {
5350 const Layer::State& layerState(mLayer->getDrawingState());
5351 return mLayer->getBufferSize(layerState);
5352 }
Marissa Wall61c58622018-07-18 10:12:20 -07005353 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005354 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005355 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005356 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005357 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005358 }
chaviwa76b2712017-09-20 12:02:26 -07005359 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005360 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005361 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005362 Rect getSourceCrop() const override {
5363 if (mCrop.isEmpty()) {
5364 return getBounds();
5365 } else {
5366 return mCrop;
5367 }
5368 }
Robert Carr578038f2018-03-09 12:25:24 -08005369 class ReparentForDrawing {
5370 public:
5371 const sp<Layer>& oldParent;
5372 const sp<Layer>& newParent;
5373
Vishnu Nair4351ad52019-02-11 14:13:02 -08005374 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5375 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005376 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005377 // Compute and cache the bounds for the new parent layer.
5378 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005379 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005380 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005381 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005382 };
5383
5384 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005385 const Rect sourceCrop = getSourceCrop();
5386 // no need to check rotation because there is none
5387 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5388 sourceCrop.height() != getReqHeight();
5389
Robert Carr578038f2018-03-09 12:25:24 -08005390 if (!mChildrenOnly) {
5391 mTransform = mLayer->getTransform().inverse();
5392 drawLayers();
5393 } else {
5394 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005395 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005396 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5397 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005398
Vishnu Nair4351ad52019-02-11 14:13:02 -08005399 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005400 drawLayers();
5401 }
5402 }
chaviwa76b2712017-09-20 12:02:26 -07005403
chaviwa76b2712017-09-20 12:02:26 -07005404 private:
chaviw7206d492017-11-10 16:16:12 -08005405 const sp<Layer> mLayer;
5406 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005407
5408 // In the "childrenOnly" case we reparent the children to a screenshot
5409 // layer which has no properties set and which does not draw.
5410 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005411 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005412 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005413
5414 SurfaceFlinger* mFlinger;
5415 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005416 };
5417
5418 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5419 auto parent = layerHandle->owner.promote();
5420
Robert Carr2e102c92018-10-23 12:11:15 -07005421 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005422 ALOGE("captureLayers called with a removed parent");
5423 return NAME_NOT_FOUND;
5424 }
5425
Robert Carr578038f2018-03-09 12:25:24 -08005426 const int uid = IPCThreadState::self()->getCallingUid();
5427 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005429 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5430 return PERMISSION_DENIED;
5431 }
5432
chaviw7206d492017-11-10 16:16:12 -08005433 Rect crop(sourceCrop);
5434 if (sourceCrop.width() <= 0) {
5435 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005437 }
5438
5439 if (sourceCrop.height() <= 0) {
5440 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005441 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005442 }
5443
5444 int32_t reqWidth = crop.width() * frameScale;
5445 int32_t reqHeight = crop.height() * frameScale;
5446
Chia-I Wu20261cb2018-08-23 12:55:44 -07005447 // really small crop or frameScale
5448 if (reqWidth <= 0) {
5449 reqWidth = 1;
5450 }
5451 if (reqHeight <= 0) {
5452 reqHeight = 1;
5453 }
5454
Peiyong Lin0e003c92018-09-17 11:09:51 -07005455 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005456
Robert Carr578038f2018-03-09 12:25:24 -08005457 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005458 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5459 if (!layer->isVisible()) {
5460 return;
Robert Carr578038f2018-03-09 12:25:24 -08005461 } else if (childrenOnly && layer == parent.get()) {
5462 return;
chaviwa76b2712017-09-20 12:02:26 -07005463 }
5464 visitor(layer);
5465 });
5466 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005467 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005468}
5469
5470status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5471 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005472 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005473 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005474 bool useIdentityTransform) {
5475 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005476
Peiyong Lin0e003c92018-09-17 11:09:51 -07005477 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005478 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5479 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005480 *outBuffer =
5481 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5482 static_cast<android_pixel_format>(reqPixelFormat), 1,
5483 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484
Dan Stozaec460082018-12-17 15:35:09 -08005485 return captureScreenCore(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
5486}
5487
5488status_t SurfaceFlinger::captureScreenCore(RenderArea& renderArea,
5489 TraverseLayersFunction traverseLayers,
5490 const sp<GraphicBuffer>& buffer,
5491 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005492 // This mutex protects syncFd and captureResult for communication of the return values from the
5493 // main thread back to this Binder thread
5494 std::mutex captureMutex;
5495 std::condition_variable captureCondition;
5496 std::unique_lock<std::mutex> captureLock(captureMutex);
5497 int syncFd = -1;
5498 std::optional<status_t> captureResult;
5499
Robert Carr03480e22018-01-04 16:02:06 -08005500 const int uid = IPCThreadState::self()->getCallingUid();
5501 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5502
Dominik Laskowski8c001672018-05-30 16:52:06 -07005503 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 // If there is a refresh pending, bug out early and tell the binder thread to try again
5505 // after the refresh.
5506 if (mRefreshPending) {
5507 ATRACE_NAME("Skipping screenshot for now");
5508 std::unique_lock<std::mutex> captureLock(captureMutex);
5509 captureResult = std::make_optional<status_t>(EAGAIN);
5510 captureCondition.notify_one();
5511 return;
5512 }
5513
5514 status_t result = NO_ERROR;
5515 int fd = -1;
5516 {
5517 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005518 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005519 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005520 useIdentityTransform, forSystem, &fd);
5521 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005522 }
5523
5524 {
5525 std::unique_lock<std::mutex> captureLock(captureMutex);
5526 syncFd = fd;
5527 captureResult = std::make_optional<status_t>(result);
5528 captureCondition.notify_one();
5529 }
5530 });
5531
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005532 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005533 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005534 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535 while (*captureResult == EAGAIN) {
5536 captureResult.reset();
5537 result = postMessageAsync(message);
5538 if (result != NO_ERROR) {
5539 return result;
5540 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005541 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005542 }
5543 result = *captureResult;
5544 }
5545
5546 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005547 sync_wait(syncFd, -1);
5548 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005549 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005550
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005551 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005552}
5553
chaviwa76b2712017-09-20 12:02:26 -07005554void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005555 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005556 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5557 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005558 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005559
chaviwa76b2712017-09-20 12:02:26 -07005560 const auto reqWidth = renderArea.getReqWidth();
5561 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005562 const auto sourceCrop = renderArea.getSourceCrop();
5563 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005564
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005565 renderengine::DisplaySettings clientCompositionDisplay;
5566 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005567
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005568 // assume that bounds are never offset, and that they are the same as the
5569 // buffer bounds.
5570 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5571 ui::Transform transform = renderArea.getTransform();
5572 mat4 m;
5573 m[0][0] = transform[0][0];
5574 m[0][1] = transform[0][1];
5575 m[0][3] = transform[0][2];
5576 m[1][0] = transform[1][0];
5577 m[1][1] = transform[1][1];
5578 m[1][3] = transform[1][2];
5579 m[3][0] = transform[2][0];
5580 m[3][1] = transform[2][1];
5581 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005582
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005583 clientCompositionDisplay.globalTransform = m;
5584 mat4 rotMatrix;
5585 // Displacement for repositioning the clipping rectangle after rotating it
5586 // with the rotation hint.
5587 int displacementX = 0;
5588 int displacementY = 0;
5589 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5590 switch (rotation) {
5591 case ui::Transform::ROT_90:
5592 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5593 displacementX = reqWidth;
5594 break;
5595 case ui::Transform::ROT_180:
5596 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5597 displacementX = reqWidth;
5598 displacementY = reqHeight;
5599 break;
5600 case ui::Transform::ROT_270:
5601 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5602 displacementY = reqHeight;
5603 break;
5604 default:
5605 break;
5606 }
5607 // We need to transform the clipping window into the right spot.
5608 // First, rotate the clipping rectangle by the rotation hint to get the
5609 // right orientation
5610 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5611 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5612 const vec4 rotClipTL = rotMatrix * clipTL;
5613 const vec4 rotClipBR = rotMatrix * clipBR;
5614 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5615 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5616 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5617 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5618
5619 // Now reposition the clipping rectangle with the displacement vector
5620 // computed above.
5621 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5622
5623 clientCompositionDisplay.clip =
5624 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5625 newClipRight + displacementX, newClipBottom + displacementY);
5626
5627 // We need to perform the same transformation in layer space, so propagate
5628 // it to the global transform.
5629 mat4 clipTransform = displacementMat * rotMatrix;
5630 clientCompositionDisplay.globalTransform *= clipTransform;
5631 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5632 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005633
chaviw50da5042018-04-09 13:49:37 -07005634 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005635
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005636 renderengine::LayerSettings fillLayer;
5637 fillLayer.source.buffer.buffer = nullptr;
5638 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5639 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5640 fillLayer.alpha = half(alpha);
5641 clientCompositionLayers.push_back(fillLayer);
5642
5643 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005644 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005645 renderengine::LayerSettings layerSettings;
5646 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5647 layerSettings);
5648 if (prepared) {
5649 clientCompositionLayers.push_back(layerSettings);
5650 }
chaviwa76b2712017-09-20 12:02:26 -07005651 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005652
5653 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005654 // Use an empty fence for the buffer fence, since we just created the buffer so
5655 // there is no need for synchronization with the GPU.
5656 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 base::unique_fd drawFence;
5658 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005659 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005660
5661 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005662}
5663
chaviwa76b2712017-09-20 12:02:26 -07005664status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5665 TraverseLayersFunction traverseLayers,
5666 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005667 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005668 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005669 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005670 ATRACE_CALL();
5671
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005672 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005673
5674 traverseLayers([&](Layer* layer) {
5675 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5676 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005677
Robert Carr03480e22018-01-04 16:02:06 -08005678 // We allow the system server to take screenshots of secure layers for
5679 // use in situations like the Screen-rotation animation and place
5680 // the impetus on WindowManager to not persist them.
5681 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005682 ALOGW("FB is protected: PERMISSION_DENIED");
5683 return PERMISSION_DENIED;
5684 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005685 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005686 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005687}
5688
chaviw95ef3c42019-02-14 10:55:09 -08005689void SurfaceFlinger::setInputWindowsFinished() {
5690 Mutex::Autolock _l(mStateLock);
5691
5692 mPendingSyncInputWindows = false;
5693 mTransactionCV.broadcast();
5694}
chaviw5f21a5e2019-02-14 10:00:34 -08005695
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005696// ---------------------------------------------------------------------------
5697
Dan Stoza412903f2017-04-27 13:42:17 -07005698void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5699 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005700}
5701
Dan Stoza412903f2017-04-27 13:42:17 -07005702void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5703 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005704}
5705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005706void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005707 const LayerVector::Visitor& visitor) {
5708 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005709 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005710 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005711 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005712 continue;
5713 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005714 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005715 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005716 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005717 return;
5718 }
chaviwa76b2712017-09-20 12:02:26 -07005719 if (!layer->isVisible()) {
5720 return;
5721 }
5722 visitor(layer);
5723 });
5724 }
5725}
5726
Ady Abraham838de062019-02-04 10:24:03 -08005727void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5728 const android::sp<android::IBinder>& displayToken,
5729 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5730 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5731 if (!displayId) {
5732 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5733 return;
5734 }
5735
5736 ALOGV("Updating allowed configs");
5737 {
5738 std::lock_guard lock(mAllowedConfigsLock);
5739 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5740 }
5741
5742 // make sure that the current config is still allowed
5743 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5744 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
5745 // TODO(b/122906558): stop querying HWC for the available configs and instead use the cached
5746 // configs queried on boot
5747 auto configs = getHwComposer().getConfigs(*displayId);
5748
5749 for (int i = 0; i < configs.size(); i++) {
5750 if (isConfigAllowed(*displayId, i)) {
5751 // TODO: we switch to the first allowed config. In the future
5752 // we may want to enhance this logic to pick a similar config
5753 // to the current one
5754 ALOGV("Old config is not allowed - switching to config %d", i);
Ady Abraham447052e2019-02-13 16:07:27 -08005755 setDesiredActiveConfig(displayToken, i, ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005756 break;
5757 }
5758 }
5759 }
5760}
5761
5762status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5763 const std::vector<int32_t>& allowedConfigs) {
5764 ATRACE_CALL();
5765
5766 if (!displayToken) {
5767 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5768 return BAD_VALUE;
5769 }
5770
5771 if (!allowedConfigs.size()) {
5772 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5773 return BAD_VALUE;
5774 }
5775
5776 {
5777 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5778 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5779 if (!displayId) {
5780 ALOGE("setAllowedDisplayConfigs: display not found");
5781 return NAME_NOT_FOUND;
5782 }
5783 }
5784
5785 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5786 for (int config : allowedConfigs) {
5787 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5788 allowedDisplayConfigsBuilder.addConfig(config);
5789 }
5790 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5791 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5792 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5793 }));
5794 return NO_ERROR;
5795}
5796
chaviw291d88a2019-02-14 10:33:58 -08005797// ----------------------------------------------------------------------------
5798
5799void SetInputWindowsListener::onSetInputWindowsFinished() {
5800 mFlinger->setInputWindowsFinished();
5801}
5802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005803}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005804
Lloyd Pique074e8122018-07-26 12:57:23 -07005805
Mathias Agopian3f844832013-08-07 21:24:32 -07005806#if defined(__gl_h_)
5807#error "don't include gl/gl.h in this file"
5808#endif
5809
5810#if defined(__gl2_h_)
5811#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005812#endif