blob: 1466785ae0f1b9b5b6211c7b4ac36aeeeac8c9e1 [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()),
287 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800288
Lloyd Pique90c115d2018-09-18 21:39:42 -0700289SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
290 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800291 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800300
Steven Thomas050b2c82017-03-06 11:45:16 -0800301 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 mDefaultCompositionDataspace =
311 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
312 mWideColorGamutCompositionDataspace =
313 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
314 defaultCompositionDataspace = mDefaultCompositionDataspace;
315 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
316 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
317 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
318 wideColorGamutCompositionPixelFormat =
319 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
324 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
325 switch (tmpPrimaryDisplayOrientation) {
326 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Sundong Ahn85131bd2019-02-18 15:51:53 +0900341 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 property_get("debug.sf.showupdates", value, "0");
350 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700352 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000353
354 // DDMS debugging deprecated (b/120782499)
355 property_get("debug.sf.ddms", value, "0");
356 int debugDdms = atoi(value);
357 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800367 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Ana Krulecc2870422019-01-29 19:00:58 -0800375 property_get("debug.sf.use_90Hz", value, "0");
376 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800377
Ana Krulecba13ab32019-02-20 14:14:12 -0800378 property_get("debug.sf.use_smart_90_for_video", value, "0");
379 mUseSmart90ForVideo = atoi(value);
380
Ana Krulec757f63a2019-01-25 10:46:18 -0800381 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
382 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700383
Romain Guy11d63f42017-07-20 12:47:14 -0700384 // We should be reading 'persist.sys.sf.color_saturation' here
385 // but since /data may be encrypted, we need to wait until after vold
386 // comes online to attempt to read the property. The property is
387 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800388
389 if (useTrebleTestingOverride()) {
390 // Without the override SurfaceFlinger cannot connect to HIDL
391 // services that are not listed in the manifests. Considered
392 // deriving the setting from the set service name, but it
393 // would be brittle if the name that's not 'default' is used
394 // for production purposes later on.
395 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
396 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399void SurfaceFlinger::onFirstRef()
400{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800401 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402}
403
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404SurfaceFlinger::~SurfaceFlinger()
405{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406}
407
Dan Stozac7014012014-02-14 15:03:43 -0800408void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409{
410 // the window manager died on us. prepare its eulogy.
411
Andy McFadden13a082e2012-08-24 10:16:42 -0700412 // restore initial conditions (default device unblank, etc)
413 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414
415 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700416 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
Robert Carr1db73f62016-12-21 12:58:51 -0800419static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700420 status_t err = client->initCheck();
421 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800422 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423 }
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return nullptr;
425}
426
427sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
428 return initClient(new Client(this));
429}
430
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700431sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
432 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433{
434 class DisplayToken : public BBinder {
435 sp<SurfaceFlinger> flinger;
436 virtual ~DisplayToken() {
437 // no more references, this display must be terminated
438 Mutex::Autolock _l(flinger->mStateLock);
439 flinger->mCurrentState.displays.removeItem(this);
440 flinger->setTransactionFlags(eDisplayTransactionNeeded);
441 }
442 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700443 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444 : flinger(flinger) {
445 }
446 };
447
448 sp<BBinder> token = new DisplayToken(this);
449
450 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 // Display ID is assigned when virtual display is allocated by HWC.
452 DisplayDeviceState state;
453 state.isSecure = secure;
454 state.displayName = displayName;
455 mCurrentState.displays.add(token, state);
456 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 return token;
458}
459
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700460void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 Mutex::Autolock _l(mStateLock);
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
464 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700465 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 return;
467 }
468
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
470 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700471 ALOGE("destroyDisplay called for non-virtual display");
472 return;
473 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 mInterceptor->saveDisplayDeletion(state.sequenceId);
475 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700476 setTransactionFlags(eDisplayTransactionNeeded);
477}
478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
480 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482 const auto internalDisplayId = getInternalDisplayIdLocked();
483 if (!internalDisplayId) {
484 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 }
486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487 std::vector<PhysicalDisplayId> displayIds;
488 displayIds.reserve(mPhysicalDisplayTokens.size());
489 displayIds.push_back(internalDisplayId->value);
490
491 for (const auto& [id, token] : mPhysicalDisplayTokens) {
492 if (id != *internalDisplayId) {
493 displayIds.push_back(id.value);
494 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497 return displayIds;
498}
499
500sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
501 Mutex::Autolock lock(mStateLock);
502 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503}
504
Ady Abraham37965d42018-11-01 13:43:32 -0700505status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
506 if (!outGetColorManagement) {
507 return BAD_VALUE;
508 }
509 *outGetColorManagement = useColorManagement;
510 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700511}
512
Lloyd Pique441d5042018-10-18 16:49:51 -0700513HWComposer& SurfaceFlinger::getHwComposer() const {
514 return mCompositionEngine->getHwComposer();
515}
516
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700517renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
518 return mCompositionEngine->getRenderEngine();
519}
520
Lloyd Pique70d91362018-10-18 16:02:55 -0700521compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
522 return *mCompositionEngine.get();
523}
524
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525void SurfaceFlinger::bootFinished()
526{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700527 if (mStartPropertySetThread->join() != NO_ERROR) {
528 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 const nsecs_t now = systemTime();
531 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000532 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
534 // wait patiently for the window manager death
535 const String16 name("window");
536 sp<IBinder> window(defaultServiceManager()->getService(name));
537 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700538 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700539 }
Robert Carr720e5062018-07-30 17:45:14 -0700540 sp<IBinder> input(defaultServiceManager()->getService(
541 String16("inputflinger")));
542 if (input == nullptr) {
543 ALOGE("Failed to link to input service");
544 } else {
545 mInputFlinger = interface_cast<IInputFlinger>(input);
546 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547
Steven Thomas050b2c82017-03-06 11:45:16 -0800548 if (mVrFlinger) {
549 mVrFlinger->OnBootFinished();
550 }
551
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700553 // formerly we would just kill the process, but we now ask it to exit so it
554 // can choose where to stop the animation.
555 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700556
557 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
558 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
559 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700560
Ana Krulecbd6654b2019-02-15 15:18:15 -0800561 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800562 readPersistentProperties();
563 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800564
565 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
566 // away and it should be controlled by flipping the switch in setting. The switch in
567 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
568 // The boot must be complete before we can set the active config.
569
570 if (mUse90Hz) {
571 mPhaseOffsets->setRefreshRateType(
572 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
573 setRefreshRateTo(RefreshRateType::PERFORMANCE);
574 } else {
575 mPhaseOffsets->setRefreshRateType(
576 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
577 setRefreshRateTo(RefreshRateType::DEFAULT);
578 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800580}
581
Dan Stoza436ccf32018-06-21 12:10:12 -0700582uint32_t SurfaceFlinger::getNewTexture() {
583 {
584 std::lock_guard lock(mTexturePoolMutex);
585 if (!mTexturePool.empty()) {
586 uint32_t name = mTexturePool.back();
587 mTexturePool.pop_back();
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
589 return name;
590 }
591
592 // The pool was too small, so increase it for the future
593 ++mTexturePoolSize;
594 }
595
596 // The pool was empty, so we need to get a new texture name directly using a
597 // blocking call to the main thread
598 uint32_t name = 0;
599 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
600 return name;
601}
602
Mathias Agopian3f844832013-08-07 21:24:32 -0700603void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700604 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700605}
606
Wei Wangf9b05ee2017-07-19 20:59:39 -0700607// Do not call property_set on main thread which will be blocked by init
608// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700609void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700610 ALOGI( "SurfaceFlinger's main thread ready to run. "
611 "Initializing graphics H/W...");
612
Ana Krulec757f63a2019-01-25 10:46:18 -0800613 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800617 mScheduler =
618 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
619 auto resyncCallback =
620 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800621
Ana Krulecc2870422019-01-29 19:00:58 -0800622 mAppConnectionHandle =
623 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
624 resyncCallback,
625 impl::EventThread::InterceptVSyncsCallback());
626 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
627 resyncCallback, [this](nsecs_t timestamp) {
628 mInterceptor->saveVSyncEvent(timestamp);
629 });
630
631 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
632 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
633 mSfConnectionHandle.get());
634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700636 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700637 renderEngineFeature |= (useColorManagement ?
638 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700639 renderEngineFeature |= (useContextPriority ?
640 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700641
642 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700643 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700644 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700645 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700646
647 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
648 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700649 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
650 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800651 // Process any initial hotplug and resulting display changes.
652 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700653 const auto display = getDefaultDisplayDeviceLocked();
654 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700655 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800657
Steven Thomas050b2c82017-03-06 11:45:16 -0800658 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700659 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700660 // This callback is called from the vr flinger dispatch thread. We
661 // need to call signalTransaction(), which requires holding
662 // mStateLock when we're not on the main thread. Acquiring
663 // mStateLock from the vr flinger dispatch thread might trigger a
664 // deadlock in surface flinger (see b/66916578), so post a message
665 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700667 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
668 mVrFlingerRequestsDisplay = requestDisplay;
669 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
673 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700674 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 .value_or(0),
676 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (!mVrFlinger) {
678 ALOGE("Failed to start vrflinger");
679 }
680 }
681
Mathias Agopian92a979a2012-08-02 18:32:23 -0700682 // initialize our drawing state
683 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700684
Andy McFadden13a082e2012-08-24 10:16:42 -0700685 // set initial conditions (e.g. unblank default device)
686 initializeDisplays();
687
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700688 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700689
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700691
692 const bool presentFenceReliable =
693 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
694 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695
696 if (mStartPropertySetThread->Start() != NO_ERROR) {
697 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699
Kevin DuBois36233132019-02-19 14:08:55 -0800700 if (mUse90Hz) {
701 mScheduler->setExpiredIdleTimerCallback([this] {
702 Mutex::Autolock lock(mStateLock);
703 setRefreshRateTo(RefreshRateType::DEFAULT);
704 });
705 mScheduler->setResetIdleTimerCallback([this] {
706 Mutex::Autolock lock(mStateLock);
707 setRefreshRateTo(RefreshRateType::PERFORMANCE);
708 });
709 }
Ana Krulecc2870422019-01-29 19:00:58 -0800710 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
711 *display->getId()),
712 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700715}
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 Mutex::Autolock _l(mStateLock);
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720 char value[PROPERTY_VALUE_MAX];
721
722 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100726
727 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700728 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800729
730 property_get("persist.sys.sf.color_mode", value, "0");
731 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700732}
733
Mathias Agopiana67e4182012-06-19 17:26:12 -0700734void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800735 // Start boot animation service by setting a property mailbox
736 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700737 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800738 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 if (mStartPropertySetThread->join() != NO_ERROR) {
740 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700742}
743
Mathias Agopian875d8e12013-06-07 15:35:48 -0700744size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700745 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700749 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800753
Jamie Gennis582270d2011-08-17 18:19:00 -0700754bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800755 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800756 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800757 return authenticateSurfaceTextureLocked(bufferProducer);
758}
759
760bool SurfaceFlinger::authenticateSurfaceTextureLocked(
761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800762 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800763 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800764}
765
Brian Anderson6b376712017-04-04 10:51:39 -0700766status_t SurfaceFlinger::getSupportedFrameTimestamps(
767 std::vector<FrameEvent>* outSupported) const {
768 *outSupported = {
769 FrameEvent::REQUESTED_PRESENT,
770 FrameEvent::ACQUIRE,
771 FrameEvent::LATCH,
772 FrameEvent::FIRST_REFRESH_START,
773 FrameEvent::LAST_REFRESH_START,
774 FrameEvent::GPU_COMPOSITION_DONE,
775 FrameEvent::DEQUEUE_READY,
776 FrameEvent::RELEASE,
777 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700778 ConditionalLock _l(mStateLock,
779 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700780 if (!getHwComposer().hasCapability(
781 HWC2::Capability::PresentFenceIsNotReliable)) {
782 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
783 }
784 return NO_ERROR;
785}
786
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800787status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
788 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700789 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700790 return BAD_VALUE;
791 }
792
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800793 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700794 if (!displayId) {
795 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700796 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700797
Mathias Agopian8b736f12012-08-13 17:54:26 -0700798 // TODO: Not sure if display density should handled by SF any longer
799 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700800 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700801 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700802 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800803 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700804 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700805 }
806 return density;
807 }
808 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700811 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 return getDensityFromProperty("ro.sf.lcd_density"); }
813 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700814
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700816
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 DisplayInfo info = DisplayInfo();
819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 float xdpi = hwConfig->getDpiX();
821 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700823 info.w = hwConfig->getWidth();
824 info.h = hwConfig->getHeight();
825 // Default display viewport to display width and height
826 info.viewportW = info.w;
827 info.viewportH = info.h;
828
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800829 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 // The density of the device is provided by a build property
831 float density = Density::getBuildDensity() / 160.0f;
832 if (density == 0) {
833 // the build doesn't provide a density -- this is wrong!
834 // use xdpi instead
835 ALOGE("ro.sf.lcd_density must be defined as a build property");
836 density = xdpi / 160.0f;
837 }
838 if (Density::getEmuDensity()) {
839 // if "qemu.sf.lcd_density" is specified, it overrides everything
840 xdpi = ydpi = density = Density::getEmuDensity();
841 density /= 160.0f;
842 }
843 info.density = density;
844
845 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 const auto display = getDefaultDisplayDeviceLocked();
847 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700848
849 // This is for screenrecord
850 const Rect viewport = display->getViewport();
851 if (viewport.isValid()) {
852 info.viewportW = uint32_t(viewport.getWidth());
853 info.viewportH = uint32_t(viewport.getHeight());
854 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 } else {
856 // TODO: where should this value come from?
857 static const int TV_DENSITY = 213;
858 info.density = TV_DENSITY / 160.0f;
859 info.orientation = 0;
860 }
861
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 info.xdpi = xdpi;
863 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800865 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866
Andy McFadden91b2ca82014-06-13 14:04:23 -0700867 // This is how far in advance a buffer must be queued for
868 // presentation at a given time. If you want a buffer to appear
869 // on the screen at time N, you must submit the buffer before
870 // (N - presentationDeadline).
871 //
872 // Normally it's one full refresh period (to give SF a chance to
873 // latch the buffer), but this can be reduced by configuring a
874 // DispSync offset. Any additional delays introduced by the hardware
875 // composer or panel must be accounted for here.
876 //
877 // We add an additional 1ms to allow for processing time and
878 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800879 info.presentationDeadline =
880 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881
882 // All non-virtual displays are currently considered secure.
883 info.secure = true;
884
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800885 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700886 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800887 std::swap(info.w, info.h);
888 }
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return NO_ERROR;
894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
897 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 return BAD_VALUE;
899 }
900
Ana Krulecc2870422019-01-29 19:00:58 -0800901 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 return NO_ERROR;
903}
904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
906 const auto display = getDisplayDevice(displayToken);
907 if (!display) {
908 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800909 return BAD_VALUE;
910 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800915void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
916 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800917
Ana Krulec7d1d6832018-12-27 11:10:09 -0800918 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800919 // Lock is acquired by setRefreshRateTo.
920 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800921 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
922 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
923 return;
924 }
925
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 // Lock is acquired by setRefreshRateTo.
927 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928 if (!display) {
929 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
930 displayToken.get());
931 return;
932 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700933 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800934 ALOGW("Attempt to set active config %d for virtual display", mode);
935 return;
936 }
937 int currentDisplayPowerMode = display->getPowerMode();
938 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
939 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 return;
941 }
942
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 // Don't check against the current mode yet. Worst case we set the desired
944 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 std::lock_guard<std::mutex> lock(mActiveConfigLock);
946 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
947
948 if (!mDesiredActiveConfigChanged) {
949 // This is the first time we set the desired
950 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
951
952 // This will trigger HWC refresh without resetting the idle timer.
953 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800955 mDesiredActiveConfigChanged = true;
956 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800957}
958
959status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
960 ATRACE_CALL();
961 postMessageSync(new LambdaMessage(
962 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
963 return NO_ERROR;
964}
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966void SurfaceFlinger::setActiveConfigInternal() {
967 ATRACE_CALL();
968
969 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800970 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971
972 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
973 display->setActiveConfig(mUpcomingActiveConfig.configId);
974
Ana Krulecc2870422019-01-29 19:00:58 -0800975 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
977}
978
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
980 // we may be in the process of changing the active state
981 if (mWaitForNextInvalidate) {
982 mWaitForNextInvalidate = false;
983
984 repaintEverythingForHWC();
985 // We do not want to give another frame to HWC while we are transitioning.
986 return true;
987 }
988
989 if (mCheckPendingFence) {
990 if (mPreviousPresentFence != Fence::NO_FENCE &&
991 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
992 // fence has not signaled yet. wait for the next invalidate
993 repaintEverythingForHWC();
994 return true;
995 }
996
997 // We received the present fence from the HWC, so we assume it successfully updated
998 // the config, hence we update SF.
999 mCheckPendingFence = false;
1000 setActiveConfigInternal();
1001 }
1002
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003 // Store the local variable to release the lock.
1004 ActiveConfigInfo desiredActiveConfig;
1005 {
1006 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (!mDesiredActiveConfigChanged) {
1008 return false;
1009 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010 desiredActiveConfig = mDesiredActiveConfig;
1011 }
1012
1013 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1015 // display is not valid or we are already in the requested mode
1016 // on both cases there is nothing left to do
1017 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1018 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1019 mDesiredActiveConfigChanged = false;
1020 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1021 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001023
1024 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1025 mUpcomingActiveConfig = desiredActiveConfig;
1026 const auto displayId = display->getId();
1027 LOG_ALWAYS_FATAL_IF(!displayId);
1028
1029 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1030 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1031
1032 // we need to submit an empty frame to HWC to start the process
1033 mWaitForNextInvalidate = true;
1034 mCheckPendingFence = true;
1035
1036 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001037}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1040 Vector<ColorMode>* outColorModes) {
1041 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001042 return BAD_VALUE;
1043 }
1044
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001046 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001047 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1048
1049 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1050 if (!displayId) {
1051 return NAME_NOT_FOUND;
1052 }
1053
Dominik Laskowski075d3172018-05-24 15:50:06 -07001054 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001055 }
Michael Wright28f24d02016-07-12 13:30:53 -07001056 outColorModes->clear();
1057 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1058
1059 return NO_ERROR;
1060}
1061
Daniel Solomon42d04562019-01-20 21:03:19 -08001062status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1063 ui::DisplayPrimaries &primaries) {
1064 if (!displayToken) {
1065 return BAD_VALUE;
1066 }
1067
1068 // Currently we only support this API for a single internal display.
1069 if (getInternalDisplayToken() != displayToken) {
1070 return BAD_VALUE;
1071 }
1072
1073 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1074 return NO_ERROR;
1075}
1076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1078 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001079 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001080 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001081 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001085 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 Vector<ColorMode> modes;
1087 getDisplayColorModes(displayToken, &modes);
1088 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1089 if (mode < ColorMode::NATIVE || !exists) {
1090 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1091 decodeColorMode(mode).c_str(), mode, displayToken.get());
1092 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDevice(displayToken);
1095 if (!display) {
1096 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1097 decodeColorMode(mode).c_str(), mode, displayToken.get());
1098 } else if (display->isVirtual()) {
1099 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1100 decodeColorMode(mode).c_str(), mode);
1101 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001102 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1103 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 }
1105 }));
1106
Michael Wright28f24d02016-07-12 13:30:53 -07001107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1123 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001124 Mutex::Autolock _l(mStateLock);
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDeviceLocked(displayToken);
1127 if (!display) {
1128 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001144status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1145 ui::PixelFormat* outFormat,
1146 ui::Dataspace* outDataspace,
1147 uint8_t* outComponentMask) const {
1148 if (!outFormat || !outDataspace || !outComponentMask) {
1149 return BAD_VALUE;
1150 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001151 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001152 if (!display || !display->getId()) {
1153 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1154 return BAD_VALUE;
1155 }
1156 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1157 outDataspace, outComponentMask);
1158}
1159
Kevin DuBois74e53772018-11-19 10:52:38 -08001160status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1161 bool enable, uint8_t componentMask,
1162 uint64_t maxFrames) const {
1163 const auto display = getDisplayDevice(displayToken);
1164 if (!display || !display->getId()) {
1165 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1166 return BAD_VALUE;
1167 }
1168
1169 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1170 componentMask, maxFrames);
1171}
1172
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001173status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1174 uint64_t maxFrames, uint64_t timestamp,
1175 DisplayedFrameStats* outStats) const {
1176 const auto display = getDisplayDevice(displayToken);
1177 if (!display || !display->getId()) {
1178 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1179 return BAD_VALUE;
1180 }
1181
1182 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1183 outStats);
1184}
1185
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001186status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1187 if (!outSupported) {
1188 return BAD_VALUE;
1189 }
1190 *outSupported = getRenderEngine().supportsProtectedContent();
1191 return NO_ERROR;
1192}
1193
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001194status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1195 bool* outIsWideColorDisplay) const {
1196 if (!displayToken || !outIsWideColorDisplay) {
1197 return BAD_VALUE;
1198 }
1199 Mutex::Autolock _l(mStateLock);
1200 const auto display = getDisplayDeviceLocked(displayToken);
1201 if (!display) {
1202 return BAD_VALUE;
1203 }
1204 *outIsWideColorDisplay = display->hasWideColorGamut();
1205 return NO_ERROR;
1206}
1207
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001209 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001210 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 if (mInjectVSyncs == enable) {
1213 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001214 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215
Ana Krulecc2870422019-01-29 19:00:58 -08001216 auto resyncCallback =
1217 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001218
Ana Krulec98b5b242018-08-10 15:03:23 -07001219 // TODO(akrulec): Part of the Injector should be refactored, so that it
1220 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 if (enable) {
1222 ALOGV("VSync Injections enabled");
1223 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001224 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001225 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001226 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001227 impl::EventThread::InterceptVSyncsCallback(),
1228 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001229 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001230 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 } else {
1232 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001233 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1234 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235 }
1236
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001237 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001238 }));
1239
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001240 return NO_ERROR;
1241}
1242
1243status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244 Mutex::Autolock _l(mStateLock);
1245
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001246 if (!mInjectVSyncs) {
1247 ALOGE("VSync Injections not enabled");
1248 return BAD_VALUE;
1249 }
1250 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1251 ALOGV("Injecting VSync inside SurfaceFlinger");
1252 mVSyncInjector->onInjectSyncEvent(when);
1253 }
1254 return NO_ERROR;
1255}
1256
Lloyd Pique755e3192018-01-31 16:46:15 -08001257status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1258 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001259 // Try to acquire a lock for 1s, fail gracefully
1260 const status_t err = mStateLock.timedLock(s2ns(1));
1261 const bool locked = (err == NO_ERROR);
1262 if (!locked) {
1263 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1264 return TIMED_OUT;
1265 }
1266
1267 outLayers->clear();
1268 mCurrentState.traverseInZOrder([&](Layer* layer) {
1269 outLayers->push_back(layer->getLayerDebugInfo());
1270 });
1271
1272 mStateLock.unlock();
1273 return NO_ERROR;
1274}
1275
Peiyong Linc6780972018-10-28 15:24:08 -07001276status_t SurfaceFlinger::getCompositionPreference(
1277 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1278 Dataspace* outWideColorGamutDataspace,
1279 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001280 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001281 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001282 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001283 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001284 return NO_ERROR;
1285}
1286
Dan Stoza84ab9372018-12-17 15:27:57 -08001287status_t SurfaceFlinger::addRegionSamplingListener(
1288 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1289 const sp<IRegionSamplingListener>& /*listener*/) {
1290 return NO_ERROR;
1291}
1292
1293status_t SurfaceFlinger::removeRegionSamplingListener(
1294 const sp<IRegionSamplingListener>& /*listener*/) {
1295 return NO_ERROR;
1296}
1297
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001298// ----------------------------------------------------------------------------
1299
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001300sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1301 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001302 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001303 Mutex::Autolock lock(mStateLock);
1304 return getVsyncPeriod();
1305 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001306
Ana Krulecc2870422019-01-29 19:00:58 -08001307 const auto& handle =
1308 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001309
Ana Krulecc2870422019-01-29 19:00:58 -08001310 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001311}
1312
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001313// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314
1315void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001316 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001317}
1318
1319void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001320 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321}
1322
1323void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001324 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001325}
1326
1327void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001328 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001329 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001330}
1331
1332status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001333 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001334 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335}
1336
1337status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001338 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001339 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340 if (res == NO_ERROR) {
1341 msg->wait();
1342 }
1343 return res;
1344}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001345
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001346void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001347 do {
1348 waitForEvent();
1349 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350}
1351
Dominik Laskowski83b88212018-12-11 13:34:06 -08001352nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001353 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001354 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1355 return 0;
1356 }
1357
1358 const auto config = getHwComposer().getActiveConfig(*displayId);
1359 return config ? config->getVsyncPeriod() : 0;
1360}
1361
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001362void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1363 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001364 ATRACE_NAME("SF onVsync");
1365
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001368 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 return;
1370 }
1371
Dominik Laskowski075d3172018-05-24 15:50:06 -07001372 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 return;
1374 }
1375
Dominik Laskowski075d3172018-05-24 15:50:06 -07001376 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 // For now, we don't do anything with external display vsyncs.
1378 return;
1379 }
1380
Ana Krulecc2870422019-01-29 19:00:58 -08001381 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001382}
1383
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001384void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001385 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1386 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001387}
1388
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001389void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1390 mPhaseOffsets->setRefreshRateType(refreshRate);
1391
1392 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1393 mVsyncModulator.setPhaseOffsets(early, gl, late);
1394
1395 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001396 return;
1397 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001398
Ana Krulec7d1d6832018-12-27 11:10:09 -08001399 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1400 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1401 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1402 // refresh cycle.
1403
1404 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001405 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001406 if (currentVsyncPeriod == 0) {
1407 return;
1408 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001409
Ana Krulec7d1d6832018-12-27 11:10:09 -08001410 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1411 // floating numbers.
1412 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001413 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1414 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001415 if (std::abs(currentFps - newFps) <= 1) {
1416 return;
1417 }
1418
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001419 const auto displayId = getInternalDisplayIdLocked();
1420 LOG_ALWAYS_FATAL_IF(!displayId);
1421
1422 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001423 for (int i = 0; i < configs.size(); i++) {
1424 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1425 if (vsyncPeriod == 0) {
1426 continue;
1427 }
1428 const float fps = 1e9 / vsyncPeriod;
1429 // TODO(b/113612090): There should be a better way at determining which config
1430 // has the right refresh rate.
1431 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001432 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001433 }
1434 }
1435}
1436
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001437void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001438 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001439 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001440 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
Lloyd Piqueba04e622017-12-14 17:11:26 -08001442 // Ignore events that do not have the right sequenceId.
1443 if (sequenceId != getBE().mComposerSequenceId) {
1444 return;
1445 }
1446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 // Only lock if we're not on the main thread. This function is normally
1448 // called on a hwbinder thread, but for the primary display it's called on
1449 // the main thread with the state lock already held, so don't attempt to
1450 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001451 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001452
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001453 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001454
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001455 if (std::this_thread::get_id() == mMainThreadId) {
1456 // Process all pending hot plug events immediately if we are on the main thread.
1457 processDisplayHotplugEventsLocked();
1458 }
1459
Lloyd Piqueba04e622017-12-14 17:11:26 -08001460 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001461}
1462
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001463void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001464 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001465 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001467 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001468 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001469}
1470
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001471void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001472 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001474 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001475 getHwComposer().setVsyncEnabled(*displayId,
1476 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1477 }
Mathias Agopian86303202012-07-24 22:46:10 -07001478}
1479
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001480// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001481void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001482 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001483 // Clear the drawing state so that the logic inside of
1484 // handleTransactionLocked will fire. It will determine the delta between
1485 // mCurrentState and mDrawingState and re-apply all changes when we make the
1486 // transition.
1487 mDrawingState.displays.clear();
1488 mDisplays.clear();
1489}
1490
Steven Thomas050b2c82017-03-06 11:45:16 -08001491void SurfaceFlinger::updateVrFlinger() {
1492 if (!mVrFlinger)
1493 return;
1494 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001495 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001496 return;
1497 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498
Lloyd Pique441d5042018-10-18 16:49:51 -07001499 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 ALOGE("Vr flinger is only supported for remote hardware composer"
1501 " service connections. Ignoring request to transition to vr"
1502 " flinger.");
1503 mVrFlingerRequestsDisplay = false;
1504 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001505 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001506
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001507 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001508
Steven Thomas0123ac62018-07-12 11:32:34 -07001509 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001510 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001511
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001512 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001513
1514 // Clear out all the output layers from the composition engine for all
1515 // displays before destroying the hardware composer interface. This ensures
1516 // any HWC layers are destroyed through that interface before it becomes
1517 // invalid.
1518 for (const auto& [token, displayDevice] : mDisplays) {
1519 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1520 compositionengine::Output::OutputLayers());
1521 }
1522
Steven Thomas0123ac62018-07-12 11:32:34 -07001523 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1524 // called below. Clear the reference now so we don't accidentally use it
1525 // later.
1526 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001533 // Delete the current instance before creating the new one
1534 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1535 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1536 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1537 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538
Lloyd Pique441d5042018-10-18 16:49:51 -07001539 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001540 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001541
1542 if (vrFlingerRequestsDisplay) {
1543 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545
1546 mVisibleRegionsDirty = true;
1547 invalidateHwcGeometry();
1548
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001550 display = getDefaultDisplayDeviceLocked();
1551 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001552 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001555 const nsecs_t vsyncPeriod = getVsyncPeriod();
1556 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001557
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001558 // The present fences returned from vr_hwc are not an accurate
1559 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001560 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001561
Steven Thomasb02664d2017-07-26 18:48:28 -07001562 // Use phase of 0 since phase is not known.
1563 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001564 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001565 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001566
Ana Krulecc2870422019-01-29 19:00:58 -08001567 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001569 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001571}
1572
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001574 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001575 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001577 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001578 break;
1579 }
1580
Ana Krulecba13ab32019-02-20 14:14:12 -08001581 if (mUse90Hz && mUseSmart90ForVideo) {
1582 // This call is made each time SF wakes up and creates a new frame. It is part
1583 // of video detection feature.
1584 mScheduler->incrementFrameCounter();
1585 }
Ana Krulecc2870422019-01-29 19:00:58 -08001586
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001587 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1588 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001589 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001590 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001591 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001592 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001593 if (mPropagateBackpressure) {
1594 signalLayerUpdate();
1595 break;
1596 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001597 }
Dan Stoza50182882016-07-08 12:02:20 -07001598
Steven Thomas050b2c82017-03-06 11:45:16 -08001599 // Now that we're going to make it to the handleMessageTransaction()
1600 // call below it's safe to call updateVrFlinger(), which will
1601 // potentially trigger a display handoff.
1602 updateVrFlinger();
1603
Dan Stoza6b9454d2014-11-07 16:00:59 -08001604 bool refreshNeeded = handleMessageTransaction();
1605 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001606
1607 updateCursorAsync();
1608 updateInputFlinger();
1609
Dan Stoza58784442014-12-02 16:58:17 -08001610 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001611 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001612 // Signal a refresh if a transaction modified the window state,
1613 // a new buffer was latched, or if HWC has requested a full
1614 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001615 signalRefresh();
1616 }
1617 break;
1618 }
1619 case MessageQueue::REFRESH: {
1620 handleMessageRefresh();
1621 break;
1622 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001623 }
1624}
1625
Dan Stoza6b9454d2014-11-07 16:00:59 -08001626bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001627 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001628
1629 // Apply any ready transactions in the queues if there are still transactions that have not been
1630 // applied, wake up during the next vsync period and check again
1631 bool transactionNeeded = false;
1632 if (!flushTransactionQueues()) {
1633 transactionNeeded = true;
1634 }
1635
Mathias Agopian4fec8732012-06-29 14:12:52 -07001636 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001637 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001638 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001639
1640 if (transactionNeeded) {
1641 setTransactionFlags(eTransactionNeeded);
1642 }
1643
1644 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001645}
1646
Mathias Agopian4fec8732012-06-29 14:12:52 -07001647void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001649
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001650 mRefreshPending = false;
1651
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001652 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001653 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001654 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001655 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001656 for (const auto& [token, display] : mDisplays) {
1657 beginFrame(display);
1658 prepareFrame(display);
1659 doDebugFlashRegions(display, repaintEverything);
1660 doComposition(display, repaintEverything);
1661 }
1662
Adrian Roos1e1a1282017-11-01 19:05:31 +01001663 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001664 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001665
1666 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001667 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001668
Dan Stozabfbffeb2016-07-21 14:49:33 -07001669 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001670 for (const auto& [token, displayDevice] : mDisplays) {
1671 auto display = displayDevice->getCompositionDisplay();
1672 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001673 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001674 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001675 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676
Jorim Jaggi90535212018-05-23 23:44:06 +02001677 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001678
David Sodman7e4ae112018-02-09 15:02:28 -08001679 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001680
1681 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001682}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684
1685bool SurfaceFlinger::handleMessageInvalidate() {
1686 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001687 bool refreshNeeded = handlePageFlip();
1688
Vishnu Nair4351ad52019-02-11 14:13:02 -08001689 if (mVisibleRegionsDirty) {
1690 computeLayerBounds();
1691 }
1692
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001693 for (auto& layer : mLayersPendingRefresh) {
1694 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001695 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001696 invalidateLayerStack(layer, visibleReg);
1697 }
1698 mLayersPendingRefresh.clear();
1699 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700}
1701
David Sodman79bba0e2018-08-05 18:07:49 -07001702void SurfaceFlinger::calculateWorkingSet() {
1703 ATRACE_CALL();
1704 ALOGV(__FUNCTION__);
1705
David Sodman79bba0e2018-08-05 18:07:49 -07001706 // build the h/w work list
1707 if (CC_UNLIKELY(mGeometryInvalid)) {
1708 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001709 for (const auto& [token, displayDevice] : mDisplays) {
1710 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001711 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001712 if (!displayId) {
1713 continue;
1714 }
David Sodman79bba0e2018-08-05 18:07:49 -07001715
Lloyd Pique32cbe282018-10-19 13:09:22 -07001716 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001717 for (size_t i = 0; i < currentLayers.size(); i++) {
1718 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001719
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001720 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001721 layer->forceClientComposition(displayDevice);
1722 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001723 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001724
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001726 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001727 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 }
David Sodman79bba0e2018-08-05 18:07:49 -07001729 }
1730 }
1731 }
1732
1733 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001734 for (const auto& [token, displayDevice] : mDisplays) {
1735 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001736 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001738 continue;
1739 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001740 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001741
1742 if (mDrawingState.colorMatrixChanged) {
1743 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001745 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001746 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001747 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001748 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1749 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001750 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001751 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001752 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1753 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001754 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001755 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001756 }
1757
Peiyong Lind3788632018-09-18 16:01:31 -07001758 // TODO(b/111562338) remove when composer 2.3 is shipped.
1759 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001760 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001761 }
1762
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001763 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001764 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001765 }
1766
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001767 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001768 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001769 layer->setCompositionType(displayDevice,
1770 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001771 continue;
1772 }
1773
Lloyd Pique32cbe282018-10-19 13:09:22 -07001774 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001775 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001776 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001777 }
1778
Peiyong Lin13effd12018-07-24 17:01:47 -07001779 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001780 ColorMode colorMode;
1781 Dataspace dataSpace;
1782 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001783 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001784 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 }
1786 }
1787
1788 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001789
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001790 for (const auto& [token, displayDevice] : mDisplays) {
1791 auto display = displayDevice->getCompositionDisplay();
1792 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001793 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001794 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1795 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1796 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001797 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001798 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001799 }
1800 }
David Sodman79bba0e2018-08-05 18:07:49 -07001801}
1802
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1804 bool repaintEverything) {
1805 auto display = displayDevice->getCompositionDisplay();
1806 const auto& displayState = display->getState();
1807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808 // is debugging enabled
1809 if (CC_LIKELY(!mDebugRegion))
1810 return;
1811
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001813 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001814 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001815 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001816 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001817 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001818 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001819
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001820 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821 }
1822 }
1823
Lloyd Pique32cbe282018-10-19 13:09:22 -07001824 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825
1826 if (mDebugRegion > 1) {
1827 usleep(mDebugRegion * 1000);
1828 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001829
Lloyd Pique32cbe282018-10-19 13:09:22 -07001830 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831}
1832
Adrian Roos1e1a1282017-11-01 19:05:31 +01001833void SurfaceFlinger::doTracing(const char* where) {
1834 ATRACE_CALL();
1835 ATRACE_NAME(where);
1836 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001837 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001838 }
1839}
1840
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001841void SurfaceFlinger::logLayerStats() {
1842 ATRACE_CALL();
1843 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001844 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001845 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001846 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001847 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001848 }
1849 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001850
1851 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001852 }
1853}
1854
David Sodman2b406362017-12-15 13:33:47 -08001855void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 ATRACE_CALL();
1858 ALOGV("preComposition");
1859
David Sodman2b406362017-12-15 13:33:47 -08001860 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1861
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001863 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001864 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865 needExtraInvalidate = true;
1866 }
Robert Carr2047fae2016-11-28 14:09:09 -08001867 });
1868
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869 if (needExtraInvalidate) {
1870 signalLayerUpdate();
1871 }
1872}
1873
Ana Krulece588e312018-09-18 12:32:24 -07001874void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1875 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001876 // Update queue of past composite+present times and determine the
1877 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001878 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001879 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001880 while (!getBE().mCompositePresentTimes.empty()) {
1881 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882 // Cached values should have been updated before calling this method,
1883 // which helps avoid duplicate syscalls.
1884 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1885 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1886 break;
1887 }
1888 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001889 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890 }
1891
1892 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001893 while (getBE().mCompositePresentTimes.size() > 16) {
1894 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001895 }
1896
Ana Krulece588e312018-09-18 12:32:24 -07001897 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001898}
1899
Ana Krulece588e312018-09-18 12:32:24 -07001900void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1901 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 // Integer division and modulo round toward 0 not -inf, so we need to
1903 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001904 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1905 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1906 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907
Ana Krulec757f63a2019-01-25 10:46:18 -08001908 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001909 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001910 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001911 }
1912
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001913 // Snap the latency to a value that removes scheduling jitter from the
1914 // composition and present times, which often have >1ms of jitter.
1915 // Reducing jitter is important if an app attempts to extrapolate
1916 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001917 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001919 nsecs_t bias = stats.vsyncPeriod / 2;
1920 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1921 nsecs_t snappedCompositeToPresentLatency =
1922 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923
David Sodman99974d22017-11-28 12:04:33 -08001924 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001925 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1926 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001927 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928}
1929
Ady Abraham8164d482019-01-11 14:47:59 -08001930// debug patch for b/119477596 - add stack guards to catch stack
1931// corruptions and disable clang optimizations.
1932// The code below is temporary and planned to be removed once stack
1933// corruptions are found.
1934#pragma clang optimize off
1935class StackGuard {
1936public:
1937 StackGuard(const char* name, const char* func, int line) {
1938 guarders.reserve(MIN_CAPACITY);
1939 guarders.push_back({this, name, func, line});
1940 validate();
1941 }
1942 ~StackGuard() {
1943 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1944 if (i->guard == this) {
1945 guarders.erase(i);
1946 break;
1947 }
1948 }
1949 }
1950
1951 static void validate() {
1952 for (const auto& guard : guarders) {
1953 if (guard.guard->cookie != COOKIE_VALUE) {
1954 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1955 CallStack stack(LOG_TAG);
1956 abort();
1957 }
1958 }
1959 }
1960
1961private:
1962 uint64_t cookie = COOKIE_VALUE;
1963 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1964 static constexpr size_t MIN_CAPACITY = 16;
1965
1966 struct GuarderElement {
1967 StackGuard* guard;
1968 const char* name;
1969 const char* func;
1970 int line;
1971 };
1972
1973 static std::vector<GuarderElement> guarders;
1974};
1975std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1976
1977#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1978
1979#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001980void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001981{
Ady Abraham8164d482019-01-11 14:47:59 -08001982 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 ATRACE_CALL();
1984 ALOGV("postComposition");
1985
Brian Anderson3546a3f2016-07-14 11:51:14 -07001986 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001987 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001988 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001989 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001990 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001991 }
Ady Abraham8164d482019-01-11 14:47:59 -08001992 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001993
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001994 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001995 const auto displayDevice = getDefaultDisplayDeviceLocked();
1996 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001997
David Sodman73beded2017-11-15 11:56:06 -08001998 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002000 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2001
Lloyd Pique32cbe282018-10-19 13:09:22 -07002002 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002004 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2005 ->getRenderSurface()
2006 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002007 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 } else {
2009 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2010 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011
Ady Abraham8164d482019-01-11 14:47:59 -08002012 ASSERT_ON_STACK_GUARD();
2013
David Sodman73beded2017-11-15 11:56:06 -08002014 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002015 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2016 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002017 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002018 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002019 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020
Ana Krulece588e312018-09-18 12:32:24 -07002021 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002022 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002023 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024
Ady Abraham8164d482019-01-11 14:47:59 -08002025 ASSERT_ON_STACK_GUARD();
2026
David Sodman2b406362017-12-15 13:33:47 -08002027 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028 // when we started doing work for this frame, but that should be okay
2029 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002030 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002031 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002032 DEFINE_STACK_GUARD(compositorTiming);
2033
Brian Andersond0010582017-03-07 13:20:31 -08002034 {
David Sodman99974d22017-11-28 12:04:33 -08002035 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002036 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002037 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002038
2039 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002040 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041
Robert Carr2047fae2016-11-28 14:09:09 -08002042 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002043 bool frameLatched =
2044 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2045 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002047 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002048 recordBufferingStats(layer->getName().string(),
2049 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002050 }
Ady Abraham8164d482019-01-11 14:47:59 -08002051 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002052 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002053
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002054 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002055 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002056 mScheduler->addPresentFence(presentFenceTime);
2057 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002058 }
2059
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002060 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002061 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2062 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002063 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002064 }
2065 }
2066
Ady Abraham8164d482019-01-11 14:47:59 -08002067 ASSERT_ON_STACK_GUARD();
2068
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002069 if (mAnimCompositionPending) {
2070 mAnimCompositionPending = false;
2071
Brian Anderson4e606e32017-03-16 15:34:57 -07002072 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002074 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002075
2076 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002077 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002078 // The HWC doesn't support present fences, so use the refresh
2079 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 const nsecs_t presentTime =
2081 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002082 DEFINE_STACK_GUARD(presentTime);
2083
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002084 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002085 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002086 }
2087 mAnimFrameTracker.advanceFrame();
2088 }
Dan Stozab90cf072015-03-05 11:05:59 -08002089
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
2091
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002092 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002093 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002094 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002095 }
2096
Ady Abraham8164d482019-01-11 14:47:59 -08002097 ASSERT_ON_STACK_GUARD();
2098
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002099 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002100
Ady Abraham8164d482019-01-11 14:47:59 -08002101 ASSERT_ON_STACK_GUARD();
2102
Lloyd Pique32cbe282018-10-19 13:09:22 -07002103 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2104 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002105 return;
2106 }
2107
2108 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002110 if (mHasPoweredOff) {
2111 mHasPoweredOff = false;
2112 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002113 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002114 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002115 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002116 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002117 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2118 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002119 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002120 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002121 }
David Sodman4a36e932017-11-07 14:29:47 -08002122 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002123
2124 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002125 }
David Sodman4a36e932017-11-07 14:29:47 -08002126 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002128
2129 {
2130 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002131 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002132 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002133 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002134 if (refillCount > 0) {
2135 const size_t offset = mTexturePool.size();
2136 mTexturePool.resize(mTexturePoolSize);
2137 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2138 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2139 }
Ady Abraham8164d482019-01-11 14:47:59 -08002140 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002141 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002142
Marissa Wallfda30bb2018-10-12 11:34:28 -07002143 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002144 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002145
2146 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002147}
Ady Abraham8164d482019-01-11 14:47:59 -08002148#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002149
Vishnu Nair4351ad52019-02-11 14:13:02 -08002150void SurfaceFlinger::computeLayerBounds() {
2151 for (const auto& pair : mDisplays) {
2152 const auto& displayDevice = pair.second;
2153 const auto display = displayDevice->getCompositionDisplay();
2154 for (const auto& layer : mDrawingState.layersSortedByZ) {
2155 // only consider the layers on the given layer stack
2156 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002157 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002158 }
2159
2160 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2161 }
2162 }
2163}
2164
Mathias Agopiancd60f992012-08-16 16:28:27 -07002165void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 ATRACE_CALL();
2167 ALOGV("rebuildLayerStacks");
2168
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002169 // We need to clear these out now as these may be holding on to a
2170 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2171 // also holds a reference. When the set of visible layers is recomputed,
2172 // some layers may be destroyed if the only thing keeping them alive was
2173 // that list of visible layers associated with each display. The layer
2174 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2175 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2176 for (const auto& [token, display] : mDisplays) {
2177 getBE().mCompositionInfo[token].clear();
2178 }
2179
Mathias Agopiancd60f992012-08-16 16:28:27 -07002180 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002181 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002182 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002183 mVisibleRegionsDirty = false;
2184 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002185
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002186 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002187 const auto& displayDevice = pair.second;
2188 auto display = displayDevice->getCompositionDisplay();
2189 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002190 Region opaqueRegion;
2191 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002192 compositionengine::Output::OutputLayers layersSortedByZ;
2193 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002194 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002195 const ui::Transform& tr = displayState.transform;
2196 const Rect bounds = displayState.bounds;
2197 if (displayState.isEnabled) {
2198 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002199
Jeff Sharkey76488112017-02-27 14:15:18 -07002200 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002201 auto compositionLayer = layer->getCompositionLayer();
2202 if (compositionLayer == nullptr) {
2203 return;
2204 }
2205
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002207 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2208 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2209
Lloyd Pique07e33212018-12-18 16:33:37 -08002210 bool needsOutputLayer = false;
2211
Lloyd Piqueef36b002019-01-23 17:52:04 -08002212 if (display->belongsInOutput(layer->getLayerStack(),
2213 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002214 Region drawRegion(tr.transform(
2215 layer->visibleNonTransparentRegion));
2216 drawRegion.andSelf(bounds);
2217 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002218 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002219 }
Chia-I Wu83806892017-11-16 10:50:20 -08002220 }
2221
Lloyd Pique07e33212018-12-18 16:33:37 -08002222 if (needsOutputLayer) {
2223 layersSortedByZ.emplace_back(
2224 display->getOrCreateOutputLayer(displayId, compositionLayer,
2225 layerFE));
2226 deprecated_layersSortedByZ.add(layer);
2227
2228 auto& outputLayerState = layersSortedByZ.back()->editState();
2229 outputLayerState.visibleRegion =
2230 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2231 } else if (displayId) {
2232 // For layers that are being removed from a HWC display,
2233 // and that have queued frames, add them to a a list of
2234 // released layers so we can properly set a fence.
2235 bool hasExistingOutputLayer =
2236 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2237 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2238 mLayersWithQueuedFrames.cend(),
2239 layer) != mLayersWithQueuedFrames.cend();
2240
2241 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002242 layersNeedingFences.add(layer);
2243 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002244 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 });
2246 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002247
2248 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2249
2250 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002251 displayDevice->setLayersNeedingFences(layersNeedingFences);
2252
2253 Region undefinedRegion{bounds};
2254 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2255
2256 display->editState().undefinedRegion = undefinedRegion;
2257 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002258 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002259 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002260}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002261
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002262// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002264// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002265// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002266// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002267// The returned HDR data space is one of
2268// - Dataspace::UNKNOWN
2269// - Dataspace::BT2020_HLG
2270// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2272 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002273 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 *outHdrDataSpace = Dataspace::UNKNOWN;
2275
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002277 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278 case Dataspace::V0_SCRGB:
2279 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002280 case Dataspace::BT2020:
2281 case Dataspace::BT2020_ITU:
2282 case Dataspace::BT2020_LINEAR:
2283 case Dataspace::DISPLAY_BT2020:
2284 bestDataSpace = Dataspace::DISPLAY_BT2020;
2285 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002287 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 case Dataspace::BT2020_PQ:
2290 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002291 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002292 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002294 case Dataspace::BT2020_HLG:
2295 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002296 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297 // When there's mixed PQ content and HLG content, we set the HDR
2298 // data space to be BT2020_PQ and convert HLG to PQ.
2299 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2300 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002301 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002302 break;
2303 default:
2304 break;
2305 }
Romain Guy54f154a2017-10-24 21:40:32 +01002306 }
2307
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002308 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002309}
2310
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2313 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2315 *outMode = ColorMode::NATIVE;
2316 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002319 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002320
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002321 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002322 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002324 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2325
Peiyong Lina3ea5592019-02-10 14:45:00 -08002326 switch (mForceColorMode) {
2327 case ColorMode::SRGB:
2328 bestDataSpace = Dataspace::V0_SRGB;
2329 break;
2330 case ColorMode::DISPLAY_P3:
2331 bestDataSpace = Dataspace::DISPLAY_P3;
2332 break;
2333 default:
2334 break;
2335 }
2336
Peiyong Lindfde5112018-06-05 10:58:41 -07002337 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002338 const bool isHdr =
2339 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002340 if (isHdr) {
2341 bestDataSpace = hdrDataSpace;
2342 }
2343
Chia-I Wu0d711262018-05-21 15:19:35 -07002344 RenderIntent intent;
2345 switch (mDisplayColorSetting) {
2346 case DisplayColorSetting::MANAGED:
2347 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002349 break;
2350 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002351 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002352 break;
2353 default: // vendor display color setting
2354 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2355 break;
2356 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002357
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002358 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002359}
2360
Lloyd Pique32cbe282018-10-19 13:09:22 -07002361void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2362 auto display = displayDevice->getCompositionDisplay();
2363 const auto& displayState = display->getState();
2364
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002365 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2367 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002368
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369 // If nothing has changed (!dirty), don't recompose.
2370 // If something changed, but we don't currently have any visible layers,
2371 // and didn't when we last did a composition, then skip it this time.
2372 // The second rule does two things:
2373 // - When all layers are removed from a display, we'll emit one black
2374 // frame, then nothing more until we get new layers.
2375 // - When a display is created with a private layer stack, we won't
2376 // emit any black frames until a layer is added to the layer stack.
2377 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002378
Dominik Laskowski075d3172018-05-24 15:50:06 -07002379 const char flagPrefix[] = {'-', '+'};
2380 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2382 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2383 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2384 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002385
Lloyd Pique31cb2942018-10-19 17:23:03 -07002386 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002387
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002390 }
2391}
2392
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2394 auto display = displayDevice->getCompositionDisplay();
2395 const auto& displayState = display->getState();
2396
2397 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398 return;
David Sodman2b406362017-12-15 13:33:47 -08002399 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002401 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002402 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002404}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002405
Lloyd Pique32cbe282018-10-19 13:09:22 -07002406void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002407 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 ALOGV("doComposition");
2409
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410 auto display = displayDevice->getCompositionDisplay();
2411 const auto& displayState = display->getState();
2412
2413 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002415 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002419
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002421 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424}
2425
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426void SurfaceFlinger::postFrame()
2427{
2428 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 const auto display = getDefaultDisplayDeviceLocked();
2430 if (display && getHwComposer().isConnected(*display->getId())) {
2431 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002432 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2433 logFrameStats();
2434 }
2435 }
2436}
2437
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002439 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002441
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 auto display = displayDevice->getCompositionDisplay();
2443 const auto& displayState = display->getState();
2444 const auto displayId = display->getId();
2445
David Sodmanfa9b2af2017-12-24 13:28:59 -08002446 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002447
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 if (displayId) {
2450 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002451 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002452 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002454 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002455
Chia-I Wu7b549592017-11-15 09:14:57 -08002456 // The layer buffer from the previous frame (if any) is released
2457 // by HWC only when the release fence from this frame (if any) is
2458 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002459 if (displayId && layer->hasHwcLayer(displayDevice)) {
2460 releaseFence =
2461 getHwComposer().getLayerReleaseFence(*displayId,
2462 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002463 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002464
2465 // If the layer was client composited in the previous frame, we
2466 // need to merge with the previous client target acquire fence.
2467 // Since we do not track that, always merge with the current
2468 // client target acquire fence when it is available, even though
2469 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002470 if (layer->getCompositionType(displayDevice) ==
2471 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002472 releaseFence =
2473 Fence::merge("LayerRelease", releaseFence,
2474 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002475 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002476
David Sodman15094112018-10-11 09:39:37 -07002477 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 }
Chia-I Wu83806892017-11-16 10:50:20 -08002479
2480 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002481 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002482 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002484 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002485 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002487 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002488 }
2489 }
2490
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 if (displayId) {
2492 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002493 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495}
2496
Mathias Agopian87baae12012-07-31 12:38:26 -07002497void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498{
Mathias Agopian841cde52012-03-01 15:44:37 -08002499 ATRACE_CALL();
2500
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002501 // here we keep a copy of the drawing state (that is the state that's
2502 // going to be overwritten by handleTransactionLocked()) outside of
2503 // mStateLock so that the side-effects of the State assignment
2504 // don't happen with mStateLock held (which can cause deadlocks).
2505 State drawingState(mDrawingState);
2506
Mathias Agopianca4d3602011-05-19 15:38:14 -07002507 Mutex::Autolock _l(mStateLock);
2508 const nsecs_t now = systemTime();
2509 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510
Mathias Agopianca4d3602011-05-19 15:38:14 -07002511 // Here we're guaranteed that some transaction flags are set
2512 // so we can call handleTransactionLocked() unconditionally.
2513 // We call getTransactionFlags(), which will also clear the flags,
2514 // with mStateLock held to guarantee that mCurrentState won't change
2515 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002516
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002517 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002518 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002519 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002520
Mathias Agopianca4d3602011-05-19 15:38:14 -07002521 mLastTransactionTime = systemTime() - now;
2522 mDebugInTransaction = 0;
2523 invalidateHwcGeometry();
2524 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002525}
2526
Lloyd Piqueba04e622017-12-14 17:11:26 -08002527void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2528 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 const std::optional<DisplayIdentificationInfo> info =
2530 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533 continue;
2534 }
2535
Lloyd Piqueba04e622017-12-14 17:11:26 -08002536 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002538 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 mPhysicalDisplayTokens[info->id] = new BBinder();
2540 DisplayDeviceState state;
2541 state.displayId = info->id;
2542 state.isSecure = true; // All physical displays are currently considered secure.
2543 state.displayName = info->name;
2544 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2545 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002546 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002547 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002548 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2551 if (index >= 0) {
2552 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2553 mInterceptor->saveDisplayDeletion(state.sequenceId);
2554 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002555 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002557 }
2558
2559 processDisplayChangesLocked();
2560 }
2561
2562 mPendingHotplugEvents.clear();
2563}
2564
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002565void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002566 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2567 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002568}
2569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002572 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 const sp<IGraphicBufferProducer>& producer) {
2574 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002575 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002577 creationArgs.isSecure = state.isSecure;
2578 creationArgs.displaySurface = dispSurface;
2579 creationArgs.hasWideColorGamut = false;
2580 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002581
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002582 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 creationArgs.isPrimary = isInternalDisplay;
2584
2585 if (useColorManagement && displayId) {
2586 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002587 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002588 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002591
Dominik Laskowski7e045462018-05-30 13:02:02 -07002592 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002594 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595 }
tangrobin6753a022018-08-10 10:58:54 +08002596 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 if (displayId) {
2599 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002600 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002602 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603
Lloyd Pique90c115d2018-09-18 21:39:42 -07002604 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 // Make sure that composition can never be stalled by a virtual display
2609 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002610 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002611 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2613 }
2614
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 creationArgs.displayInstallOrientation =
2616 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002617
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002619 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620
Lloyd Pique90c115d2018-09-18 21:39:42 -07002621 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622
2623 if (maxFrameBufferAcquiredBuffers >= 3) {
2624 nativeWindowSurface->preallocateBuffers();
2625 }
2626
2627 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002628 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002631 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002633 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2634 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 if (!state.isVirtual()) {
2636 LOG_ALWAYS_FATAL_IF(!displayId);
2637 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002638 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 display->setLayerStack(state.layerStack);
2641 display->setProjection(state.orientation, state.viewport, state.frame);
2642 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002645}
2646
Lloyd Pique347200f2017-12-14 17:00:15 -08002647void SurfaceFlinger::processDisplayChangesLocked() {
2648 // here we take advantage of Vector's copy-on-write semantics to
2649 // improve performance by skipping the transaction entirely when
2650 // know that the lists are identical
2651 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2652 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2653 if (!curr.isIdenticalTo(draw)) {
2654 mVisibleRegionsDirty = true;
2655 const size_t cc = curr.size();
2656 size_t dc = draw.size();
2657
2658 // find the displays that were removed
2659 // (ie: in drawing state but not in current state)
2660 // also handle displays that changed
2661 // (ie: displays that are in both lists)
2662 for (size_t i = 0; i < dc;) {
2663 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2664 if (j < 0) {
2665 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002667 // Save display ID before disconnecting.
2668 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002669 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002670
2671 if (!display->isVirtual()) {
2672 LOG_ALWAYS_FATAL_IF(!displayId);
2673 dispatchDisplayHotplugEvent(displayId->value, false);
2674 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002676
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002677 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002678 } else {
2679 // this display is in both lists. see if something changed.
2680 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2683 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2684 if (state_binder != draw_binder) {
2685 // changing the surface is like destroying and
2686 // recreating the DisplayDevice, so we just remove it
2687 // from the drawing state, so that it get re-added
2688 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002690 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 mDrawingState.displays.removeItemsAt(i);
2694 dc--;
2695 // at this point we must loop to the next item
2696 continue;
2697 }
2698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 }
2703 if ((state.orientation != draw[i].orientation) ||
2704 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 }
2707 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710 }
2711 }
2712 ++i;
2713 }
2714
2715 // find displays that were added
2716 // (ie: in current state but not in drawing state)
2717 for (size_t i = 0; i < cc; i++) {
2718 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2719 const DisplayDeviceState& state(curr[i]);
2720
Lloyd Pique542307f2018-10-19 13:24:08 -07002721 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 sp<IGraphicBufferProducer> producer;
2723 sp<IGraphicBufferProducer> bqProducer;
2724 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002725 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002726
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002728 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 // Virtual displays without a surface are dormant:
2730 // they have external state (layer stack, projection,
2731 // etc.) but no internal state (i.e. a DisplayDevice).
2732 if (state.surface != nullptr) {
2733 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002734 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 int width = 0;
2736 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2737 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2738 int height = 0;
2739 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2740 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2741 int intFormat = 0;
2742 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002744 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 displayId =
2747 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 }
2749
2750 // TODO: Plumb requested format back up to consumer
2751
2752 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 bqProducer, bqConsumer,
2755 state.displayName);
2756
2757 dispSurface = vds;
2758 producer = vds;
2759 }
2760 } else {
2761 ALOGE_IF(state.surface != nullptr,
2762 "adding a supported display, but rendering "
2763 "surface is provided (%p), ignoring it",
2764 state.surface.get());
2765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 displayId = state.displayId;
2767 LOG_ALWAYS_FATAL_IF(!displayId);
2768 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 producer = bqProducer;
2770 }
2771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002773 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002775 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002777 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002778 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002779 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 }
2781 }
2782 }
2783 }
2784 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002785
2786 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002787}
2788
Mathias Agopian87baae12012-07-31 12:38:26 -07002789void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002790{
Dan Stoza7dde5992015-05-22 09:51:44 -07002791 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002792 mCurrentState.traverseInZOrder([](Layer* layer) {
2793 layer->notifyAvailableFrames();
2794 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002795
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 /*
2797 * Traversal of the children
2798 * (perform the transaction for each of them if needed)
2799 */
2800
Mathias Agopian3559b072012-08-15 13:46:03 -07002801 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002802 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002804 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805
2806 const uint32_t flags = layer->doTransaction(0);
2807 if (flags & Layer::eVisibleRegion)
2808 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002809
2810 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002811 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002812 }
Robert Carr2047fae2016-11-28 14:09:09 -08002813 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 }
2815
2816 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002817 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 */
2819
Mathias Agopiane57f2922012-08-09 16:29:12 -07002820 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002821 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002822 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002825 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002826 // The transform hint might have changed for some layers
2827 // (either because a display has changed, or because a layer
2828 // as changed).
2829 //
2830 // Walk through all the layers in currentLayers,
2831 // and update their transform hint.
2832 //
2833 // If a layer is visible only on a single display, then that
2834 // display is used to calculate the hint, otherwise we use the
2835 // default display.
2836 //
2837 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2838 // the hint is set before we acquire a buffer from the surface texture.
2839 //
2840 // NOTE: layer transactions have taken place already, so we use their
2841 // drawing state. However, SurfaceFlinger's own transaction has not
2842 // happened yet, so we must use the current state layer list
2843 // (soon to become the drawing state list).
2844 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002846 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002847 bool first = true;
2848 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002849 // NOTE: we rely on the fact that layers are sorted by
2850 // layerStack first (so we don't have to traverse the list
2851 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002853 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002854 currentlayerStack = layerStack;
2855 // figure out if this layerstack is mirrored
2856 // (more than one display) if so, pick the default display,
2857 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 hintDisplay = nullptr;
2859 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002860 if (display->getCompositionDisplay()
2861 ->belongsInOutput(layer->getLayerStack(),
2862 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 if (hintDisplay) {
2864 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002865 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002866 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002867 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002868 }
2869 }
2870 }
2871 }
Chet Haase91d25932013-04-11 15:24:55 -07002872
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002873 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002874 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2875 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002876
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002877 // could be null when this layer is using a layerStack
2878 // that is not visible on any display. Also can occur at
2879 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002880 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002881 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002882
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002884 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 if (hintDisplay) {
2886 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002887 }
Robert Carr2047fae2016-11-28 14:09:09 -08002888
2889 first = false;
2890 });
Mathias Agopian84300952012-11-21 16:02:13 -08002891 }
2892
2893
Mathias Agopian3559b072012-08-15 13:46:03 -07002894 /*
2895 * Perform our own transaction if needed
2896 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002897
2898 if (mLayersAdded) {
2899 mLayersAdded = false;
2900 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002901 mVisibleRegionsDirty = true;
2902 }
2903
2904 // some layers might have been removed, so
2905 // we need to update the regions they're exposing.
2906 if (mLayersRemoved) {
2907 mLayersRemoved = false;
2908 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002909 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002911 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002913 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002914 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002915 }
Robert Carr2047fae2016-11-28 14:09:09 -08002916 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 }
2918
Vishnu Nairec0ab382019-02-13 15:32:56 -08002919 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002921}
2922
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002923void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002924 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002925 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002926 return;
2927 }
2928
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002929 if (mVisibleRegionsDirty || mInputInfoChanged) {
2930 mInputInfoChanged = false;
2931 updateInputWindowInfo();
2932 }
2933
2934 executeInputWindowCommands();
2935}
2936
2937void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002938 Vector<InputWindowInfo> inputHandles;
2939
2940 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2941 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002942 // When calculating the screen bounds we ignore the transparent region since it may
2943 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002944 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002945 }
2946 });
2947 mInputFlinger->setInputWindows(inputHandles);
2948}
2949
Vishnu Nairec0ab382019-02-13 15:32:56 -08002950void SurfaceFlinger::commitInputWindowCommands() {
2951 mInputWindowCommands.merge(mPendingInputWindowCommands);
2952 mPendingInputWindowCommands.clear();
2953}
2954
chaviwfbe5d9c2018-12-26 12:23:37 -08002955void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002956 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2957 if (transferTouchFocusCommand.fromToken != nullptr &&
2958 transferTouchFocusCommand.toToken != nullptr &&
2959 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2960 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2961 transferTouchFocusCommand.toToken);
2962 }
2963 }
2964
2965 mInputWindowCommands.clear();
2966}
2967
Riley Andrews03414a12014-07-01 14:22:59 -07002968void SurfaceFlinger::updateCursorAsync()
2969{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002970 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002971 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002972 continue;
2973 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2976 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002977 }
2978 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002979}
2980
chaviw61626f22018-11-15 16:26:27 -08002981void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2982 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002983 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002984 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002985 }
2986 layer->releasePendingBuffer(systemTime());
2987}
2988
Mathias Agopian4fec8732012-06-29 14:12:52 -07002989void SurfaceFlinger::commitTransaction()
2990{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002991 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002992 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 for (const auto& l : mLayersPendingRemoval) {
2994 recordBufferingStats(l->getName().string(),
2995 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002996
Lloyd Pique07e33212018-12-18 16:33:37 -08002997 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002998 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002999 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003000 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003001 }
3002 mLayersPendingRemoval.clear();
3003 }
3004
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003005 // If this transaction is part of a window animation then the next frame
3006 // we composite should be considered an animation as well.
3007 mAnimCompositionPending = mAnimTransactionPending;
3008
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003010 // clear the "changed" flags in current state
3011 mCurrentState.colorMatrixChanged = false;
3012
Robert Carr1f0a16a2016-10-24 16:27:39 -07003013 mDrawingState.traverseInZOrder([](Layer* layer) {
3014 layer->commitChildList();
3015 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003016 mTransactionPending = false;
3017 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019}
3020
Lloyd Pique32cbe282018-10-19 13:09:22 -07003021void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003023 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003025
Lloyd Pique32cbe282018-10-19 13:09:22 -07003026 auto display = displayDevice->getCompositionDisplay();
3027
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028 Region aboveOpaqueLayers;
3029 Region aboveCoveredLayers;
3030 Region dirty;
3031
Mathias Agopian87baae12012-07-31 12:38:26 -07003032 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033
Robert Carr2047fae2016-11-28 14:09:09 -08003034 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003035 // start with the whole surface at its current location
3036 const Layer::State& s(layer->getDrawingState());
3037
Jesse Hall01e29052013-02-19 16:13:35 -08003038 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003039 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003040 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003041 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003042
Mathias Agopianab028732010-03-16 16:41:46 -07003043 /*
3044 * opaqueRegion: area of a surface that is fully opaque.
3045 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003047
3048 /*
3049 * visibleRegion: area of a surface that is visible on screen
3050 * and not fully transparent. This is essentially the layer's
3051 * footprint minus the opaque regions above it.
3052 * Areas covered by a translucent surface are considered visible.
3053 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003055
3056 /*
3057 * coveredRegion: area of a surface that is covered by all
3058 * visible regions above it (which includes the translucent areas).
3059 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003061
Jesse Halla8026d22012-09-25 13:25:04 -07003062 /*
3063 * transparentRegion: area of a surface that is hinted to be completely
3064 * transparent. This is only used to tell when the layer has no visible
3065 * non-transparent regions and can be removed from the layer list. It
3066 * does not affect the visibleRegion of this layer or any layers
3067 * beneath it. The hint may not be correct if apps don't respect the
3068 * SurfaceView restrictions (which, sadly, some don't).
3069 */
3070 Region transparentRegion;
3071
Mathias Agopianab028732010-03-16 16:41:46 -07003072
3073 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003074 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003075 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003076 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003079 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003080 if (!visibleRegion.isEmpty()) {
3081 // Remove the transparent area from the visible region
3082 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003083 if (tr.preserveRects()) {
3084 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003085 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003086 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003087 // transformation too complex, can't do the
3088 // transparent region optimization.
3089 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003090 }
Mathias Agopianab028732010-03-16 16:41:46 -07003091 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092
Mathias Agopianab028732010-03-16 16:41:46 -07003093 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003095 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003096 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003097 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003098 // the opaque region is the layer's footprint
3099 opaqueRegion = visibleRegion;
3100 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 }
3102 }
3103
Robert Carre5f4f692018-01-12 13:12:28 -08003104 if (visibleRegion.isEmpty()) {
3105 layer->clearVisibilityRegions();
3106 return;
3107 }
3108
Mathias Agopianab028732010-03-16 16:41:46 -07003109 // Clip the covered region to the visible region
3110 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3111
3112 // Update aboveCoveredLayers for next (lower) layer
3113 aboveCoveredLayers.orSelf(visibleRegion);
3114
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 // subtract the opaque region covered by the layers above us
3116 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117
3118 // compute this layer's dirty region
3119 if (layer->contentDirty) {
3120 // we need to invalidate the whole region
3121 dirty = visibleRegion;
3122 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003123 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 layer->contentDirty = false;
3125 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003126 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003127 * the exposed region consists of two components:
3128 * 1) what's VISIBLE now and was COVERED before
3129 * 2) what's EXPOSED now less what was EXPOSED before
3130 *
3131 * note that (1) is conservative, we start with the whole
3132 * visible region but only keep what used to be covered by
3133 * something -- which mean it may have been exposed.
3134 *
3135 * (2) handles areas that were not covered by anything but got
3136 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003137 */
Mathias Agopianab028732010-03-16 16:41:46 -07003138 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 const Region oldVisibleRegion = layer->visibleRegion;
3140 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003141 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3142 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
3144 dirty.subtractSelf(aboveOpaqueLayers);
3145
3146 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003147 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148
Mathias Agopianab028732010-03-16 16:41:46 -07003149 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003151
Jesse Halla8026d22012-09-25 13:25:04 -07003152 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 layer->setVisibleRegion(visibleRegion);
3154 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003155 layer->setVisibleNonTransparentRegion(
3156 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003157 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158
Mathias Agopian87baae12012-07-31 12:38:26 -07003159 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160}
3161
Chia-I Wuab0c3192017-08-01 11:29:00 -07003162void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003163 for (const auto& [token, displayDevice] : mDisplays) {
3164 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003165 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003166 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003167 }
3168 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003169}
3170
Dan Stoza6b9454d2014-11-07 16:00:59 -08003171bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003173 ALOGV("handlePageFlip");
3174
Brian Andersond6927fb2016-07-23 23:37:30 -07003175 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176
Mathias Agopian4fec8732012-06-29 14:12:52 -07003177 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003178 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003179 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003180
3181 // Store the set of layers that need updates. This set must not change as
3182 // buffers are being latched, as this could result in a deadlock.
3183 // Example: Two producers share the same command stream and:
3184 // 1.) Layer 0 is latched
3185 // 2.) Layer 0 gets a new frame
3186 // 2.) Layer 1 gets a new frame
3187 // 3.) Layer 1 is latched.
3188 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3189 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003190 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003191 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003192 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003193 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003194 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003195 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003196 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003197 } else {
3198 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003199 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003200 } else {
3201 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003202 }
Robert Carr2047fae2016-11-28 14:09:09 -08003203 });
3204
Lloyd Piquef2c79392018-12-20 16:23:33 -08003205 if (!mLayersWithQueuedFrames.empty()) {
3206 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3207 // writes to Layer current state. See also b/119481871
3208 Mutex::Autolock lock(mStateLock);
3209
3210 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003211 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003212 mLayersPendingRefresh.push_back(layer);
3213 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003214 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003215 if (layer->isBufferLatched()) {
3216 newDataLatched = true;
3217 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003218 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003219 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003220
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003221 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222
3223 // If we will need to wake up at some time in the future to deal with a
3224 // queued frame that shouldn't be displayed during this vsync period, wake
3225 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003226 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003227 signalLayerUpdate();
3228 }
3229
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003230 // enter boot animation on first buffer latch
3231 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3232 ALOGI("Enter boot animation");
3233 mBootStage = BootStage::BOOTANIMATION;
3234 }
3235
Dan Stoza6b9454d2014-11-07 16:00:59 -08003236 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003237 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238}
3239
Mathias Agopianad456f92011-01-13 17:53:01 -08003240void SurfaceFlinger::invalidateHwcGeometry()
3241{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003242 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003243}
3244
Lloyd Pique32cbe282018-10-19 13:09:22 -07003245void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003246 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003247 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003248 // We only need to actually compose the display if:
3249 // 1) It is being handled by hardware composer, which may need this to
3250 // keep its virtual display state machine in sync, or
3251 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003252 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003253 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003254 return;
3255 }
3256
Dan Stoza9e56aa02015-11-02 13:00:03 -08003257 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003258 base::unique_fd readyFence;
3259 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003260
3261 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003262 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003265bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3266 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003267 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003268 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003269
Lloyd Pique32cbe282018-10-19 13:09:22 -07003270 auto display = displayDevice->getCompositionDisplay();
3271 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003272 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003273
3274 const Region bounds(displayState.bounds);
3275 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003276 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003277 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003278
Peiyong Lind3788632018-09-18 16:01:31 -07003279 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003280 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003281
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003282 renderengine::DisplaySettings clientCompositionDisplay;
3283 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3284 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003285
Dan Stoza9e56aa02015-11-02 13:00:03 -08003286 if (hasClientComposition) {
3287 ALOGV("hasClientComposition");
3288
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003289 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003290
3291 if (buf == nullptr) {
3292 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3293 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003294 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003295 return false;
3296 }
3297
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003298 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3299 clientCompositionDisplay.clip = displayState.scissor;
3300 const ui::Transform& displayTransform = displayState.transform;
3301 mat4 m;
3302 m[0][0] = displayTransform[0][0];
3303 m[0][1] = displayTransform[0][1];
3304 m[0][3] = displayTransform[0][2];
3305 m[1][0] = displayTransform[1][0];
3306 m[1][1] = displayTransform[1][1];
3307 m[1][3] = displayTransform[1][2];
3308 m[3][0] = displayTransform[2][0];
3309 m[3][1] = displayTransform[2][1];
3310 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003311
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003312 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003313
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003314 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003315 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003316 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003317 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003318 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003319 clientCompositionDisplay.outputDataspace = outputDataspace;
3320 clientCompositionDisplay.maxLuminance =
3321 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003322
Lloyd Pique441d5042018-10-18 16:49:51 -07003323 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003324 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003325 getHwComposer()
3326 .hasDisplayCapability(displayId,
3327 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003328
Peiyong Lind3788632018-09-18 16:01:31 -07003329 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003330 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3331 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003332 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003333 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003334 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003335
Mathias Agopian85d751c2012-08-29 16:59:24 -07003336 /*
3337 * and then, render the layers targeted at the framebuffer
3338 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003339
Dan Stoza9e56aa02015-11-02 13:00:03 -08003340 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003341 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003342 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003343 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003344 const Region viewportRegion(displayState.viewport);
3345 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003346 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003347 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003348 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003349 switch (layer->getCompositionType(displayDevice)) {
3350 case Hwc2::IComposerClient::Composition::CURSOR:
3351 case Hwc2::IComposerClient::Composition::DEVICE:
3352 case Hwc2::IComposerClient::Composition::SIDEBAND:
3353 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003354 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003355 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003356 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003357 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003358 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003359 // never clear the very first layer since we're
3360 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003361 renderengine::LayerSettings layerSettings;
3362 Region dummyRegion;
3363 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3364 layerSettings);
3365
3366 if (prepared) {
3367 layerSettings.source.buffer.buffer = nullptr;
3368 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3369 layerSettings.alpha = half(0.0);
3370 layerSettings.disableBlending = true;
3371 clientCompositionLayers.push_back(layerSettings);
3372 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003373 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003375 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003376 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003377 renderengine::LayerSettings layerSettings;
3378 bool prepared =
3379 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3380 if (prepared) {
3381 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003382 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 break;
3384 }
3385 default:
3386 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003387 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003388 } else {
3389 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003390 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003391 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003392 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003393
Alec Mouri820c7402019-01-23 13:02:39 -08003394 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003395 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003396 clientCompositionDisplay.clearRegion = clearRegion;
3397 if (!debugRegion.isEmpty()) {
3398 Region::const_iterator it = debugRegion.begin();
3399 Region::const_iterator end = debugRegion.end();
3400 while (it != end) {
3401 const Rect& rect = *it++;
3402 renderengine::LayerSettings layerSettings;
3403 layerSettings.source.buffer.buffer = nullptr;
3404 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3405 layerSettings.geometry.boundaries = rect.toFloatRect();
3406 layerSettings.alpha = half(1.0);
3407 clientCompositionLayers.push_back(layerSettings);
3408 }
3409 }
3410 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3411 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003412 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003413 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414}
3415
Chia-I Wu28e3a252018-09-07 12:05:02 -07003416void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003417 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003418 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003419}
3420
Dan Stoza7d89d062015-04-30 13:29:25 -07003421status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003422 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003423 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003424 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003425 const sp<Layer>& parent,
3426 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003427{
Dan Stoza7d89d062015-04-30 13:29:25 -07003428 // add this layer to the current state list
3429 {
3430 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003431 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003432 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3433 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003434 return NO_MEMORY;
3435 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003436 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003437 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003438 } else if (parent == nullptr) {
3439 lbc->onRemovedFromCurrentState();
3440 } else if (parent->isRemovedFromCurrentState()) {
3441 parent->addChild(lbc);
3442 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003443 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003444 parent->addChild(lbc);
3445 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003446
Yiwei Zhang243b3782018-05-15 17:40:04 -07003447 if (gbc != nullptr) {
3448 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3449 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3450 mMaxGraphicBufferProducerListSize,
3451 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3452 mGraphicBufferProducerList.size(),
3453 mMaxGraphicBufferProducerListSize, mNumLayers);
3454 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003456 }
3457
Mathias Agopian96f08192010-06-02 23:28:45 -07003458 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003459 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003460
Dan Stoza7d89d062015-04-30 13:29:25 -07003461 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003462}
3463
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003464uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003465 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003466}
3467
Mathias Agopian3f844832013-08-07 21:24:32 -07003468uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003469 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470}
3471
Mathias Agopian3f844832013-08-07 21:24:32 -07003472uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003473 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003474}
3475
3476uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003477 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003478 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003479 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003480 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003481 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482 }
3483 return old;
3484}
3485
Marissa Wall713b63f2018-10-17 15:42:43 -07003486bool SurfaceFlinger::flushTransactionQueues() {
3487 Mutex::Autolock _l(mStateLock);
3488 auto it = mTransactionQueues.begin();
3489 while (it != mTransactionQueues.end()) {
3490 auto& [applyToken, transactionQueue] = *it;
3491
3492 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003493 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3494 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003495 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003496 break;
3497 }
Robert Carr14167e02019-02-13 13:50:55 -08003498 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003499 transactionQueue.pop();
3500 }
3501
3502 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3503 }
3504 return mTransactionQueues.empty();
3505}
3506
chaviwca27f252018-02-06 16:46:39 -08003507bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3508 for (const ComposerState& state : states) {
3509 // Here we need to check that the interface we're given is indeed
3510 // one of our own. A malicious client could give us a nullptr
3511 // IInterface, or one of its own or even one of our own but a
3512 // different type. All these situations would cause us to crash.
3513 if (state.client == nullptr) {
3514 return true;
3515 }
3516
3517 sp<IBinder> binder = IInterface::asBinder(state.client);
3518 if (binder == nullptr) {
3519 return true;
3520 }
3521
3522 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3523 return true;
3524 }
3525 }
3526 return false;
3527}
3528
Marissa Wall17b4e452018-12-26 16:32:34 -08003529bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3530 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003531 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003532 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3533 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3534 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3535 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3536 return false;
3537 }
3538
Marissa Wall713b63f2018-10-17 15:42:43 -07003539 for (const ComposerState& state : states) {
3540 const layer_state_t& s = state.state;
3541 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3542 continue;
3543 }
3544 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003545 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003546 }
3547 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003548 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003549}
3550
3551void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3552 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003553 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003554 const InputWindowCommands& inputWindowCommands,
3555 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003556 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003557
3558 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3559
Mathias Agopian698c0872011-06-28 19:09:31 -07003560 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003561
chaviwca27f252018-02-06 16:46:39 -08003562 if (containsAnyInvalidClientState(states)) {
3563 return;
3564 }
3565
Marissa Wall713b63f2018-10-17 15:42:43 -07003566 // If its TransactionQueue already has a pending TransactionState or if it is pending
3567 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003568 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003569 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3570 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 setTransactionFlags(eTransactionNeeded);
3572 return;
3573 }
3574
Robert Carr14167e02019-02-13 13:50:55 -08003575 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003576}
3577
3578void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003579 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003580 const InputWindowCommands& inputWindowCommands,
3581 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003582 uint32_t transactionFlags = 0;
3583
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003584 if (flags & eAnimation) {
3585 // For window updates that are part of an animation we must wait for
3586 // previous animation "frames" to be handled.
3587 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003588 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003589 if (CC_UNLIKELY(err != NO_ERROR)) {
3590 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003591 // caller after a few seconds.
3592 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3593 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003594 mAnimTransactionPending = false;
3595 break;
3596 }
3597 }
3598 }
3599
chaviwca27f252018-02-06 16:46:39 -08003600 for (const DisplayState& display : displays) {
3601 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003602 }
3603
Marissa Walle2ffb422018-10-12 11:33:52 -07003604 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003605 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003606 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003607 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003608 // If the state doesn't require a traversal and there are callbacks, send them now
3609 if (!(clientStateFlags & eTraversalNeeded)) {
3610 mTransactionCompletedThread.sendCallbacks();
3611 }
3612 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003613
chaviw273171b2018-12-26 11:46:30 -08003614 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3615
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003616 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3617 // anyway. This can be used as a flush mechanism for previous async transactions.
3618 // Empty animation transaction can be used to simulate back-pressure, so also force a
3619 // transaction for empty animation transactions.
3620 if (transactionFlags == 0 &&
3621 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003622 transactionFlags = eTransactionNeeded;
3623 }
3624
Mathias Agopian386aa982011-11-07 21:58:03 -08003625 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003626 if (mInterceptor->isEnabled()) {
3627 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003628 }
Irvel468051e2016-06-13 16:44:44 -07003629
Mathias Agopian386aa982011-11-07 21:58:03 -08003630 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003631 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3632 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003633 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003634
3635 // if this is a synchronous transaction, wait for it to take effect
3636 // before returning.
3637 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003638 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003639 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003640 if (flags & eAnimation) {
3641 mAnimTransactionPending = true;
3642 }
3643 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003644 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3645 if (CC_UNLIKELY(err != NO_ERROR)) {
3646 // just in case something goes wrong in SF, return to the
3647 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003648 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3649 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003650 break;
3651 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653 }
3654}
3655
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003656uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3657 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3658 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003659
Mathias Agopiane57f2922012-08-09 16:29:12 -07003660 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003661 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3662
3663 const uint32_t what = s.what;
3664 if (what & DisplayState::eSurfaceChanged) {
3665 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3666 state.surface = s.surface;
3667 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003668 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003669 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003670 if (what & DisplayState::eLayerStackChanged) {
3671 if (state.layerStack != s.layerStack) {
3672 state.layerStack = s.layerStack;
3673 flags |= eDisplayTransactionNeeded;
3674 }
3675 }
3676 if (what & DisplayState::eDisplayProjectionChanged) {
3677 if (state.orientation != s.orientation) {
3678 state.orientation = s.orientation;
3679 flags |= eDisplayTransactionNeeded;
3680 }
3681 if (state.frame != s.frame) {
3682 state.frame = s.frame;
3683 flags |= eDisplayTransactionNeeded;
3684 }
3685 if (state.viewport != s.viewport) {
3686 state.viewport = s.viewport;
3687 flags |= eDisplayTransactionNeeded;
3688 }
3689 }
3690 if (what & DisplayState::eDisplaySizeChanged) {
3691 if (state.width != s.width) {
3692 state.width = s.width;
3693 flags |= eDisplayTransactionNeeded;
3694 }
3695 if (state.height != s.height) {
3696 state.height = s.height;
3697 flags |= eDisplayTransactionNeeded;
3698 }
3699 }
3700
Mathias Agopiane57f2922012-08-09 16:29:12 -07003701 return flags;
3702}
3703
Robert Carr14167e02019-02-13 13:50:55 -08003704bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003705 IPCThreadState* ipc = IPCThreadState::self();
3706 const int pid = ipc->getCallingPid();
3707 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003708 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003709 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003710 return false;
3711 }
3712 return true;
3713}
3714
Robert Carr14167e02019-02-13 13:50:55 -08003715uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3716 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003717 const layer_state_t& s = composerState.state;
3718 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3719
Mathias Agopian13127d82013-03-05 17:47:11 -08003720 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003721 if (layer == nullptr) {
3722 return 0;
3723 }
3724
chaviw8b3871a2017-11-01 17:41:01 -07003725 uint32_t flags = 0;
3726
Garfield Tan8a3083e2018-12-03 13:21:07 -08003727 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003728 bool geometryAppliesWithResize =
3729 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003730
3731 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3732 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003733 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003734 layer->pushPendingState();
3735 }
3736
chaviw8b3871a2017-11-01 17:41:01 -07003737 if (what & layer_state_t::ePositionChanged) {
3738 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3739 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003740 }
chaviw8b3871a2017-11-01 17:41:01 -07003741 }
3742 if (what & layer_state_t::eLayerChanged) {
3743 // NOTE: index needs to be calculated before we update the state
3744 const auto& p = layer->getParent();
3745 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003746 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003747 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003748 mCurrentState.layersSortedByZ.removeAt(idx);
3749 mCurrentState.layersSortedByZ.add(layer);
3750 // we need traversal (state changed)
3751 // AND transaction (list changed)
3752 flags |= eTransactionNeeded|eTraversalNeeded;
3753 }
chaviw8b3871a2017-11-01 17:41:01 -07003754 } else {
3755 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003756 flags |= eTransactionNeeded|eTraversalNeeded;
3757 }
3758 }
chaviw8b3871a2017-11-01 17:41:01 -07003759 }
3760 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003761 // NOTE: index needs to be calculated before we update the state
3762 const auto& p = layer->getParent();
3763 if (p == nullptr) {
3764 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3765 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3766 mCurrentState.layersSortedByZ.removeAt(idx);
3767 mCurrentState.layersSortedByZ.add(layer);
3768 // we need traversal (state changed)
3769 // AND transaction (list changed)
3770 flags |= eTransactionNeeded|eTraversalNeeded;
3771 }
3772 } else {
3773 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3774 flags |= eTransactionNeeded|eTraversalNeeded;
3775 }
chaviw8b3871a2017-11-01 17:41:01 -07003776 }
3777 }
3778 if (what & layer_state_t::eSizeChanged) {
3779 if (layer->setSize(s.w, s.h)) {
3780 flags |= eTraversalNeeded;
3781 }
3782 }
3783 if (what & layer_state_t::eAlphaChanged) {
3784 if (layer->setAlpha(s.alpha))
3785 flags |= eTraversalNeeded;
3786 }
3787 if (what & layer_state_t::eColorChanged) {
3788 if (layer->setColor(s.color))
3789 flags |= eTraversalNeeded;
3790 }
Peiyong Lind3788632018-09-18 16:01:31 -07003791 if (what & layer_state_t::eColorTransformChanged) {
3792 if (layer->setColorTransform(s.colorTransform)) {
3793 flags |= eTraversalNeeded;
3794 }
3795 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003796 if (what & layer_state_t::eBackgroundColorChanged) {
3797 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3798 flags |= eTraversalNeeded;
3799 }
3800 }
chaviw8b3871a2017-11-01 17:41:01 -07003801 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003802 // TODO: b/109894387
3803 //
3804 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3805 // rotation. To see the problem observe that if we have a square parent, and a child
3806 // of the same size, then we rotate the child 45 degrees around it's center, the child
3807 // must now be cropped to a non rectangular 8 sided region.
3808 //
3809 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3810 // private API, and the WindowManager only uses rotation in one case, which is on a top
3811 // level layer in which cropping is not an issue.
3812 //
3813 // However given that abuse of rotation matrices could lead to surfaces extending outside
3814 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3815 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3816 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003817 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003818 flags |= eTraversalNeeded;
3819 }
3820 if (what & layer_state_t::eTransparentRegionChanged) {
3821 if (layer->setTransparentRegionHint(s.transparentRegion))
3822 flags |= eTraversalNeeded;
3823 }
3824 if (what & layer_state_t::eFlagsChanged) {
3825 if (layer->setFlags(s.flags, s.mask))
3826 flags |= eTraversalNeeded;
3827 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003828 if (what & layer_state_t::eCropChanged_legacy) {
3829 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003830 flags |= eTraversalNeeded;
3831 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003832 if (what & layer_state_t::eCornerRadiusChanged) {
3833 if (layer->setCornerRadius(s.cornerRadius))
3834 flags |= eTraversalNeeded;
3835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (what & layer_state_t::eLayerStackChanged) {
3837 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3838 // We only allow setting layer stacks for top level layers,
3839 // everything else inherits layer stack from its parent.
3840 if (layer->hasParent()) {
3841 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3842 layer->getName().string());
3843 } else if (idx < 0) {
3844 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3845 "that also does not appear in the top level layer list. Something"
3846 " has gone wrong.", layer->getName().string());
3847 } else if (layer->setLayerStack(s.layerStack)) {
3848 mCurrentState.layersSortedByZ.removeAt(idx);
3849 mCurrentState.layersSortedByZ.add(layer);
3850 // we need traversal (state changed)
3851 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003852 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003853 }
3854 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003855 if (what & layer_state_t::eDeferTransaction_legacy) {
3856 if (s.barrierHandle_legacy != nullptr) {
3857 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3858 } else if (s.barrierGbp_legacy != nullptr) {
3859 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003860 if (authenticateSurfaceTextureLocked(gbp)) {
3861 const auto& otherLayer =
3862 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003863 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003864 } else {
3865 ALOGE("Attempt to defer transaction to to an"
3866 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003867 }
3868 }
chaviw8b3871a2017-11-01 17:41:01 -07003869 // We don't trigger a traversal here because if no other state is
3870 // changed, we don't want this to cause any more work
3871 }
3872 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003873 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003874 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003875 if (!hadParent) {
3876 mCurrentState.layersSortedByZ.remove(layer);
3877 }
chaviw8b3871a2017-11-01 17:41:01 -07003878 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003879 }
chaviw8b3871a2017-11-01 17:41:01 -07003880 }
3881 if (what & layer_state_t::eReparentChildren) {
3882 if (layer->reparentChildren(s.reparentHandle)) {
3883 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003884 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003885 }
chaviw8b3871a2017-11-01 17:41:01 -07003886 if (what & layer_state_t::eDetachChildren) {
3887 layer->detachChildren();
3888 }
3889 if (what & layer_state_t::eOverrideScalingModeChanged) {
3890 layer->setOverrideScalingMode(s.overrideScalingMode);
3891 // We don't trigger a traversal here because if no other state is
3892 // changed, we don't want this to cause any more work
3893 }
Marissa Wall61c58622018-07-18 10:12:20 -07003894 if (what & layer_state_t::eTransformChanged) {
3895 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3896 }
3897 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3898 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3899 flags |= eTraversalNeeded;
3900 }
3901 if (what & layer_state_t::eCropChanged) {
3902 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3903 }
Marissa Wall861616d2018-10-22 12:52:23 -07003904 if (what & layer_state_t::eFrameChanged) {
3905 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3906 }
Marissa Wall61c58622018-07-18 10:12:20 -07003907 if (what & layer_state_t::eAcquireFenceChanged) {
3908 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3909 }
3910 if (what & layer_state_t::eDataspaceChanged) {
3911 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3912 }
3913 if (what & layer_state_t::eHdrMetadataChanged) {
3914 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3915 }
3916 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3917 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eApiChanged) {
3920 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3921 }
3922 if (what & layer_state_t::eSidebandStreamChanged) {
3923 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3924 }
Robert Carr720e5062018-07-30 17:45:14 -07003925 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003926 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3927 layer->setInputInfo(s.inputInfo);
3928 flags |= eTraversalNeeded;
3929 } else {
3930 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3931 }
Robert Carr720e5062018-07-30 17:45:14 -07003932 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003933 if (what & layer_state_t::eMetadataChanged) {
3934 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3935 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003936 std::vector<sp<CallbackHandle>> callbackHandles;
3937 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3938 mTransactionCompletedThread.run();
3939 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3940 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3941 }
3942 }
Marissa Wall73411622019-01-25 10:45:41 -08003943
3944 if (what & layer_state_t::eBufferChanged) {
3945 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3946 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3947 s.buffer);
3948 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003949 if (what & layer_state_t::eCachedBufferChanged) {
3950 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003951 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3952 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003953 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3954 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003955 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3956 // Do not put anything that updates layer state or modifies flags after
3957 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003958 return flags;
3959}
3960
chaviw273171b2018-12-26 11:46:30 -08003961uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3962 uint32_t flags = 0;
3963 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3964 flags |= eTraversalNeeded;
3965 }
3966
chaviwa911b102019-02-14 10:18:33 -08003967 if (inputWindowCommands.syncInputWindows) {
3968 flags |= eTraversalNeeded;
3969 }
3970
Vishnu Nairec0ab382019-02-13 15:32:56 -08003971 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003972 return flags;
3973}
3974
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003975status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3976 uint32_t h, PixelFormat format, uint32_t flags,
3977 LayerMetadata metadata, sp<IBinder>* handle,
3978 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003979 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003980 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003981 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003982 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003983 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003984
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003985 status_t result = NO_ERROR;
3986
3987 sp<Layer> layer;
3988
Cody Northropbc755282017-03-31 12:00:08 -06003989 String8 uniqueName = getUniqueLayerName(name);
3990
Mathias Agopian3165cc22012-08-08 19:42:09 -07003991 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003992 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003993 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3994 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003995
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003997 case ISurfaceComposerClient::eFXSurfaceBufferState:
3998 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3999 break;
chaviw13fdc492017-06-27 12:40:18 -07004000 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004001 // check if buffer size is set for color layer.
4002 if (w > 0 || h > 0) {
4003 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4004 int(w), int(h));
4005 return BAD_VALUE;
4006 }
4007
chaviw13fdc492017-06-27 12:40:18 -07004008 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004009 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004010 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004012 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004013 // check if buffer size is set for container layer.
4014 if (w > 0 || h > 0) {
4015 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4016 int(w), int(h));
4017 return BAD_VALUE;
4018 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004019 result = createContainerLayer(client,
4020 uniqueName, w, h, flags,
4021 handle, &layer);
4022 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004023 default:
4024 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 break;
4026 }
4027
Dan Stoza7d89d062015-04-30 13:29:25 -07004028 if (result != NO_ERROR) {
4029 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004030 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004031
Chia-I Wuab0c3192017-08-01 11:29:00 -07004032 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4033 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004034 if (metadata.has(METADATA_WINDOW_TYPE)) {
4035 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4036 if (windowType == 441731) {
4037 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4038 layer->setPrimaryDisplayOnly();
4039 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004040 }
4041
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004042 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004043
Robert Carrb89ea9d2018-12-10 13:01:14 -08004044 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4045 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4046 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004047 if (result != NO_ERROR) {
4048 return result;
4049 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004050 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004051
4052 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004053 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054}
4055
Cody Northropbc755282017-03-31 12:00:08 -06004056String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4057{
4058 bool matchFound = true;
4059 uint32_t dupeCounter = 0;
4060
4061 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4062 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4063
Dan Stoza436ccf32018-06-21 12:10:12 -07004064 // Grab the state lock since we're accessing mCurrentState
4065 Mutex::Autolock lock(mStateLock);
4066
Cody Northropbc755282017-03-31 12:00:08 -06004067 // Loop over layers until we're sure there is no matching name
4068 while (matchFound) {
4069 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004070 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004071 if (layer->getName() == uniqueName) {
4072 matchFound = true;
4073 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4074 }
4075 });
4076 }
4077
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004078 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4079 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004080
4081 return uniqueName;
4082}
4083
Marissa Wallfd668622018-05-10 10:21:13 -07004084status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4085 uint32_t w, uint32_t h, uint32_t flags,
4086 PixelFormat& format, sp<IBinder>* handle,
4087 sp<IGraphicBufferProducer>* gbp,
4088 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004090 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 case PIXEL_FORMAT_TRANSPARENT:
4092 case PIXEL_FORMAT_TRANSLUCENT:
4093 format = PIXEL_FORMAT_RGBA_8888;
4094 break;
4095 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004096 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097 break;
4098 }
4099
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004100 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004101 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004102 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004103 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004104 *handle = layer->getHandle();
4105 *gbp = layer->getProducer();
4106 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004108
Marissa Wallfd668622018-05-10 10:21:13 -07004109 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004110 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111}
4112
Marissa Wall61c58622018-07-18 10:12:20 -07004113status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4114 uint32_t w, uint32_t h, uint32_t flags,
4115 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004116 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004117 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004118 *handle = layer->getHandle();
4119 *outLayer = layer;
4120
4121 return NO_ERROR;
4122}
4123
chaviw13fdc492017-06-27 12:40:18 -07004124status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004125 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004126 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004128 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004130 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004131}
4132
Robert Carr6b3f6c52018-08-13 13:05:17 -07004133status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4134 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4135 sp<IBinder>* handle, sp<Layer>* outLayer)
4136{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004137 *outLayer =
4138 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004139 *handle = (*outLayer)->getHandle();
4140 return NO_ERROR;
4141}
4142
4143
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004144void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004145 mLayersPendingRemoval.add(layer);
4146 mLayersRemoved = true;
4147 setTransactionFlags(eTransactionNeeded);
4148}
4149
Robert Carr695d5282018-12-18 15:27:58 -08004150void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004151{
Robert Carr2e102c92018-10-23 12:11:15 -07004152 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004153 // If a layer has a parent, we allow it to out-live it's handle
4154 // with the idea that the parent holds a reference and will eventually
4155 // be cleaned up. However no one cleans up the top-level so we do so
4156 // here.
4157 if (layer->getParent() == nullptr) {
4158 mCurrentState.layersSortedByZ.remove(layer);
4159 }
4160 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004161 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004162}
4163
Mathias Agopianb60314a2012-04-10 22:09:54 -07004164// ---------------------------------------------------------------------------
4165
Andy McFadden13a082e2012-08-24 10:16:42 -07004166void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004167 const auto display = getDefaultDisplayDeviceLocked();
4168 if (!display) return;
4169
4170 const sp<IBinder> token = display->getDisplayToken().promote();
4171 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004172
Jesse Hall01e29052013-02-19 16:13:35 -08004173 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004174 Vector<ComposerState> state;
4175 Vector<DisplayState> displays;
4176 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004177 d.what = DisplayState::eDisplayProjectionChanged |
4178 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004179 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004180 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004181 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004182 d.frame.makeInvalid();
4183 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004184 d.width = 0;
4185 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004186 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004187 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004188
Dominik Laskowskie9774092018-12-11 10:04:24 -08004189 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004190
Dominik Laskowski83b88212018-12-11 13:34:06 -08004191 const nsecs_t vsyncPeriod = getVsyncPeriod();
4192 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004193
Brian Andersond0010582017-03-07 13:20:31 -08004194 // Use phase of 0 since phase is not known.
4195 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004196 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004197 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004198}
4199
4200void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004201 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004202 postMessageAsync(
4203 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004204}
4205
Dominik Laskowskie9774092018-12-11 10:04:24 -08004206void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207 if (display->isVirtual()) {
4208 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004209 return;
4210 }
4211
Dominik Laskowski075d3172018-05-24 15:50:06 -07004212 const auto displayId = display->getId();
4213 LOG_ALWAYS_FATAL_IF(!displayId);
4214
Dominik Laskowski34157762018-10-31 13:07:19 -07004215 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004216
4217 int currentMode = display->getPowerMode();
4218 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004219 return;
4220 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004222 display->setPowerMode(mode);
4223
Lloyd Pique4dccc412018-01-22 17:21:36 -08004224 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004225 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004226 }
4227
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004228 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004229 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004230 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004231 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004232 mScheduler->onScreenAcquired(mAppConnectionHandle);
4233 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004234 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004236 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004237 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004238 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004239
4240 struct sched_param param = {0};
4241 param.sched_priority = 1;
4242 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4243 ALOGW("Couldn't set SCHED_FIFO on display on");
4244 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004245 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004246 // Turn off the display
4247 struct sched_param param = {0};
4248 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4249 ALOGW("Couldn't set SCHED_OTHER on display off");
4250 }
4251
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004253 mScheduler->disableHardwareVsync(true);
4254 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004255 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004256
Dominik Laskowski075d3172018-05-24 15:50:06 -07004257 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004258 mVisibleRegionsDirty = true;
4259 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004260 } else if (mode == HWC_POWER_MODE_DOZE ||
4261 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004262 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004263 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004264 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004265 mScheduler->onScreenAcquired(mAppConnectionHandle);
4266 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004267 }
4268 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4269 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004270 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004271 mScheduler->disableHardwareVsync(true);
4272 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004273 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004275 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004276 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004278 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004280 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004281 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004282 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004283 // Update refresh rate stats.
4284 mRefreshRateStats->setPowerMode(mode);
4285 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004286 }
4287
Dominik Laskowski34157762018-10-31 13:07:19 -07004288 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004289}
4290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004292 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 const auto display = getDisplayDevice(displayToken);
4294 if (!display) {
4295 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4296 displayToken.get());
4297 } else if (display->isVirtual()) {
4298 ALOGW("Attempt to set power mode %d for virtual display", mode);
4299 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004300 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004301 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004302 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004303}
4304
4305// ---------------------------------------------------------------------------
4306
Dominik Laskowskic2867142019-01-21 11:33:38 -08004307status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4308 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004310
Mathias Agopianbd115332013-04-18 16:41:04 -07004311 IPCThreadState* ipc = IPCThreadState::self();
4312 const int pid = ipc->getCallingPid();
4313 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004314
Mathias Agopianbd115332013-04-18 16:41:04 -07004315 if ((uid != AID_SHELL) &&
4316 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004317 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4318 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004319 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004320 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004321 // (this would indicate SF is stuck, but we want to be able to
4322 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004323 status_t err = mStateLock.timedLock(s2ns(1));
4324 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004325 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004326 StringAppendF(&result,
4327 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4328 "(no locks held)\n",
4329 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004330 }
4331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004333
Dominik Laskowskic2867142019-01-21 11:33:38 -08004334 static const std::unordered_map<std::string, Dumper> dumpers = {
4335 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4336 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4337 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004338 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004339 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004340 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004341 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4342 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004343 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4344 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4345 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4346 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4347 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4348 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004349 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004350 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4351 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004352
Dominik Laskowskic2867142019-01-21 11:33:38 -08004353 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004354
Dominik Laskowskic2867142019-01-21 11:33:38 -08004355 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4356 (it->second)(args, asProto, result);
4357 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004358 if (asProto) {
4359 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4360 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4361 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004362 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004363 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004364 }
4365
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 if (locked) {
4367 mStateLock.unlock();
4368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004369 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004370 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 return NO_ERROR;
4372}
4373
Dominik Laskowskic2867142019-01-21 11:33:38 -08004374void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 mCurrentState.traverseInZOrder(
4376 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377}
4378
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004380 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004381
Dominik Laskowskic2867142019-01-21 11:33:38 -08004382 if (args.size() > 1) {
4383 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004384 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004385 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004386 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004387 }
Robert Carr2047fae2016-11-28 14:09:09 -08004388 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389 } else {
4390 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391 }
4392}
4393
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004395 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004396 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004397 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004398 }
Robert Carr2047fae2016-11-28 14:09:09 -08004399 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004400
Svetoslavd85084b2014-03-20 10:28:31 -07004401 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004402}
4403
Dominik Laskowskic2867142019-01-21 11:33:38 -08004404void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4405 mTimeStats->parseArgs(asProto, args, result);
4406}
4407
Jamie Gennis6547ff42013-07-16 20:12:42 -07004408// This should only be called from the main thread. Otherwise it would need
4409// the lock and should use mCurrentState rather than mDrawingState.
4410void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004411 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004412 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004413 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004414
4415 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4416}
4417
Yiwei Zhang5434a782018-12-05 18:06:32 -08004418void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004419 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004420
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004421 if (isLayerTripleBufferingDisabled())
4422 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004423
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4425 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4426 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4427 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4428 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4429 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004430 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004431}
4432
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004433void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004434 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004435 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004436 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004437 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004438
Ana Krulecba13ab32019-02-20 14:14:12 -08004439 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4440 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4441 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004442 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004443}
4444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4446 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004447 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4448 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004449 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004450 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004452 }
David Sodman4a36e932017-11-07 14:29:47 -08004453 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004454 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004455 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004456 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4457 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004458}
4459
Dan Stozae77c7662016-05-13 11:37:28 -07004460void SurfaceFlinger::recordBufferingStats(const char* layerName,
4461 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004462 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4463 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004464 for (const auto& segment : history) {
4465 if (!segment.usedThirdBuffer) {
4466 stats.twoBufferTime += segment.totalTime;
4467 }
4468 if (segment.occupancyAverage < 1.0f) {
4469 stats.doubleBufferedTime += segment.totalTime;
4470 } else if (segment.occupancyAverage < 2.0f) {
4471 stats.tripleBufferedTime += segment.totalTime;
4472 }
4473 ++stats.numSegments;
4474 stats.totalTime += segment.totalTime;
4475 }
4476}
4477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4479 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004480
4481 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4482 const size_t count = currentLayers.size();
4483 for (size_t i=0 ; i<count ; i++) {
4484 currentLayers[i]->dumpFrameEvents(result);
4485 }
4486}
4487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004489 result.append("Buffering stats:\n");
4490 result.append(" [Layer name] <Active time> <Two buffer> "
4491 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004492 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004493 typedef std::tuple<std::string, float, float, float> BufferTuple;
4494 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004495 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004496 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004497 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004498 if (stats.numSegments == 0) {
4499 continue;
4500 }
4501 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4502 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4503 stats.totalTime;
4504 float doubleBufferRatio = static_cast<float>(
4505 stats.doubleBufferedTime) / stats.totalTime;
4506 float tripleBufferRatio = static_cast<float>(
4507 stats.tripleBufferedTime) / stats.totalTime;
4508 sorted.insert({activeTime, {name, twoBufferRatio,
4509 doubleBufferRatio, tripleBufferRatio}});
4510 }
4511 for (const auto& sortedPair : sorted) {
4512 float activeTime = sortedPair.first;
4513 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4515 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004516 }
4517 result.append("\n");
4518}
4519
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004521 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004522 const auto displayId = display->getId();
4523 if (!displayId) {
4524 continue;
4525 }
4526 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004527 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004528 continue;
4529 }
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531 StringAppendF(&result,
4532 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4533 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004534 uint8_t port;
4535 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004536 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004537 result.append("no identification data\n");
4538 continue;
4539 }
4540
4541 if (!isEdid(data)) {
4542 result.append("unknown identification data: ");
4543 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004545 }
4546 result.append("\n");
4547 continue;
4548 }
4549
4550 const auto edid = parseEdid(data);
4551 if (!edid) {
4552 result.append("invalid EDID: ");
4553 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004555 }
4556 result.append("\n");
4557 continue;
4558 }
4559
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 result.append(edid->displayName.data(), edid->displayName.length());
4562 result.append("\"\n");
4563 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564}
4565
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4567 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4568 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4569 StringAppendF(&result, "DisplayColorSetting: %s\n",
4570 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004571
4572 // TODO: print out if wide-color mode is active or not
4573
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004575 const auto displayId = display->getId();
4576 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004577 continue;
4578 }
4579
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004581 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004582 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004584 }
4585
Lloyd Pique32cbe282018-10-19 13:09:22 -07004586 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result, " Current color mode: %s (%d)\n",
4588 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004589 }
4590 result.append("\n");
4591}
4592
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004593LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004594 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004595 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4596 const State& state = useDrawing ? mDrawingState : mCurrentState;
4597 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004598 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004599 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004600 });
4601
4602 return layersProto;
4603}
4604
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004605LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4606 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004607 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004608
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004609 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004610 resolution->set_w(displayDevice->getWidth());
4611 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004612
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004613 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004614 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004615
Lloyd Pique32cbe282018-10-19 13:09:22 -07004616 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4617 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4618 layersProto.set_global_transform(displayState.orientation);
4619
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004620 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004621 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004622 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004623 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004624 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004625 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004626 }
4627 });
4628
4629 return layersProto;
4630}
4631
Dominik Laskowskic2867142019-01-21 11:33:38 -08004632void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4633 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 Colorizer colorizer(colorize);
4635
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004636 // figure out if we're stuck somewhere
4637 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004639 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4640
4641 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004642 * Dump library configuration.
4643 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004644
4645 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004646 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004647 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004648 appendSfConfigString(result);
4649 appendUiConfigString(result);
4650 appendGuiConfigString(result);
4651 result.append("\n");
4652
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004653 result.append("\nDisplay identification data:\n");
4654 dumpDisplayIdentificationData(result);
4655
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004656 result.append("\nWide-Color information:\n");
4657 dumpWideColorInfo(result);
4658
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004660 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004662 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004663 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004664
Andy McFadden41d67d72014-04-25 16:58:34 -07004665 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004666 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004667 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004668 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004669 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004670
Dan Stozab90cf072015-03-05 11:05:59 -08004671 dumpStaticScreenStats(result);
4672 result.append("\n");
4673
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004675
Dan Stozae77c7662016-05-13 11:37:28 -07004676 dumpBufferingStats(result);
4677
Andy McFadden4803b742012-09-24 19:07:20 -07004678 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 * Dump the visible layer list
4680 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004681 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4683 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4684 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004685 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004686
Chia-I Wu2f884132018-09-13 15:17:58 -07004687 {
4688 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4689 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004690 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004691 result.append("\n");
4692 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693
4694 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004695 * Dump Display state
4696 */
4697
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004701 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004702 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004703 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004704 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004705
4706 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004707 * Dump SurfaceFlinger global state
4708 */
4709
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004710 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004711 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004714 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715
Dominik Laskowski075d3172018-05-24 15:50:06 -07004716 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004717 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4718 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4720 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004721 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result,
4723 " transaction-flags : %08x\n"
4724 " gpu_to_cpu_unsupported : %d\n",
4725 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004726
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004727 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004728 displayId && getHwComposer().isConnected(*displayId)) {
4729 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result,
4731 " refresh-rate : %f fps\n"
4732 " x-dpi : %f\n"
4733 " y-dpi : %f\n",
4734 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4735 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004736 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739
Dan Stozae22aec72016-08-01 13:20:59 -07004740 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004741 * Tracing state
4742 */
4743 mTracing.dump(result);
4744 result.append("\n");
4745
4746 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004747 * HWC layer minidump
4748 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004749 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004750 const auto displayId = display->getId();
4751 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004752 continue;
4753 }
4754
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004756 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004757 const sp<DisplayDevice> displayDevice = display;
4758 mCurrentState.traverseInZOrder(
4759 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004760 result.append("\n");
4761 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762
4763 /*
4764 * Dump HWComposer state
4765 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004767 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004769 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004771 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772
4773 /*
4774 * Dump gralloc state
4775 */
4776 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4777 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004778
4779 /*
4780 * Dump VrFlinger state if in use.
4781 */
4782 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4783 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004785 result.append("\n");
4786 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004787
4788 /**
4789 * Scheduler dump state.
4790 */
Ana Krulecc2870422019-01-29 19:00:58 -08004791 result.append("\nScheduler state:\n");
4792 result.append(mScheduler->doDump() + "\n");
4793 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794}
4795
Dominik Laskowski075d3172018-05-24 15:50:06 -07004796const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004797 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004798 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004799 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004800 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004801 }
4802 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004803
Dominik Laskowski34157762018-10-31 13:07:19 -07004804 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004805 static const Vector<sp<Layer>> empty;
4806 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004807}
4808
Chia-I Wu28f320b2018-05-03 11:02:56 -07004809void SurfaceFlinger::updateColorMatrixLocked() {
4810 mat4 colorMatrix;
4811 if (mGlobalSaturationFactor != 1.0f) {
4812 // Rec.709 luma coefficients
4813 float3 luminance{0.213f, 0.715f, 0.072f};
4814 luminance *= 1.0f - mGlobalSaturationFactor;
4815 mat4 saturationMatrix = mat4(
4816 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4817 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4818 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4819 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4820 );
4821 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4822 } else {
4823 colorMatrix = mClientColorMatrix * mDaltonizer();
4824 }
4825
4826 if (mCurrentState.colorMatrix != colorMatrix) {
4827 mCurrentState.colorMatrix = colorMatrix;
4828 mCurrentState.colorMatrixChanged = true;
4829 setTransactionFlags(eTransactionNeeded);
4830 }
4831}
4832
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004833status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004834#pragma clang diagnostic push
4835#pragma clang diagnostic error "-Wswitch-enum"
4836 switch (static_cast<ISurfaceComposerTag>(code)) {
4837 // These methods should at minimum make sure that the client requested
4838 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004839 case BOOT_FINISHED:
4840 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 case CREATE_DISPLAY:
4842 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004843 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844 case GET_ACTIVE_COLOR_MODE:
4845 case GET_ANIMATION_FRAME_STATS:
4846 case GET_HDR_CAPABILITIES:
4847 case SET_ACTIVE_CONFIG:
4848 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004849 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004850 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004851 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004852 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4853 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004854 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4855 IPCThreadState* ipc = IPCThreadState::self();
4856 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4857 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004858 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 }
Robert Carr1db73f62016-12-21 12:58:51 -08004860 return OK;
4861 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004863 IPCThreadState* ipc = IPCThreadState::self();
4864 const int pid = ipc->getCallingPid();
4865 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4867 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004868 return PERMISSION_DENIED;
4869 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004871 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004872 // Used by apps to hook Choreographer to SurfaceFlinger.
4873 case CREATE_DISPLAY_EVENT_CONNECTION:
4874 // The following calls are currently used by clients that do not
4875 // request necessary permissions. However, they do not expose any secret
4876 // information, so it is OK to pass them.
4877 case AUTHENTICATE_SURFACE:
4878 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004879 case GET_PHYSICAL_DISPLAY_IDS:
4880 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004882 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 case GET_DISPLAY_CONFIGS:
4884 case GET_DISPLAY_STATS:
4885 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4886 // Calling setTransactionState is safe, because you need to have been
4887 // granted a reference to Client* and Handle* to do anything with it.
4888 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004889 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004890 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004891 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004892 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004893 case IS_WIDE_COLOR_DISPLAY:
4894 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004895 return OK;
4896 }
4897 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004898 case CAPTURE_SCREEN:
4899 case ADD_REGION_SAMPLING_LISTENER:
4900 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004902 IPCThreadState* ipc = IPCThreadState::self();
4903 const int pid = ipc->getCallingPid();
4904 const int uid = ipc->getCallingUid();
4905 if ((uid != AID_GRAPHICS) &&
4906 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4907 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4908 return PERMISSION_DENIED;
4909 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 return OK;
4911 }
4912 // The following codes are deprecated and should never be allowed to access SF.
4913 case CONNECT_DISPLAY_UNUSED:
4914 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4915 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4916 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919
4920 // These codes are used for the IBinder protocol to either interrogate the recipient
4921 // side of the transaction for its canonical interface descriptor or to dump its state.
4922 // We let them pass by default.
4923 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4924 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4925 code == IBinder::SYSPROPS_TRANSACTION) {
4926 return OK;
4927 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004928 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004930 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4932 return OK;
4933 }
4934 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4935 return PERMISSION_DENIED;
4936#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004937}
4938
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4940 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004941 status_t credentialCheck = CheckTransactCodeCredentials(code);
4942 if (credentialCheck != OK) {
4943 return credentialCheck;
4944 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004945
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004946 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4947 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004948 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004949 IPCThreadState* ipc = IPCThreadState::self();
4950 const int uid = ipc->getCallingUid();
4951 if (CC_UNLIKELY(uid != AID_SYSTEM
4952 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004953 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004954 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004955 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 return PERMISSION_DENIED;
4957 }
4958 int n;
4959 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004960 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004961 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004962 return NO_ERROR;
4963 case 1002: // SHOW_UPDATES
4964 n = data.readInt32();
4965 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004966 invalidateHwcGeometry();
4967 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004968 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004969 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004970 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004971 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004972 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004973 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004974 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004975 setTransactionFlags(
4976 eTransactionNeeded|
4977 eDisplayTransactionNeeded|
4978 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004979 return NO_ERROR;
4980 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004981 case 1006:{ // send empty update
4982 signalRefresh();
4983 return NO_ERROR;
4984 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004985 case 1008: // toggle use of hw composer
4986 n = data.readInt32();
4987 mDebugDisableHWC = n ? 1 : 0;
4988 invalidateHwcGeometry();
4989 repaintEverything();
4990 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004991 case 1009: // toggle use of transform hint
4992 n = data.readInt32();
4993 mDebugDisableTransformHint = n ? 1 : 0;
4994 invalidateHwcGeometry();
4995 repaintEverything();
4996 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004998 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 reply->writeInt32(0);
5000 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005001 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005002 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return NO_ERROR;
5004 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005005 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005006 if (!display) {
5007 return NAME_NOT_FOUND;
5008 }
5009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005010 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005011 return NO_ERROR;
5012 }
5013 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005014 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005015 // daltonize
5016 n = data.readInt32();
5017 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005018 case 1:
5019 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5020 break;
5021 case 2:
5022 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5023 break;
5024 case 3:
5025 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5026 break;
5027 default:
5028 mDaltonizer.setType(ColorBlindnessType::None);
5029 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005030 }
5031 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005032 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005033 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005034 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005035 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005036
5037 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005038 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005040 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005041 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005042 // apply a color matrix
5043 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005044 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005045 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005046 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005047 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005048 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005049 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005051 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005052 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005053 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005054
5055 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5056 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005058 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5059 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5060 }
5061
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 return NO_ERROR;
5064 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005065 // This is an experimental interface
5066 // Needs to be shifted to proper binder interface when we productize
5067 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005068 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005069 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005070 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005071 return NO_ERROR;
5072 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005073 case 1017: {
5074 n = data.readInt32();
5075 mForceFullDamage = static_cast<bool>(n);
5076 return NO_ERROR;
5077 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005078 case 1018: { // Modify Choreographer's phase offset
5079 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005080 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005081 return NO_ERROR;
5082 }
5083 case 1019: { // Modify SurfaceFlinger's phase offset
5084 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005085 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005086 return NO_ERROR;
5087 }
Irvel468051e2016-06-13 16:44:44 -07005088 case 1020: { // Layer updates interceptor
5089 n = data.readInt32();
5090 if (n) {
5091 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005092 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005093 }
5094 else{
5095 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005096 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005097 }
5098 return NO_ERROR;
5099 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005100 case 1021: { // Disable HWC virtual displays
5101 n = data.readInt32();
5102 mUseHwcVirtualDisplays = !n;
5103 return NO_ERROR;
5104 }
Romain Guy0147a172017-06-01 13:53:56 -07005105 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005106 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005107 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005108
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005110 return NO_ERROR;
5111 }
Romain Guy54f154a2017-10-24 21:40:32 +01005112 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005113 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005114 invalidateHwcGeometry();
5115 repaintEverything();
5116 return NO_ERROR;
5117 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005118 // Deprecate, use 1030 to check whether the device is color managed.
5119 case 1024: {
5120 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005121 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005122 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005123 n = data.readInt32();
5124 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005125 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005126 mTracing.enable();
5127 doTracing("tracing.enable");
5128 reply->writeInt32(NO_ERROR);
5129 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005130 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005131 status_t err = mTracing.disable();
5132 reply->writeInt32(err);
5133 }
5134 return NO_ERROR;
5135 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005136 case 1026: { // Get layer tracing status
5137 reply->writeBool(mTracing.isEnabled());
5138 return NO_ERROR;
5139 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005140 // Is a DisplayColorSetting supported?
5141 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005142 const auto display = getDefaultDisplayDevice();
5143 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005144 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005145 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005146
5147 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5148 switch (setting) {
5149 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005150 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005151 break;
5152 case DisplayColorSetting::UNMANAGED:
5153 reply->writeBool(true);
5154 break;
5155 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005156 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005157 break;
5158 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 reply->writeBool(
5160 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005161 break;
5162 }
5163 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005164 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005165 // Is VrFlinger active?
5166 case 1028: {
5167 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005168 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005169 return NO_ERROR;
5170 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005171 // Is device color managed?
5172 case 1030: {
5173 reply->writeBool(useColorManagement);
5174 return NO_ERROR;
5175 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005176 // Override default composition data space
5177 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5178 // && adb shell stop zygote && adb shell start zygote
5179 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5180 // adb shell stop zygote && adb shell start zygote
5181 case 1031: {
5182 Mutex::Autolock _l(mStateLock);
5183 n = data.readInt32();
5184 if (n) {
5185 n = data.readInt32();
5186 if (n) {
5187 Dataspace dataspace = static_cast<Dataspace>(n);
5188 if (!validateCompositionDataspace(dataspace)) {
5189 return BAD_VALUE;
5190 }
5191 mDefaultCompositionDataspace = dataspace;
5192 }
5193 n = data.readInt32();
5194 if (n) {
5195 Dataspace dataspace = static_cast<Dataspace>(n);
5196 if (!validateCompositionDataspace(dataspace)) {
5197 return BAD_VALUE;
5198 }
5199 mWideColorGamutCompositionDataspace = dataspace;
5200 }
5201 } else {
5202 // restore composition data space.
5203 mDefaultCompositionDataspace = defaultCompositionDataspace;
5204 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5205 }
5206 return NO_ERROR;
5207 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005208 }
5209 }
5210 return err;
5211}
5212
Steven Thomas6d8110b2017-08-31 18:24:21 -07005213void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005214 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005215 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005216}
5217
Ana Krulec7d1d6832018-12-27 11:10:09 -08005218void SurfaceFlinger::repaintEverythingForHWC() {
5219 mRepaintEverything = true;
5220 mEventQueue->invalidateForHWC();
5221}
5222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005223// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5224class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005225public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005226 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5227 ~WindowDisconnector() {
5228 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005229 }
5230
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005231private:
5232 ANativeWindow* mWindow;
5233 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005234};
5235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005236status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005237 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5238 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005239 uint32_t reqWidth, uint32_t reqHeight,
5240 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005241 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005242 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005245
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005246 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5247
Chia-I Wu20261cb2018-08-23 12:55:44 -07005248 sp<DisplayDevice> display;
5249 {
5250 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005251
Chia-I Wu20261cb2018-08-23 12:55:44 -07005252 display = getDisplayDeviceLocked(displayToken);
5253 if (!display) return BAD_VALUE;
5254
Chia-I Wucb023152018-08-28 12:57:23 -07005255 // set the requested width/height to the logical display viewport size
5256 // by default
5257 if (reqWidth == 0 || reqHeight == 0) {
5258 reqWidth = uint32_t(display->getViewport().width());
5259 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005260 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005261 }
5262
Peiyong Lin0e003c92018-09-17 11:09:51 -07005263 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5264 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005265
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005266 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5267 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005268 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5269 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005270}
5271
5272status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005273 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5274 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005275 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005276 ATRACE_CALL();
5277
5278 class LayerRenderArea : public RenderArea {
5279 public:
Robert Carr578038f2018-03-09 12:25:24 -08005280 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005281 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5282 bool childrenOnly)
5283 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005284 mLayer(layer),
5285 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005286 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005287 mFlinger(flinger),
5288 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005289 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005290 Rect getBounds() const override {
5291 const Layer::State& layerState(mLayer->getDrawingState());
5292 return mLayer->getBufferSize(layerState);
5293 }
Marissa Wall61c58622018-07-18 10:12:20 -07005294 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005295 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005296 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005297 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005298 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005299 }
chaviwa76b2712017-09-20 12:02:26 -07005300 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005301 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005302 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005303 Rect getSourceCrop() const override {
5304 if (mCrop.isEmpty()) {
5305 return getBounds();
5306 } else {
5307 return mCrop;
5308 }
5309 }
Robert Carr578038f2018-03-09 12:25:24 -08005310 class ReparentForDrawing {
5311 public:
5312 const sp<Layer>& oldParent;
5313 const sp<Layer>& newParent;
5314
Vishnu Nair4351ad52019-02-11 14:13:02 -08005315 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5316 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005317 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005318 // Compute and cache the bounds for the new parent layer.
5319 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005320 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005321 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005322 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005323 };
5324
5325 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005326 const Rect sourceCrop = getSourceCrop();
5327 // no need to check rotation because there is none
5328 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5329 sourceCrop.height() != getReqHeight();
5330
Robert Carr578038f2018-03-09 12:25:24 -08005331 if (!mChildrenOnly) {
5332 mTransform = mLayer->getTransform().inverse();
5333 drawLayers();
5334 } else {
5335 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005336 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005337 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5338 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005339
Vishnu Nair4351ad52019-02-11 14:13:02 -08005340 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005341 drawLayers();
5342 }
5343 }
chaviwa76b2712017-09-20 12:02:26 -07005344
chaviwa76b2712017-09-20 12:02:26 -07005345 private:
chaviw7206d492017-11-10 16:16:12 -08005346 const sp<Layer> mLayer;
5347 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005348
5349 // In the "childrenOnly" case we reparent the children to a screenshot
5350 // layer which has no properties set and which does not draw.
5351 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005352 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005353 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005354
5355 SurfaceFlinger* mFlinger;
5356 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005357 };
5358
5359 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5360 auto parent = layerHandle->owner.promote();
5361
Robert Carr2e102c92018-10-23 12:11:15 -07005362 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005363 ALOGE("captureLayers called with a removed parent");
5364 return NAME_NOT_FOUND;
5365 }
5366
Robert Carr578038f2018-03-09 12:25:24 -08005367 const int uid = IPCThreadState::self()->getCallingUid();
5368 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005369 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005370 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5371 return PERMISSION_DENIED;
5372 }
5373
chaviw7206d492017-11-10 16:16:12 -08005374 Rect crop(sourceCrop);
5375 if (sourceCrop.width() <= 0) {
5376 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005377 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005378 }
5379
5380 if (sourceCrop.height() <= 0) {
5381 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005382 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005383 }
5384
5385 int32_t reqWidth = crop.width() * frameScale;
5386 int32_t reqHeight = crop.height() * frameScale;
5387
Chia-I Wu20261cb2018-08-23 12:55:44 -07005388 // really small crop or frameScale
5389 if (reqWidth <= 0) {
5390 reqWidth = 1;
5391 }
5392 if (reqHeight <= 0) {
5393 reqHeight = 1;
5394 }
5395
Peiyong Lin0e003c92018-09-17 11:09:51 -07005396 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005397
Robert Carr578038f2018-03-09 12:25:24 -08005398 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005399 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5400 if (!layer->isVisible()) {
5401 return;
Robert Carr578038f2018-03-09 12:25:24 -08005402 } else if (childrenOnly && layer == parent.get()) {
5403 return;
chaviwa76b2712017-09-20 12:02:26 -07005404 }
5405 visitor(layer);
5406 });
5407 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005408 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005409}
5410
5411status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5412 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005413 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005415 bool useIdentityTransform) {
5416 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005417
Peiyong Lin0e003c92018-09-17 11:09:51 -07005418 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005419 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5420 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005421 *outBuffer =
5422 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5423 static_cast<android_pixel_format>(reqPixelFormat), 1,
5424 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005425
5426 // This mutex protects syncFd and captureResult for communication of the return values from the
5427 // main thread back to this Binder thread
5428 std::mutex captureMutex;
5429 std::condition_variable captureCondition;
5430 std::unique_lock<std::mutex> captureLock(captureMutex);
5431 int syncFd = -1;
5432 std::optional<status_t> captureResult;
5433
Robert Carr03480e22018-01-04 16:02:06 -08005434 const int uid = IPCThreadState::self()->getCallingUid();
5435 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5436
Dominik Laskowski8c001672018-05-30 16:52:06 -07005437 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005438 // If there is a refresh pending, bug out early and tell the binder thread to try again
5439 // after the refresh.
5440 if (mRefreshPending) {
5441 ATRACE_NAME("Skipping screenshot for now");
5442 std::unique_lock<std::mutex> captureLock(captureMutex);
5443 captureResult = std::make_optional<status_t>(EAGAIN);
5444 captureCondition.notify_one();
5445 return;
5446 }
5447
5448 status_t result = NO_ERROR;
5449 int fd = -1;
5450 {
5451 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005452 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005453 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5454 useIdentityTransform, forSystem, &fd);
5455 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005456 }
5457
5458 {
5459 std::unique_lock<std::mutex> captureLock(captureMutex);
5460 syncFd = fd;
5461 captureResult = std::make_optional<status_t>(result);
5462 captureCondition.notify_one();
5463 }
5464 });
5465
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005466 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005467 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005468 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005469 while (*captureResult == EAGAIN) {
5470 captureResult.reset();
5471 result = postMessageAsync(message);
5472 if (result != NO_ERROR) {
5473 return result;
5474 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005475 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005476 }
5477 result = *captureResult;
5478 }
5479
5480 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005481 sync_wait(syncFd, -1);
5482 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005484
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005486}
5487
chaviwa76b2712017-09-20 12:02:26 -07005488void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005489 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5491 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005492 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005493
chaviwa76b2712017-09-20 12:02:26 -07005494 const auto reqWidth = renderArea.getReqWidth();
5495 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005496 const auto sourceCrop = renderArea.getSourceCrop();
5497 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005498
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005499 renderengine::DisplaySettings clientCompositionDisplay;
5500 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005501
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005502 // assume that bounds are never offset, and that they are the same as the
5503 // buffer bounds.
5504 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5505 ui::Transform transform = renderArea.getTransform();
5506 mat4 m;
5507 m[0][0] = transform[0][0];
5508 m[0][1] = transform[0][1];
5509 m[0][3] = transform[0][2];
5510 m[1][0] = transform[1][0];
5511 m[1][1] = transform[1][1];
5512 m[1][3] = transform[1][2];
5513 m[3][0] = transform[2][0];
5514 m[3][1] = transform[2][1];
5515 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005516
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005517 clientCompositionDisplay.globalTransform = m;
5518 mat4 rotMatrix;
5519 // Displacement for repositioning the clipping rectangle after rotating it
5520 // with the rotation hint.
5521 int displacementX = 0;
5522 int displacementY = 0;
5523 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5524 switch (rotation) {
5525 case ui::Transform::ROT_90:
5526 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5527 displacementX = reqWidth;
5528 break;
5529 case ui::Transform::ROT_180:
5530 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5531 displacementX = reqWidth;
5532 displacementY = reqHeight;
5533 break;
5534 case ui::Transform::ROT_270:
5535 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5536 displacementY = reqHeight;
5537 break;
5538 default:
5539 break;
5540 }
5541 // We need to transform the clipping window into the right spot.
5542 // First, rotate the clipping rectangle by the rotation hint to get the
5543 // right orientation
5544 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5545 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5546 const vec4 rotClipTL = rotMatrix * clipTL;
5547 const vec4 rotClipBR = rotMatrix * clipBR;
5548 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5549 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5550 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5551 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5552
5553 // Now reposition the clipping rectangle with the displacement vector
5554 // computed above.
5555 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5556
5557 clientCompositionDisplay.clip =
5558 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5559 newClipRight + displacementX, newClipBottom + displacementY);
5560
5561 // We need to perform the same transformation in layer space, so propagate
5562 // it to the global transform.
5563 mat4 clipTransform = displacementMat * rotMatrix;
5564 clientCompositionDisplay.globalTransform *= clipTransform;
5565 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5566 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005567
chaviw50da5042018-04-09 13:49:37 -07005568 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005569
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005570 renderengine::LayerSettings fillLayer;
5571 fillLayer.source.buffer.buffer = nullptr;
5572 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5573 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5574 fillLayer.alpha = half(alpha);
5575 clientCompositionLayers.push_back(fillLayer);
5576
5577 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005578 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005579 renderengine::LayerSettings layerSettings;
5580 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5581 layerSettings);
5582 if (prepared) {
5583 clientCompositionLayers.push_back(layerSettings);
5584 }
chaviwa76b2712017-09-20 12:02:26 -07005585 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005586
5587 clientCompositionDisplay.clearRegion = clearRegion;
5588 base::unique_fd drawFence;
5589 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5590 &drawFence);
5591
5592 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005593}
5594
chaviwa76b2712017-09-20 12:02:26 -07005595status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5596 TraverseLayersFunction traverseLayers,
5597 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005598 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005599 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005600 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005601 ATRACE_CALL();
5602
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005603 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005604
5605 traverseLayers([&](Layer* layer) {
5606 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5607 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005608
Robert Carr03480e22018-01-04 16:02:06 -08005609 // We allow the system server to take screenshots of secure layers for
5610 // use in situations like the Screen-rotation animation and place
5611 // the impetus on WindowManager to not persist them.
5612 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005613 ALOGW("FB is protected: PERMISSION_DENIED");
5614 return PERMISSION_DENIED;
5615 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005616 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005617 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005618}
5619
chaviw5f21a5e2019-02-14 10:00:34 -08005620void SurfaceFlinger::setInputWindowsFinished() {}
5621
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005622// ---------------------------------------------------------------------------
5623
Dan Stoza412903f2017-04-27 13:42:17 -07005624void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5625 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005626}
5627
Dan Stoza412903f2017-04-27 13:42:17 -07005628void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5629 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005630}
5631
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005632void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005633 const LayerVector::Visitor& visitor) {
5634 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005635 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005636 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005637 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005638 continue;
5639 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005640 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005641 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005642 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005643 return;
5644 }
chaviwa76b2712017-09-20 12:02:26 -07005645 if (!layer->isVisible()) {
5646 return;
5647 }
5648 visitor(layer);
5649 });
5650 }
5651}
5652
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005653}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005654
Lloyd Pique074e8122018-07-26 12:57:23 -07005655
Mathias Agopian3f844832013-08-07 21:24:32 -07005656#if defined(__gl_h_)
5657#error "don't include gl/gl.h in this file"
5658#endif
5659
5660#if defined(__gl2_h_)
5661#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005662#endif