blob: 59b0e05abfe6c6866cbf5e92cb617f36cf1805b6 [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 Mouri79108df2019-02-04 19:33:44 +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 Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080081#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700112#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800113#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900114#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
chaviw1d044282017-09-27 12:19:28 -0700116#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900117#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120
Jaesoo Lee43518572017-01-23 19:03:16 +0900121using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Steven Thomasb02664d2017-07-26 18:48:28 -0700131namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700132
133#pragma clang diagnostic push
134#pragma clang diagnostic error "-Wswitch-enum"
135
136bool isWideColorMode(const ColorMode colorMode) {
137 switch (colorMode) {
138 case ColorMode::DISPLAY_P3:
139 case ColorMode::ADOBE_RGB:
140 case ColorMode::DCI_P3:
141 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700142 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700143 case ColorMode::BT2100_PQ:
144 case ColorMode::BT2100_HLG:
145 return true;
146 case ColorMode::NATIVE:
147 case ColorMode::STANDARD_BT601_625:
148 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
149 case ColorMode::STANDARD_BT601_525:
150 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
151 case ColorMode::STANDARD_BT709:
152 case ColorMode::SRGB:
153 return false;
154 }
155 return false;
156}
157
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700158ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
159 switch (rotation) {
160 case ISurfaceComposer::eRotateNone:
161 return ui::Transform::ROT_0;
162 case ISurfaceComposer::eRotate90:
163 return ui::Transform::ROT_90;
164 case ISurfaceComposer::eRotate180:
165 return ui::Transform::ROT_180;
166 case ISurfaceComposer::eRotate270:
167 return ui::Transform::ROT_270;
168 }
169 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
170 return ui::Transform::ROT_0;
171}
172
Peiyong Linfca547f2018-07-09 13:03:33 -0700173#pragma clang diagnostic pop
174
Steven Thomasb02664d2017-07-26 18:48:28 -0700175class ConditionalLock {
176public:
177 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
178 if (lock) {
179 mMutex.lock();
180 }
181 }
182 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
183private:
184 Mutex& mMutex;
185 bool mLocked;
186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Peiyong Lin9d846a52018-11-05 13:18:20 -0800188// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
189bool validateCompositionDataspace(Dataspace dataspace) {
190 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
191}
192
Steven Thomasb02664d2017-07-26 18:48:28 -0700193} // namespace anonymous
194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195// ---------------------------------------------------------------------------
196
Mathias Agopian99b49842011-06-27 16:05:52 -0700197const String16 sHardwareTest("android.permission.HARDWARE_TEST");
198const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
199const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
200const String16 sDump("android.permission.DUMP");
201
Daniel Solomon42d04562019-01-20 21:03:19 -0800202constexpr float kSrgbRedX = 0.4123f;
203constexpr float kSrgbRedY = 0.2126f;
204constexpr float kSrgbRedZ = 0.0193f;
205constexpr float kSrgbGreenX = 0.3576f;
206constexpr float kSrgbGreenY = 0.7152f;
207constexpr float kSrgbGreenZ = 0.1192f;
208constexpr float kSrgbBlueX = 0.1805f;
209constexpr float kSrgbBlueY = 0.0722f;
210constexpr float kSrgbBlueZ = 0.9506f;
211constexpr float kSrgbWhiteX = 0.9505f;
212constexpr float kSrgbWhiteY = 1.0000f;
213constexpr float kSrgbWhiteZ = 1.0891f;
214
Mathias Agopian99b49842011-06-27 16:05:52 -0700215// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700216int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700217bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800220bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800221int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700223int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700230
Kalle Raitaa099a242017-01-11 11:17:29 -0800231std::string getHwcServiceName() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.hwc_service_name", value, "default");
234 ALOGI("Using HWComposer service: '%s'", value);
235 return std::string(value);
236}
237
238bool useTrebleTestingOverride() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.treble_testing_override", value, "false");
241 ALOGI("Treble testing override: '%s'", value);
242 return std::string(value) == "true";
243}
244
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
246 switch(displayColorSetting) {
247 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Enhanced");
253 default:
254 return std::string("Unknown ") +
255 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257}
258
David Sodmanbc815282017-11-05 18:57:52 -0800259SurfaceFlingerBE::SurfaceFlingerBE()
260 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800261 mFrameBuckets(),
262 mTotalTime(0),
263 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800264 mComposerSequenceId(0) {
265}
266
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
268 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800269 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700271 mTransactionPending(false),
272 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700273 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700274 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800276 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800278 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800279 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800280 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700282 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700283 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700284 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700285 mDebugInTransaction(0),
286 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700287 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800288 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700289 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700290 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800291 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800292 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700294 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700295 mMainThreadId(std::this_thread::get_id()),
296 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800297
Lloyd Pique90c115d2018-09-18 21:39:42 -0700298SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
299 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800300 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800309
Steven Thomas050b2c82017-03-06 11:45:16 -0800310 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 mDefaultCompositionDataspace =
320 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
321 mWideColorGamutCompositionDataspace =
322 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
323 defaultCompositionDataspace = mDefaultCompositionDataspace;
324 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
325 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
326 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
327 wideColorGamutCompositionPixelFormat =
328 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
333 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
334 switch (tmpPrimaryDisplayOrientation) {
335 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800349
Lloyd Pique90c115d2018-09-18 21:39:42 -0700350 mPrimaryDispSync =
351 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
352 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 property_get("debug.sf.ddms", value, "0");
374 mDebugDDMS = atoi(value);
375 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700376 if (!startDdmConnection()) {
377 // start failed, and DDMS debugging not enabled
378 mDebugDDMS = 0;
379 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700381 ALOGI_IF(mDebugRegion, "showupdates enabled");
382 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800392 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Ana Krulec757f63a2019-01-25 10:46:18 -0800403 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
404 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700405
Romain Guy11d63f42017-07-20 12:47:14 -0700406 // We should be reading 'persist.sys.sf.color_saturation' here
407 // but since /data may be encrypted, we need to wait until after vold
408 // comes online to attempt to read the property. The property is
409 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800410
411 if (useTrebleTestingOverride()) {
412 // Without the override SurfaceFlinger cannot connect to HIDL
413 // services that are not listed in the manifests. Considered
414 // deriving the setting from the set service name, but it
415 // would be brittle if the name that's not 'default' is used
416 // for production purposes later on.
417 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419}
420
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421void SurfaceFlinger::onFirstRef()
422{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800423 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426SurfaceFlinger::~SurfaceFlinger()
427{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Dan Stozac7014012014-02-14 15:03:43 -0800430void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431{
432 // the window manager died on us. prepare its eulogy.
433
Andy McFadden13a082e2012-08-24 10:16:42 -0700434 // restore initial conditions (default device unblank, etc)
435 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436
437 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700438 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439}
440
Robert Carr1db73f62016-12-21 12:58:51 -0800441static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700442 status_t err = client->initCheck();
443 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 }
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return nullptr;
447}
448
449sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
450 return initClient(new Client(this));
451}
452
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
454 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455{
456 class DisplayToken : public BBinder {
457 sp<SurfaceFlinger> flinger;
458 virtual ~DisplayToken() {
459 // no more references, this display must be terminated
460 Mutex::Autolock _l(flinger->mStateLock);
461 flinger->mCurrentState.displays.removeItem(this);
462 flinger->setTransactionFlags(eDisplayTransactionNeeded);
463 }
464 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700465 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 : flinger(flinger) {
467 }
468 };
469
470 sp<BBinder> token = new DisplayToken(this);
471
472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 // Display ID is assigned when virtual display is allocated by HWC.
474 DisplayDeviceState state;
475 state.isSecure = secure;
476 state.displayName = displayName;
477 mCurrentState.displays.add(token, state);
478 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 return token;
480}
481
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700482void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 Mutex::Autolock _l(mStateLock);
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
486 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
492 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 ALOGE("destroyDisplay called for non-virtual display");
494 return;
495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 mInterceptor->saveDisplayDeletion(state.sequenceId);
497 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 setTransactionFlags(eDisplayTransactionNeeded);
499}
500
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 std::optional<DisplayId> displayId;
503
504 if (id == HWC_DISPLAY_PRIMARY) {
505 displayId = getInternalDisplayId();
506 } else if (id == HWC_DISPLAY_EXTERNAL) {
507 displayId = getExternalDisplayId();
508 }
509
510 if (!displayId) {
511 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800512 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
515 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516}
517
Ady Abraham37965d42018-11-01 13:43:32 -0700518status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
519 if (!outGetColorManagement) {
520 return BAD_VALUE;
521 }
522 *outGetColorManagement = useColorManagement;
523 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700524}
525
Lloyd Pique441d5042018-10-18 16:49:51 -0700526HWComposer& SurfaceFlinger::getHwComposer() const {
527 return mCompositionEngine->getHwComposer();
528}
529
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700530renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
531 return mCompositionEngine->getRenderEngine();
532}
533
Lloyd Pique70d91362018-10-18 16:02:55 -0700534compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
535 return *mCompositionEngine.get();
536}
537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538void SurfaceFlinger::bootFinished()
539{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700540 if (mStartPropertySetThread->join() != NO_ERROR) {
541 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 const nsecs_t now = systemTime();
544 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000545 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
547 // wait patiently for the window manager death
548 const String16 name("window");
549 sp<IBinder> window(defaultServiceManager()->getService(name));
550 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700551 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552 }
Robert Carr720e5062018-07-30 17:45:14 -0700553 sp<IBinder> input(defaultServiceManager()->getService(
554 String16("inputflinger")));
555 if (input == nullptr) {
556 ALOGE("Failed to link to input service");
557 } else {
558 mInputFlinger = interface_cast<IInputFlinger>(input);
559 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560
Steven Thomas050b2c82017-03-06 11:45:16 -0800561 if (mVrFlinger) {
562 mVrFlinger->OnBootFinished();
563 }
564
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700566 // formerly we would just kill the process, but we now ask it to exit so it
567 // can choose where to stop the animation.
568 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700569
570 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
571 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
572 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700573
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800574 postMessageAsync(new LambdaMessage([this] {
575 readPersistentProperties();
576 mBootStage = BootStage::FINISHED;
577 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578}
579
Dan Stoza436ccf32018-06-21 12:10:12 -0700580uint32_t SurfaceFlinger::getNewTexture() {
581 {
582 std::lock_guard lock(mTexturePoolMutex);
583 if (!mTexturePool.empty()) {
584 uint32_t name = mTexturePool.back();
585 mTexturePool.pop_back();
586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
587 return name;
588 }
589
590 // The pool was too small, so increase it for the future
591 ++mTexturePoolSize;
592 }
593
594 // The pool was empty, so we need to get a new texture name directly using a
595 // blocking call to the main thread
596 uint32_t name = 0;
597 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
598 return name;
599}
600
Mathias Agopian3f844832013-08-07 21:24:32 -0700601void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700603}
604
Wei Wangf9b05ee2017-07-19 20:59:39 -0700605// Do not call property_set on main thread which will be blocked by init
606// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700608 ALOGI( "SurfaceFlinger's main thread ready to run. "
609 "Initializing graphics H/W...");
610
Ana Krulec757f63a2019-01-25 10:46:18 -0800611 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614
Dominik Laskowski83b88212018-12-11 13:34:06 -0800615 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700618 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700619 mScheduler = getFactory().createScheduler([this](bool enabled) {
620 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
621 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
623 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
624 mPhaseOffsets->setRefreshRateType(
625 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800628 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800629 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800632 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800633 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800636
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700638 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
639 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 } else {
641 mEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800643 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mEventThread =
645 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 impl::EventThread::InterceptVSyncsCallback(),
647 "appEventThread");
648 mSfEventThreadSource =
649 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800650 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700651
652 mSFEventThread =
653 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700654 [this](nsecs_t timestamp) {
655 mInterceptor->saveVSyncEvent(timestamp);
656 },
657 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800658 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
660 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661
Steven Thomasb02664d2017-07-26 18:48:28 -0700662 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700663 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700664 renderEngineFeature |= (useColorManagement ?
665 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700666 renderEngineFeature |= (useContextPriority ?
667 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700668
669 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700670 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700671 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700676 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
677 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800678 // Process any initial hotplug and resulting display changes.
679 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 const auto display = getDefaultDisplayDeviceLocked();
681 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 // This callback is called from the vr flinger dispatch thread. We
688 // need to call signalTransaction(), which requires holding
689 // mStateLock when we're not on the main thread. Acquiring
690 // mStateLock from the vr flinger dispatch thread might trigger a
691 // deadlock in surface flinger (see b/66916578), so post a message
692 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
695 mVrFlingerRequestsDisplay = requestDisplay;
696 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700699 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
700 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700701 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 .value_or(0),
703 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 if (!mVrFlinger) {
705 ALOGE("Failed to start vrflinger");
706 }
707 }
708
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700710 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700711
Mathias Agopian92a979a2012-08-02 18:32:23 -0700712 // initialize our drawing state
713 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700714
Andy McFadden13a082e2012-08-24 10:16:42 -0700715 // set initial conditions (e.g. unblank default device)
716 initializeDisplays();
717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700719
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700721
722 const bool presentFenceReliable =
723 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
724 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725
726 if (mStartPropertySetThread->Start() != NO_ERROR) {
727 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800731 mScheduler->setExpiredIdleTimerCallback([this]() {
732 mPhaseOffsets->setRefreshRateType(
733 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
734 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
735 mVsyncModulator.setPhaseOffsets(early, gl, late);
736 setRefreshRateTo(60.f /* fps */);
737 });
738 mScheduler->setResetIdleTimerCallback([this]() {
739 mPhaseOffsets->setRefreshRateType(
740 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
741 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
742 mVsyncModulator.setPhaseOffsets(early, gl, late);
743 setRefreshRateTo(90.f /* fps */);
744 });
Alec Mourifb571ea2019-01-24 18:42:10 -0800745 mRefreshRateStats =
746 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
747 *display->getId()),
748 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800749 }
750
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700752}
753
Romain Guy11d63f42017-07-20 12:47:14 -0700754void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 Mutex::Autolock _l(mStateLock);
756
Romain Guy11d63f42017-07-20 12:47:14 -0700757 char value[PROPERTY_VALUE_MAX];
758
759 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700761 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800762 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100763
764 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700765 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700766}
767
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800769 // Start boot animation service by setting a property mailbox
770 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800772 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700773 if (mStartPropertySetThread->join() != NO_ERROR) {
774 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800775 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700783 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800786// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800787
Jamie Gennis582270d2011-08-17 18:19:00 -0700788bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800790 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800791 return authenticateSurfaceTextureLocked(bufferProducer);
792}
793
794bool SurfaceFlinger::authenticateSurfaceTextureLocked(
795 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800796 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800797 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800798}
799
Brian Anderson6b376712017-04-04 10:51:39 -0700800status_t SurfaceFlinger::getSupportedFrameTimestamps(
801 std::vector<FrameEvent>* outSupported) const {
802 *outSupported = {
803 FrameEvent::REQUESTED_PRESENT,
804 FrameEvent::ACQUIRE,
805 FrameEvent::LATCH,
806 FrameEvent::FIRST_REFRESH_START,
807 FrameEvent::LAST_REFRESH_START,
808 FrameEvent::GPU_COMPOSITION_DONE,
809 FrameEvent::DEQUEUE_READY,
810 FrameEvent::RELEASE,
811 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700812 ConditionalLock _l(mStateLock,
813 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700814 if (!getHwComposer().hasCapability(
815 HWC2::Capability::PresentFenceIsNotReliable)) {
816 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
817 }
818 return NO_ERROR;
819}
820
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700821status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
822 Vector<DisplayInfo>* configs) {
823 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 return BAD_VALUE;
825 }
826
Dominik Laskowski075d3172018-05-24 15:50:06 -0700827 const auto displayId = getPhysicalDisplayId(displayToken);
828 if (!displayId) {
829 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700830 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 // TODO: Not sure if display density should handled by SF any longer
833 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700836 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800837 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 }
840 return density;
841 }
842 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 return getDensityFromProperty("ro.sf.lcd_density"); }
847 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Steven Thomas6d8110b2017-08-31 18:24:21 -0700851 ConditionalLock _l(mStateLock,
852 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700853 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 DisplayInfo info = DisplayInfo();
855
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 float xdpi = hwConfig->getDpiX();
857 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859 info.w = hwConfig->getWidth();
860 info.h = hwConfig->getHeight();
861 // Default display viewport to display width and height
862 info.viewportW = info.w;
863 info.viewportH = info.h;
864
Dominik Laskowski075d3172018-05-24 15:50:06 -0700865 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 // The density of the device is provided by a build property
867 float density = Density::getBuildDensity() / 160.0f;
868 if (density == 0) {
869 // the build doesn't provide a density -- this is wrong!
870 // use xdpi instead
871 ALOGE("ro.sf.lcd_density must be defined as a build property");
872 density = xdpi / 160.0f;
873 }
874 if (Density::getEmuDensity()) {
875 // if "qemu.sf.lcd_density" is specified, it overrides everything
876 xdpi = ydpi = density = Density::getEmuDensity();
877 density /= 160.0f;
878 }
879 info.density = density;
880
881 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700882 const auto display = getDefaultDisplayDeviceLocked();
883 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700884
885 // This is for screenrecord
886 const Rect viewport = display->getViewport();
887 if (viewport.isValid()) {
888 info.viewportW = uint32_t(viewport.getWidth());
889 info.viewportH = uint32_t(viewport.getHeight());
890 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700891 } else {
892 // TODO: where should this value come from?
893 static const int TV_DENSITY = 213;
894 info.density = TV_DENSITY / 160.0f;
895 info.orientation = 0;
896 }
897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 info.xdpi = xdpi;
899 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800901 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902
Andy McFadden91b2ca82014-06-13 14:04:23 -0700903 // This is how far in advance a buffer must be queued for
904 // presentation at a given time. If you want a buffer to appear
905 // on the screen at time N, you must submit the buffer before
906 // (N - presentationDeadline).
907 //
908 // Normally it's one full refresh period (to give SF a chance to
909 // latch the buffer), but this can be reduced by configuring a
910 // DispSync offset. Any additional delays introduced by the hardware
911 // composer or panel must be accounted for here.
912 //
913 // We add an additional 1ms to allow for processing time and
914 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800915 info.presentationDeadline =
916 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700917
918 // All non-virtual displays are currently considered secure.
919 info.secure = true;
920
Dominik Laskowski075d3172018-05-24 15:50:06 -0700921 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700922 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800923 std::swap(info.w, info.h);
924 }
925
Michael Wright28f24d02016-07-12 13:30:53 -0700926 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700927 }
928
Dan Stoza7f7da322014-05-02 15:26:25 -0700929 return NO_ERROR;
930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
933 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 return BAD_VALUE;
935 }
936
Ana Krulece588e312018-09-18 12:32:24 -0700937 if (mUseScheduler) {
938 mScheduler->getDisplayStatInfo(stats);
939 } else {
940 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
941 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
942 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700943 return NO_ERROR;
944}
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
947 const auto display = getDisplayDevice(displayToken);
948 if (!display) {
949 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800950 return BAD_VALUE;
951 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700952
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700954}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700955
Ana Krulec7d1d6832018-12-27 11:10:09 -0800956status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
957 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800958 postMessageAsync(new LambdaMessage(
959 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960 return NO_ERROR;
961}
962
963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800965 postMessageSync(new LambdaMessage(
966 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967 return NO_ERROR;
968}
969
970void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
975 return;
976 }
977
978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 return;
983 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800985 ALOGW("Attempt to set active config %d for virtual display", mode);
986 return;
987 }
988 int currentDisplayPowerMode = display->getPowerMode();
989 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
990 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 return;
992 }
993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800996 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997 return;
998 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800999 if (mUseScheduler) {
1000 mRefreshRateStats->setConfigMode(mode);
1001 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Dominik Laskowski075d3172018-05-24 15:50:06 -07001003 const auto displayId = display->getId();
1004 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008
Ana Krulec7d1d6832018-12-27 11:10:09 -08001009 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001010 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1014 Vector<ColorMode>* outColorModes) {
1015 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 return BAD_VALUE;
1017 }
1018
Dominik Laskowski075d3172018-05-24 15:50:06 -07001019 const auto displayId = getPhysicalDisplayId(displayToken);
1020 if (!displayId) {
1021 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001022 }
1023
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001025 {
1026 ConditionalLock _l(mStateLock,
1027 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001029 }
Michael Wright28f24d02016-07-12 13:30:53 -07001030 outColorModes->clear();
1031 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1032
1033 return NO_ERROR;
1034}
1035
Daniel Solomon42d04562019-01-20 21:03:19 -08001036status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1037 ui::DisplayPrimaries &primaries) {
1038 if (!displayToken) {
1039 return BAD_VALUE;
1040 }
1041
1042 // Currently we only support this API for a single internal display.
1043 if (getInternalDisplayToken() != displayToken) {
1044 return BAD_VALUE;
1045 }
1046
1047 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001053 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001059 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 Vector<ColorMode> modes;
1061 getDisplayColorModes(displayToken, &modes);
1062 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1063 if (mode < ColorMode::NATIVE || !exists) {
1064 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001067 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 const auto display = getDisplayDevice(displayToken);
1069 if (!display) {
1070 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1071 decodeColorMode(mode).c_str(), mode, displayToken.get());
1072 } else if (display->isVirtual()) {
1073 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1074 decodeColorMode(mode).c_str(), mode);
1075 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001076 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1077 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 }
1079 }));
1080
Michael Wright28f24d02016-07-12 13:30:53 -07001081 return NO_ERROR;
1082}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001083
Svetoslavd85084b2014-03-20 10:28:31 -07001084status_t SurfaceFlinger::clearAnimationFrameStats() {
1085 Mutex::Autolock _l(mStateLock);
1086 mAnimFrameTracker.clearStats();
1087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1091 Mutex::Autolock _l(mStateLock);
1092 mAnimFrameTracker.getStats(outStats);
1093 return NO_ERROR;
1094}
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1097 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 Mutex::Autolock _l(mStateLock);
1099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100 const auto display = getDisplayDeviceLocked(displayToken);
1101 if (!display) {
1102 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001103 return BAD_VALUE;
1104 }
1105
Peiyong Linfb069302018-04-25 14:34:31 -07001106 // At this point the DisplayDeivce should already be set up,
1107 // meaning the luminance information is already queried from
1108 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001110 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1111 capabilities.getDesiredMaxLuminance(),
1112 capabilities.getDesiredMaxAverageLuminance(),
1113 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001114
1115 return NO_ERROR;
1116}
1117
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001118status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1119 ui::PixelFormat* outFormat,
1120 ui::Dataspace* outDataspace,
1121 uint8_t* outComponentMask) const {
1122 if (!outFormat || !outDataspace || !outComponentMask) {
1123 return BAD_VALUE;
1124 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001125 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001126 if (!display || !display->getId()) {
1127 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1128 return BAD_VALUE;
1129 }
1130 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1131 outDataspace, outComponentMask);
1132}
1133
Kevin DuBois74e53772018-11-19 10:52:38 -08001134status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1135 bool enable, uint8_t componentMask,
1136 uint64_t maxFrames) const {
1137 const auto display = getDisplayDevice(displayToken);
1138 if (!display || !display->getId()) {
1139 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1140 return BAD_VALUE;
1141 }
1142
1143 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1144 componentMask, maxFrames);
1145}
1146
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001147status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1148 uint64_t maxFrames, uint64_t timestamp,
1149 DisplayedFrameStats* outStats) const {
1150 const auto display = getDisplayDevice(displayToken);
1151 if (!display || !display->getId()) {
1152 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1153 return BAD_VALUE;
1154 }
1155
1156 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1157 outStats);
1158}
1159
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001160status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1161 if (!outSupported) {
1162 return BAD_VALUE;
1163 }
1164 *outSupported = getRenderEngine().supportsProtectedContent();
1165 return NO_ERROR;
1166}
1167
Marissa Wallebc2c052019-01-16 19:16:55 -08001168status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1169 int32_t* outBufferId) {
1170 if (!outBufferId) {
1171 return BAD_VALUE;
1172 }
1173 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1174 return NO_ERROR;
1175}
1176
1177status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1178 mBufferStateLayerCache.release(token, bufferId);
1179 return NO_ERROR;
1180}
1181
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001182status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1183 bool* outIsWideColorDisplay) const {
1184 if (!displayToken || !outIsWideColorDisplay) {
1185 return BAD_VALUE;
1186 }
1187 Mutex::Autolock _l(mStateLock);
1188 const auto display = getDisplayDeviceLocked(displayToken);
1189 if (!display) {
1190 return BAD_VALUE;
1191 }
1192 *outIsWideColorDisplay = display->hasWideColorGamut();
1193 return NO_ERROR;
1194}
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001197 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 if (mInjectVSyncs == enable) {
1201 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203
Dominik Laskowski83b88212018-12-11 13:34:06 -08001204 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001205
Ana Krulec98b5b242018-08-10 15:03:23 -07001206 // TODO(akrulec): Part of the Injector should be refactored, so that it
1207 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 if (enable) {
1209 ALOGV("VSync Injections enabled");
1210 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001211 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001212 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001213 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001214 impl::EventThread::InterceptVSyncsCallback(),
1215 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001217 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218 } else {
1219 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001220 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 }
1222
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001223 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001224 }));
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226 return NO_ERROR;
1227}
1228
1229status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 Mutex::Autolock _l(mStateLock);
1231
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232 if (!mInjectVSyncs) {
1233 ALOGE("VSync Injections not enabled");
1234 return BAD_VALUE;
1235 }
1236 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1237 ALOGV("Injecting VSync inside SurfaceFlinger");
1238 mVSyncInjector->onInjectSyncEvent(when);
1239 }
1240 return NO_ERROR;
1241}
1242
Lloyd Pique755e3192018-01-31 16:46:15 -08001243status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1244 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001245 // Try to acquire a lock for 1s, fail gracefully
1246 const status_t err = mStateLock.timedLock(s2ns(1));
1247 const bool locked = (err == NO_ERROR);
1248 if (!locked) {
1249 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1250 return TIMED_OUT;
1251 }
1252
1253 outLayers->clear();
1254 mCurrentState.traverseInZOrder([&](Layer* layer) {
1255 outLayers->push_back(layer->getLayerDebugInfo());
1256 });
1257
1258 mStateLock.unlock();
1259 return NO_ERROR;
1260}
1261
Peiyong Linc6780972018-10-28 15:24:08 -07001262status_t SurfaceFlinger::getCompositionPreference(
1263 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1264 Dataspace* outWideColorGamutDataspace,
1265 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001266 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001267 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001268 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001269 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001270 return NO_ERROR;
1271}
1272
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001273// ----------------------------------------------------------------------------
1274
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001275sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1276 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001277 auto resyncCallback = makeResyncCallback([this] {
1278 Mutex::Autolock lock(mStateLock);
1279 return getVsyncPeriod();
1280 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001281
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 if (mUseScheduler) {
1283 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001288 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001289 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001290 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001291 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001292 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001293 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001294 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001295}
1296
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001297// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298
1299void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001300 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301}
1302
1303void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001304 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001305}
1306
1307void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001308 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001309}
1310
1311void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001312 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001313 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314}
1315
1316status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001317 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001318 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001319}
1320
1321status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001322 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324 if (res == NO_ERROR) {
1325 msg->wait();
1326 }
1327 return res;
1328}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001329
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001330void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001331 do {
1332 waitForEvent();
1333 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334}
1335
Dominik Laskowski83b88212018-12-11 13:34:06 -08001336nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1337 const auto displayId = getInternalDisplayId();
1338 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1339 return 0;
1340 }
1341
1342 const auto config = getHwComposer().getActiveConfig(*displayId);
1343 return config ? config->getVsyncPeriod() : 0;
1344}
1345
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346void SurfaceFlinger::enableHardwareVsync() {
1347 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001349 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001350 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001352 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353}
1354
Dominik Laskowski83b88212018-12-11 13:34:06 -08001355void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356 Mutex::Autolock _l(mHWVsyncLock);
1357
Jesse Hall948fe0c2013-10-14 12:56:09 -07001358 if (makeAvailable) {
1359 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001360 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1361 if (mUseScheduler) {
1362 mScheduler->makeHWSyncAvailable(true);
1363 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001364 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001365 // Hardware vsync is not currently available, so abort the resync
1366 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367 return;
1368 }
1369
Dominik Laskowski83b88212018-12-11 13:34:06 -08001370 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001371 return;
1372 }
1373
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (mUseScheduler) {
1375 mScheduler->setVsyncPeriod(period);
1376 } else {
1377 mPrimaryDispSync->reset();
1378 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379
Ana Krulece588e312018-09-18 12:32:24 -07001380 if (!mPrimaryHWVsyncEnabled) {
1381 mPrimaryDispSync->beginResync();
1382 mEventControlThread->setVsyncEnabled(true);
1383 mPrimaryHWVsyncEnabled = true;
1384 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001385 }
1386}
1387
Jesse Hall948fe0c2013-10-14 12:56:09 -07001388void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389 Mutex::Autolock _l(mHWVsyncLock);
1390 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001391 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001392 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001393 mPrimaryHWVsyncEnabled = false;
1394 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001395 if (makeUnavailable) {
1396 mHWVsyncAvailable = false;
1397 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001398}
1399
Dominik Laskowski83b88212018-12-11 13:34:06 -08001400void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001401 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001402
Dan Stoza57164302017-05-08 14:03:54 -07001403 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001404 const nsecs_t last = lastResyncTime.exchange(now);
1405
1406 if (now - last > kIgnoreDelay) {
1407 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001408 }
1409}
1410
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001411void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1412 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001413 ATRACE_NAME("SF onVsync");
1414
Steven Thomas3cfac282017-02-06 12:29:30 -08001415 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 return;
1419 }
1420
Dominik Laskowski075d3172018-05-24 15:50:06 -07001421 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001422 return;
1423 }
1424
Dominik Laskowski075d3172018-05-24 15:50:06 -07001425 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001426 // For now, we don't do anything with external display vsyncs.
1427 return;
1428 }
1429
Ana Krulece588e312018-09-18 12:32:24 -07001430 if (mUseScheduler) {
1431 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001432 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001433 bool needsHwVsync = false;
1434 { // Scope for the lock
1435 Mutex::Autolock _l(mHWVsyncLock);
1436 if (mPrimaryHWVsyncEnabled) {
1437 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1438 }
1439 }
1440
1441 if (needsHwVsync) {
1442 enableHardwareVsync();
1443 } else {
1444 disableHardwareVsync(false);
1445 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001446 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001447}
1448
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001449void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001450 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1451 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001452}
1453
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454void SurfaceFlinger::setRefreshRateTo(float newFps) {
1455 const auto displayId = getInternalDisplayId();
1456 if (!displayId || mBootStage != BootStage::FINISHED) {
1457 return;
1458 }
1459 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1460 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1461 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1462 // refresh cycle.
1463
1464 // Don't do any updating if the current fps is the same as the new one.
1465 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1466 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1467 if (currentVsyncPeriod == 0) {
1468 return;
1469 }
1470 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1471 // floating numbers.
1472 const float currentFps = 1e9 / currentVsyncPeriod;
1473 if (std::abs(currentFps - newFps) <= 1) {
1474 return;
1475 }
1476
1477 auto configs = getHwComposer().getConfigs(*displayId);
1478 for (int i = 0; i < configs.size(); i++) {
1479 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1480 if (vsyncPeriod == 0) {
1481 continue;
1482 }
1483 const float fps = 1e9 / vsyncPeriod;
1484 // TODO(b/113612090): There should be a better way at determining which config
1485 // has the right refresh rate.
1486 if (std::abs(fps - newFps) <= 1) {
1487 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1488 if (!display) return;
1489 // This is posted in async function to avoid deadlock when getDisplayDevice
1490 // requires mStateLock.
1491 setActiveConfigAsync(display, i);
1492 ATRACE_INT("FPS", newFps);
1493 }
1494 }
1495}
1496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 // Ignore events that do not have the right sequenceId.
1503 if (sequenceId != getBE().mComposerSequenceId) {
1504 return;
1505 }
1506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Only lock if we're not on the main thread. This function is normally
1508 // called on a hwbinder thread, but for the primary display it's called on
1509 // the main thread with the state lock already held, so don't attempt to
1510 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001514
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001515 if (std::this_thread::get_id() == mMainThreadId) {
1516 // Process all pending hot plug events immediately if we are on the main thread.
1517 processDisplayHotplugEventsLocked();
1518 }
1519
Lloyd Piqueba04e622017-12-14 17:11:26 -08001520 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001525 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001528 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001529}
1530
Dominik Laskowski075d3172018-05-24 15:50:06 -07001531void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001532 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001534 if (const auto displayId = getInternalDisplayId()) {
1535 getHwComposer().setVsyncEnabled(*displayId,
1536 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1537 }
Mathias Agopian86303202012-07-24 22:46:10 -07001538}
1539
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001541void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001542 if (mUseScheduler) {
1543 mScheduler->disableHardwareVsync(true);
1544 } else {
1545 disableHardwareVsync(true);
1546 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001547 // Clear the drawing state so that the logic inside of
1548 // handleTransactionLocked will fire. It will determine the delta between
1549 // mCurrentState and mDrawingState and re-apply all changes when we make the
1550 // transition.
1551 mDrawingState.displays.clear();
1552 mDisplays.clear();
1553}
1554
Steven Thomas050b2c82017-03-06 11:45:16 -08001555void SurfaceFlinger::updateVrFlinger() {
1556 if (!mVrFlinger)
1557 return;
1558 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001559 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001560 return;
1561 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562
Lloyd Pique441d5042018-10-18 16:49:51 -07001563 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 ALOGE("Vr flinger is only supported for remote hardware composer"
1565 " service connections. Ignoring request to transition to vr"
1566 " flinger.");
1567 mVrFlingerRequestsDisplay = false;
1568 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001569 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001571 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572
Steven Thomas0123ac62018-07-12 11:32:34 -07001573 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001574 LOG_ALWAYS_FATAL_IF(!display);
1575 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001576 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1577 // called below. Clear the reference now so we don't accidentally use it
1578 // later.
1579 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001580
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001583 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 // Delete the current instance before creating the new one
1587 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1588 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1589 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1590 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591
Lloyd Pique441d5042018-10-18 16:49:51 -07001592 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001593 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001594
1595 if (vrFlingerRequestsDisplay) {
1596 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001598
1599 mVisibleRegionsDirty = true;
1600 invalidateHwcGeometry();
1601
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001602 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001603 display = getDefaultDisplayDeviceLocked();
1604 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001605 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001606
Steven Thomasb02664d2017-07-26 18:48:28 -07001607 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001608 const nsecs_t vsyncPeriod = getVsyncPeriod();
1609 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001611 // The present fences returned from vr_hwc are not an accurate
1612 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001613 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001614 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1615 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001616 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001617 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001618 !hasSyncFramework);
1619 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001620
Steven Thomasb02664d2017-07-26 18:48:28 -07001621 // Use phase of 0 since phase is not known.
1622 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001623 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001624 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001625
Dominik Laskowski83b88212018-12-11 13:34:06 -08001626 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001627
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001628 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001629 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630}
1631
Mathias Agopian4fec8732012-06-29 14:12:52 -07001632void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001633 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001634 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001635 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001636 if (mUseScheduler) {
1637 // This call is made each time SF wakes up and creates a new frame.
1638 mScheduler->incrementFrameCounter();
1639 }
Dan Stoza50182882016-07-08 12:02:20 -07001640 bool frameMissed = !mHadClientComposition &&
1641 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 (mPreviousPresentFence->getSignalTime() ==
1643 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001644 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001645 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001646 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001647 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001648 if (mPropagateBackpressure) {
1649 signalLayerUpdate();
1650 break;
1651 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001652 }
Dan Stoza50182882016-07-08 12:02:20 -07001653
Steven Thomas050b2c82017-03-06 11:45:16 -08001654 // Now that we're going to make it to the handleMessageTransaction()
1655 // call below it's safe to call updateVrFlinger(), which will
1656 // potentially trigger a display handoff.
1657 updateVrFlinger();
1658
Dan Stoza6b9454d2014-11-07 16:00:59 -08001659 bool refreshNeeded = handleMessageTransaction();
1660 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001661 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001662 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001663 // Signal a refresh if a transaction modified the window state,
1664 // a new buffer was latched, or if HWC has requested a full
1665 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001666 signalRefresh();
1667 }
1668 break;
1669 }
1670 case MessageQueue::REFRESH: {
1671 handleMessageRefresh();
1672 break;
1673 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001674 }
1675}
1676
Dan Stoza6b9454d2014-11-07 16:00:59 -08001677bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001678 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001679
1680 // Apply any ready transactions in the queues if there are still transactions that have not been
1681 // applied, wake up during the next vsync period and check again
1682 bool transactionNeeded = false;
1683 if (!flushTransactionQueues()) {
1684 transactionNeeded = true;
1685 }
1686
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001688 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001689 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001690
1691 if (transactionNeeded) {
1692 setTransactionFlags(eTransactionNeeded);
1693 }
1694
1695 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001696}
1697
Mathias Agopian4fec8732012-06-29 14:12:52 -07001698void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001700
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001701 mRefreshPending = false;
1702
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001703 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001704 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001705 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001706 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 for (const auto& [token, display] : mDisplays) {
1708 beginFrame(display);
1709 prepareFrame(display);
1710 doDebugFlashRegions(display, repaintEverything);
1711 doComposition(display, repaintEverything);
1712 }
1713
Adrian Roos1e1a1282017-11-01 19:05:31 +01001714 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001715 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716
1717 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001718 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001719
Dan Stozabfbffeb2016-07-21 14:49:33 -07001720 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001721 for (const auto& [token, displayDevice] : mDisplays) {
1722 auto display = displayDevice->getCompositionDisplay();
1723 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001724 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001726 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001727
Alec Mouri86770e52018-09-24 22:40:58 +00001728 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001729 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001730 if (mHadClientComposition) {
1731 base::unique_fd flushFence(getRenderEngine().flush());
1732 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1733 getBE().flushFence = new Fence(std::move(flushFence));
1734 } else {
1735 // Cleanup for hygiene.
1736 getBE().flushFence = Fence::NO_FENCE;
1737 }
1738 }
1739
Jorim Jaggi90535212018-05-23 23:44:06 +02001740 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001741
David Sodman7e4ae112018-02-09 15:02:28 -08001742 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001743 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001744 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001745 compositionInfo.hwc.hwcLayer = nullptr;
1746 }
David Sodmanba340492018-08-05 21:51:33 -07001747 }
David Sodman7e4ae112018-02-09 15:02:28 -08001748
1749 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001751
David Sodmanfa9b2af2017-12-24 13:28:59 -08001752
1753bool SurfaceFlinger::handleMessageInvalidate() {
1754 ATRACE_CALL();
1755 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001756}
1757
David Sodman79bba0e2018-08-05 18:07:49 -07001758void SurfaceFlinger::calculateWorkingSet() {
1759 ATRACE_CALL();
1760 ALOGV(__FUNCTION__);
1761
David Sodman79bba0e2018-08-05 18:07:49 -07001762 // build the h/w work list
1763 if (CC_UNLIKELY(mGeometryInvalid)) {
1764 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001765 for (const auto& [token, displayDevice] : mDisplays) {
1766 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001767 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001768 if (!displayId) {
1769 continue;
1770 }
David Sodman79bba0e2018-08-05 18:07:49 -07001771
Lloyd Pique32cbe282018-10-19 13:09:22 -07001772 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 for (size_t i = 0; i < currentLayers.size(); i++) {
1774 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001775
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 if (!layer->hasHwcLayer(*displayId)) {
1777 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1778 layer->forceClientComposition(*displayId);
1779 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001780 }
1781 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782
Lloyd Pique32cbe282018-10-19 13:09:22 -07001783 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 if (mDebugDisableHWC || mDebugRegion) {
1785 layer->forceClientComposition(*displayId);
1786 }
David Sodman79bba0e2018-08-05 18:07:49 -07001787 }
1788 }
1789 }
1790
1791 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001792 for (const auto& [token, displayDevice] : mDisplays) {
1793 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001794 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001795 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001796 continue;
1797 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001798 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001799
1800 if (mDrawingState.colorMatrixChanged) {
1801 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001802 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001804 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1807 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001808 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001809 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001810 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1811 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001812 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001813 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001814 }
1815
Peiyong Lind3788632018-09-18 16:01:31 -07001816 // TODO(b/111562338) remove when composer 2.3 is shipped.
1817 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001818 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001819 }
1820
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001821 if (layer->getRoundedCornerState().radius > 0.0f) {
1822 layer->forceClientComposition(*displayId);
1823 }
1824
Dominik Laskowski075d3172018-05-24 15:50:06 -07001825 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001826 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001827 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001828 continue;
1829 }
1830
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 const auto& displayState = display->getState();
1832 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1833 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001834 }
1835
Peiyong Lin13effd12018-07-24 17:01:47 -07001836 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001837 ColorMode colorMode;
1838 Dataspace dataSpace;
1839 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001840 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 }
1843 }
1844
1845 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001846
1847 for (const auto& [token, display] : mDisplays) {
1848 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001849 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001850 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001851
1852 if (displayId) {
1853 if (!layer->setHwcLayer(*displayId)) {
1854 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1855 }
1856 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001857 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858
Dominik Laskowski05275f12018-11-01 15:03:24 -07001859 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001860 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1861 }
1862 }
David Sodman79bba0e2018-08-05 18:07:49 -07001863}
1864
Lloyd Pique32cbe282018-10-19 13:09:22 -07001865void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1866 bool repaintEverything) {
1867 auto display = displayDevice->getCompositionDisplay();
1868 const auto& displayState = display->getState();
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 // is debugging enabled
1871 if (CC_LIKELY(!mDebugRegion))
1872 return;
1873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001875 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00001876 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 if (!dirtyRegion.isEmpty()) {
1878 // redraw the whole screen
Alec Mouri79108df2019-02-04 19:33:44 +00001879 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880
Alec Mouri79108df2019-02-04 19:33:44 +00001881 // and draw the dirty region
1882 auto& engine(getRenderEngine());
1883 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
1884
1885 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 }
1887 }
1888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890
1891 if (mDebugRegion > 1) {
1892 usleep(mDebugRegion * 1000);
1893 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001894
Lloyd Pique32cbe282018-10-19 13:09:22 -07001895 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896}
1897
Adrian Roos1e1a1282017-11-01 19:05:31 +01001898void SurfaceFlinger::doTracing(const char* where) {
1899 ATRACE_CALL();
1900 ATRACE_NAME(where);
1901 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001902 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001903 }
1904}
1905
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001906void SurfaceFlinger::logLayerStats() {
1907 ATRACE_CALL();
1908 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001909 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001910 if (display->isPrimary()) {
1911 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001912 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001913 }
1914 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915
1916 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917 }
1918}
1919
David Sodman2b406362017-12-15 13:33:47 -08001920void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 ATRACE_CALL();
1923 ALOGV("preComposition");
1924
David Sodman2b406362017-12-15 13:33:47 -08001925 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001929 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 needExtraInvalidate = true;
1931 }
Robert Carr2047fae2016-11-28 14:09:09 -08001932 });
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 if (needExtraInvalidate) {
1935 signalLayerUpdate();
1936 }
1937}
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1940 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Update queue of past composite+present times and determine the
1942 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001945 while (!getBE().mCompositePresentTimes.empty()) {
1946 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Cached values should have been updated before calling this method,
1948 // which helps avoid duplicate syscalls.
1949 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1950 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1951 break;
1952 }
1953 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
1957 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001958 while (getBE().mCompositePresentTimes.size() > 16) {
1959 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 }
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001963}
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1966 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 // Integer division and modulo round toward 0 not -inf, so we need to
1968 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1970 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1971 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972
Ana Krulec757f63a2019-01-25 10:46:18 -08001973 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001974 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001975 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001976 }
1977
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Snap the latency to a value that removes scheduling jitter from the
1979 // composition and present times, which often have >1ms of jitter.
1980 // Reducing jitter is important if an app attempts to extrapolate
1981 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001982 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001984 nsecs_t bias = stats.vsyncPeriod / 2;
1985 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1986 nsecs_t snappedCompositeToPresentLatency =
1987 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988
David Sodman99974d22017-11-28 12:04:33 -08001989 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001990 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1991 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001992 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993}
1994
Ady Abraham8164d482019-01-11 14:47:59 -08001995// debug patch for b/119477596 - add stack guards to catch stack
1996// corruptions and disable clang optimizations.
1997// The code below is temporary and planned to be removed once stack
1998// corruptions are found.
1999#pragma clang optimize off
2000class StackGuard {
2001public:
2002 StackGuard(const char* name, const char* func, int line) {
2003 guarders.reserve(MIN_CAPACITY);
2004 guarders.push_back({this, name, func, line});
2005 validate();
2006 }
2007 ~StackGuard() {
2008 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2009 if (i->guard == this) {
2010 guarders.erase(i);
2011 break;
2012 }
2013 }
2014 }
2015
2016 static void validate() {
2017 for (const auto& guard : guarders) {
2018 if (guard.guard->cookie != COOKIE_VALUE) {
2019 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2020 CallStack stack(LOG_TAG);
2021 abort();
2022 }
2023 }
2024 }
2025
2026private:
2027 uint64_t cookie = COOKIE_VALUE;
2028 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2029 static constexpr size_t MIN_CAPACITY = 16;
2030
2031 struct GuarderElement {
2032 StackGuard* guard;
2033 const char* name;
2034 const char* func;
2035 int line;
2036 };
2037
2038 static std::vector<GuarderElement> guarders;
2039};
2040std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2041
2042#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2043
2044#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002045void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046{
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 ATRACE_CALL();
2049 ALOGV("postComposition");
2050
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002052 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002055 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002059 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 const auto displayDevice = getDefaultDisplayDeviceLocked();
2061 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062
David Sodman73beded2017-11-15 11:56:06 -08002063 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2066
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002069 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2070 ->getRenderSurface()
2071 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002072 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073 } else {
2074 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2075 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
2078
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2081 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002082 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002084 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085
Ana Krulece588e312018-09-18 12:32:24 -07002086 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002087 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002088 if (mUseScheduler) {
2089 mScheduler->getDisplayStatInfo(&stats);
2090 } else {
2091 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2092 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2093 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002094
Ady Abraham8164d482019-01-11 14:47:59 -08002095 ASSERT_ON_STACK_GUARD();
2096
David Sodman2b406362017-12-15 13:33:47 -08002097 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098 // when we started doing work for this frame, but that should be okay
2099 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002100 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002101 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002102 DEFINE_STACK_GUARD(compositorTiming);
2103
Brian Andersond0010582017-03-07 13:20:31 -08002104 {
David Sodman99974d22017-11-28 12:04:33 -08002105 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002106 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002107 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002108
2109 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002110 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111
Robert Carr2047fae2016-11-28 14:09:09 -08002112 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 bool frameLatched =
2114 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2115 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002116 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002117 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002118 recordBufferingStats(layer->getName().string(),
2119 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002120 }
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002122 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002124 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002126 if (mUseScheduler) {
2127 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002130 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2131 enableHardwareVsync();
2132 } else {
2133 disableHardwareVsync(false);
2134 }
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002136 }
2137 }
2138
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002139 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2141 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002142 if (mUseScheduler) {
2143 mScheduler->enableHardwareVsync();
2144 } else {
2145 enableHardwareVsync();
2146 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002147 }
2148 }
2149
Ady Abraham8164d482019-01-11 14:47:59 -08002150 ASSERT_ON_STACK_GUARD();
2151
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002152 if (mAnimCompositionPending) {
2153 mAnimCompositionPending = false;
2154
Brian Anderson4e606e32017-03-16 15:34:57 -07002155 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002157 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002158
2159 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 // The HWC doesn't support present fences, so use the refresh
2162 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 const nsecs_t presentTime =
2164 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002165 DEFINE_STACK_GUARD(presentTime);
2166
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002167 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002168 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002169 }
2170 mAnimFrameTracker.advanceFrame();
2171 }
Dan Stozab90cf072015-03-05 11:05:59 -08002172
Ady Abraham8164d482019-01-11 14:47:59 -08002173 ASSERT_ON_STACK_GUARD();
2174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002176 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002178 }
2179
Ady Abraham8164d482019-01-11 14:47:59 -08002180 ASSERT_ON_STACK_GUARD();
2181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002183
Ady Abraham8164d482019-01-11 14:47:59 -08002184 ASSERT_ON_STACK_GUARD();
2185
Lloyd Pique32cbe282018-10-19 13:09:22 -07002186 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2187 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002188 return;
2189 }
2190
2191 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002192 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002193 if (mHasPoweredOff) {
2194 mHasPoweredOff = false;
2195 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002196 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002198 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002200 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2201 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002202 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002203 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002204 }
David Sodman4a36e932017-11-07 14:29:47 -08002205 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002206
2207 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002208 }
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002210 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002211
2212 {
2213 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002214 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002215 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002216 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002217 if (refillCount > 0) {
2218 const size_t offset = mTexturePool.size();
2219 mTexturePool.resize(mTexturePoolSize);
2220 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2221 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2222 }
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002224 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002225
Marissa Wallfda30bb2018-10-12 11:34:28 -07002226 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002227 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002228
2229 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002230}
Ady Abraham8164d482019-01-11 14:47:59 -08002231#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232
2233void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 ATRACE_CALL();
2235 ALOGV("rebuildLayerStacks");
2236
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002237 // We need to clear these out now as these may be holding on to a
2238 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2239 // also holds a reference. When the set of visible layers is recomputed,
2240 // some layers may be destroyed if the only thing keeping them alive was
2241 // that list of visible layers associated with each display. The layer
2242 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2243 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2244 for (const auto& [token, display] : mDisplays) {
2245 getBE().mCompositionInfo[token].clear();
2246 }
2247
Mathias Agopiancd60f992012-08-16 16:28:27 -07002248 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002250 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 mVisibleRegionsDirty = false;
2252 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002254 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const auto& displayDevice = pair.second;
2256 auto display = displayDevice->getCompositionDisplay();
2257 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 Region opaqueRegion;
2259 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002260 compositionengine::Output::OutputLayers layersSortedByZ;
2261 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002262 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263 const ui::Transform& tr = displayState.transform;
2264 const Rect bounds = displayState.bounds;
2265 if (displayState.isEnabled) {
2266 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267
Jeff Sharkey76488112017-02-27 14:15:18 -07002268 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002269 auto compositionLayer = layer->getCompositionLayer();
2270 if (compositionLayer == nullptr) {
2271 return;
2272 }
2273
Chia-I Wu83806892017-11-16 10:50:20 -08002274 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002275 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002276 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2277 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2278
Lloyd Piqueef36b002019-01-23 17:52:04 -08002279 if (display->belongsInOutput(layer->getLayerStack(),
2280 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002281 Region drawRegion(tr.transform(
2282 layer->visibleNonTransparentRegion));
2283 drawRegion.andSelf(bounds);
2284 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002285 layersSortedByZ.emplace_back(
2286 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2287 layerFE));
2288
2289 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002290 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002291 // Clear out the HWC layer if this layer was
2292 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002294 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002295 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002296 // WM changes display->layerStack upon sleep/awake.
2297 // Here we make sure we delete the HWC layers even if
2298 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002300 }
2301
2302 // If a layer is not going to get a release fence because
2303 // it is invisible, but it is also going to release its
2304 // old buffer, add it to the list of layers needing
2305 // fences.
2306 if (hwcLayerDestroyed) {
2307 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2308 mLayersWithQueuedFrames.cend(), layer);
2309 if (found != mLayersWithQueuedFrames.cend()) {
2310 layersNeedingFences.add(layer);
2311 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002312 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002313 });
2314 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002315
2316 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2317
2318 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002319 displayDevice->setLayersNeedingFences(layersNeedingFences);
2320
2321 Region undefinedRegion{bounds};
2322 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2323
2324 display->editState().undefinedRegion = undefinedRegion;
2325 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002326 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002327 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002328}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002329
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002332// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002334// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335// The returned HDR data space is one of
2336// - Dataspace::UNKNOWN
2337// - Dataspace::BT2020_HLG
2338// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2340 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002341 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002342 *outHdrDataSpace = Dataspace::UNKNOWN;
2343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002345 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 case Dataspace::V0_SCRGB:
2347 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002348 case Dataspace::BT2020:
2349 case Dataspace::BT2020_ITU:
2350 case Dataspace::BT2020_LINEAR:
2351 case Dataspace::DISPLAY_BT2020:
2352 bestDataSpace = Dataspace::DISPLAY_BT2020;
2353 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002355 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 case Dataspace::BT2020_PQ:
2358 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002359 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002362 case Dataspace::BT2020_HLG:
2363 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002364 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002365 // When there's mixed PQ content and HLG content, we set the HDR
2366 // data space to be BT2020_PQ and convert HLG to PQ.
2367 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2368 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002369 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002370 break;
2371 default:
2372 break;
2373 }
Romain Guy54f154a2017-10-24 21:40:32 +01002374 }
2375
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002377}
2378
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2381 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002382 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2383 *outMode = ColorMode::NATIVE;
2384 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002385 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002386 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002387 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002388
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002389 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002392 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2393
Peiyong Lindfde5112018-06-05 10:58:41 -07002394 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002395 const bool isHdr =
2396 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002397 if (isHdr) {
2398 bestDataSpace = hdrDataSpace;
2399 }
2400
Chia-I Wu0d711262018-05-21 15:19:35 -07002401 RenderIntent intent;
2402 switch (mDisplayColorSetting) {
2403 case DisplayColorSetting::MANAGED:
2404 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002405 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002406 break;
2407 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002408 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002409 break;
2410 default: // vendor display color setting
2411 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2412 break;
2413 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002414
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002415 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002416}
2417
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2419 auto display = displayDevice->getCompositionDisplay();
2420 const auto& displayState = display->getState();
2421
Alec Mouri79108df2019-02-04 19:33:44 +00002422 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2424 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002425
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426 // If nothing has changed (!dirty), don't recompose.
2427 // If something changed, but we don't currently have any visible layers,
2428 // and didn't when we last did a composition, then skip it this time.
2429 // The second rule does two things:
2430 // - When all layers are removed from a display, we'll emit one black
2431 // frame, then nothing more until we get new layers.
2432 // - When a display is created with a private layer stack, we won't
2433 // emit any black frames until a layer is added to the layer stack.
2434 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 const char flagPrefix[] = {'-', '+'};
2437 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2439 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2440 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2441 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002442
Lloyd Pique31cb2942018-10-19 17:23:03 -07002443 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002444
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002447 }
2448}
2449
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2451 auto display = displayDevice->getCompositionDisplay();
2452 const auto& displayState = display->getState();
2453
2454 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002455 return;
David Sodman2b406362017-12-15 13:33:47 -08002456 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457
Lloyd Pique31cb2942018-10-19 17:23:03 -07002458 status_t result = display->getRenderSurface()->prepareFrame(
2459 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002462}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002463
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002465 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 ALOGV("doComposition");
2467
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 auto display = displayDevice->getCompositionDisplay();
2469 const auto& displayState = display->getState();
2470
2471 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00002473 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002474
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002477
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002479 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002482}
2483
David Sodmanfa9b2af2017-12-24 13:28:59 -08002484void SurfaceFlinger::postFrame()
2485{
2486 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 const auto display = getDefaultDisplayDeviceLocked();
2488 if (display && getHwComposer().isConnected(*display->getId())) {
2489 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002490 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2491 logFrameStats();
2492 }
2493 }
2494}
2495
Lloyd Pique32cbe282018-10-19 13:09:22 -07002496void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002497 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002499
Lloyd Pique32cbe282018-10-19 13:09:22 -07002500 auto display = displayDevice->getCompositionDisplay();
2501 const auto& displayState = display->getState();
2502 const auto displayId = display->getId();
2503
David Sodmanfa9b2af2017-12-24 13:28:59 -08002504 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002505
Lloyd Pique32cbe282018-10-19 13:09:22 -07002506 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 if (displayId) {
2508 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002509 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002510 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002511 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002512 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002513
Chia-I Wu7b549592017-11-15 09:14:57 -08002514 // The layer buffer from the previous frame (if any) is released
2515 // by HWC only when the release fence from this frame (if any) is
2516 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 if (displayId && layer->hasHwcLayer(*displayId)) {
2518 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2519 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002520 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002521
2522 // If the layer was client composited in the previous frame, we
2523 // need to merge with the previous client target acquire fence.
2524 // Since we do not track that, always merge with the current
2525 // client target acquire fence when it is available, even though
2526 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002527 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002528 releaseFence =
2529 Fence::merge("LayerRelease", releaseFence,
2530 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002531 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002532
David Sodman15094112018-10-11 09:39:37 -07002533 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 }
Chia-I Wu83806892017-11-16 10:50:20 -08002535
2536 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002538 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002539 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002541 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002542 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002543 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002544 }
2545 }
2546
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 if (displayId) {
2548 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002549 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551}
2552
Mathias Agopian87baae12012-07-31 12:38:26 -07002553void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554{
Mathias Agopian841cde52012-03-01 15:44:37 -08002555 ATRACE_CALL();
2556
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002557 // here we keep a copy of the drawing state (that is the state that's
2558 // going to be overwritten by handleTransactionLocked()) outside of
2559 // mStateLock so that the side-effects of the State assignment
2560 // don't happen with mStateLock held (which can cause deadlocks).
2561 State drawingState(mDrawingState);
2562
Mathias Agopianca4d3602011-05-19 15:38:14 -07002563 Mutex::Autolock _l(mStateLock);
2564 const nsecs_t now = systemTime();
2565 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566
Mathias Agopianca4d3602011-05-19 15:38:14 -07002567 // Here we're guaranteed that some transaction flags are set
2568 // so we can call handleTransactionLocked() unconditionally.
2569 // We call getTransactionFlags(), which will also clear the flags,
2570 // with mStateLock held to guarantee that mCurrentState won't change
2571 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002572
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002573 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002574 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002575 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002576
Mathias Agopianca4d3602011-05-19 15:38:14 -07002577 mLastTransactionTime = systemTime() - now;
2578 mDebugInTransaction = 0;
2579 invalidateHwcGeometry();
2580 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002581}
2582
Lloyd Piqueba04e622017-12-14 17:11:26 -08002583void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2584 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 const std::optional<DisplayIdentificationInfo> info =
2586 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002589 continue;
2590 }
2591
Lloyd Piqueba04e622017-12-14 17:11:26 -08002592 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002594 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 mPhysicalDisplayTokens[info->id] = new BBinder();
2596 DisplayDeviceState state;
2597 state.displayId = info->id;
2598 state.isSecure = true; // All physical displays are currently considered secure.
2599 state.displayName = info->name;
2600 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2601 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002602 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002604 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2607 if (index >= 0) {
2608 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2609 mInterceptor->saveDisplayDeletion(state.sequenceId);
2610 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002611 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002613 }
2614
2615 processDisplayChangesLocked();
2616 }
2617
2618 mPendingHotplugEvents.clear();
2619}
2620
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002621void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2622 bool connected) {
2623 if (mUseScheduler) {
2624 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2625 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2626 } else {
2627 mEventThread->onHotplugReceived(displayType, connected);
2628 mSFEventThread->onHotplugReceived(displayType, connected);
2629 }
2630}
2631
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002634 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 const sp<IGraphicBufferProducer>& producer) {
2636 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002637 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002639 creationArgs.isSecure = state.isSecure;
2640 creationArgs.displaySurface = dispSurface;
2641 creationArgs.hasWideColorGamut = false;
2642 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002643
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2645 creationArgs.isPrimary = isInternalDisplay;
2646
2647 if (useColorManagement && displayId) {
2648 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002650 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002651 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002653
Dominik Laskowski7e045462018-05-30 13:02:02 -07002654 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002656 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657 }
tangrobin6753a022018-08-10 10:58:54 +08002658 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660 if (displayId) {
2661 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002662 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002663 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002664 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665
Lloyd Pique90c115d2018-09-18 21:39:42 -07002666 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002668 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
Lloyd Pique99d3da52018-01-22 17:48:03 -08002670 // Make sure that composition can never be stalled by a virtual display
2671 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002672 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002673 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2675 }
2676
Dominik Laskowski075d3172018-05-24 15:50:06 -07002677 creationArgs.displayInstallOrientation =
2678 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002679
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002681 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002682
Lloyd Pique90c115d2018-09-18 21:39:42 -07002683 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684
2685 if (maxFrameBufferAcquiredBuffers >= 3) {
2686 nativeWindowSurface->preallocateBuffers();
2687 }
2688
2689 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002690 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002691 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002692 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002693 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002694 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002695 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2696 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002697 if (!state.isVirtual()) {
2698 LOG_ALWAYS_FATAL_IF(!displayId);
2699 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002700 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 display->setLayerStack(state.layerStack);
2703 display->setProjection(state.orientation, state.viewport, state.frame);
2704 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002707}
2708
Lloyd Pique347200f2017-12-14 17:00:15 -08002709void SurfaceFlinger::processDisplayChangesLocked() {
2710 // here we take advantage of Vector's copy-on-write semantics to
2711 // improve performance by skipping the transaction entirely when
2712 // know that the lists are identical
2713 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2714 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2715 if (!curr.isIdenticalTo(draw)) {
2716 mVisibleRegionsDirty = true;
2717 const size_t cc = curr.size();
2718 size_t dc = draw.size();
2719
2720 // find the displays that were removed
2721 // (ie: in drawing state but not in current state)
2722 // also handle displays that changed
2723 // (ie: displays that are in both lists)
2724 for (size_t i = 0; i < dc;) {
2725 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2726 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 // Save display IDs before disconnecting.
2728 const auto internalDisplayId = getInternalDisplayId();
2729 const auto externalDisplayId = getExternalDisplayId();
2730
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002732 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002733 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002735 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002736 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002738 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002739 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 } else {
2742 // this display is in both lists. see if something changed.
2743 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2746 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2747 if (state_binder != draw_binder) {
2748 // changing the surface is like destroying and
2749 // recreating the DisplayDevice, so we just remove it
2750 // from the drawing state, so that it get re-added
2751 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002752 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002753 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 mDrawingState.displays.removeItemsAt(i);
2757 dc--;
2758 // at this point we must loop to the next item
2759 continue;
2760 }
2761
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 if ((state.orientation != draw[i].orientation) ||
2767 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002768 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 }
2770 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002771 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 }
2773 }
2774 }
2775 ++i;
2776 }
2777
2778 // find displays that were added
2779 // (ie: in current state but not in drawing state)
2780 for (size_t i = 0; i < cc; i++) {
2781 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2782 const DisplayDeviceState& state(curr[i]);
2783
Lloyd Pique542307f2018-10-19 13:24:08 -07002784 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002785 sp<IGraphicBufferProducer> producer;
2786 sp<IGraphicBufferProducer> bqProducer;
2787 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002788 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002789
Dominik Laskowski075d3172018-05-24 15:50:06 -07002790 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002791 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 // Virtual displays without a surface are dormant:
2793 // they have external state (layer stack, projection,
2794 // etc.) but no internal state (i.e. a DisplayDevice).
2795 if (state.surface != nullptr) {
2796 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002797 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002798 int width = 0;
2799 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2800 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2801 int height = 0;
2802 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2803 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2804 int intFormat = 0;
2805 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2806 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002807 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002808
Dominik Laskowski075d3172018-05-24 15:50:06 -07002809 displayId =
2810 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002811 }
2812
2813 // TODO: Plumb requested format back up to consumer
2814
2815 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002816 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 bqProducer, bqConsumer,
2818 state.displayName);
2819
2820 dispSurface = vds;
2821 producer = vds;
2822 }
2823 } else {
2824 ALOGE_IF(state.surface != nullptr,
2825 "adding a supported display, but rendering "
2826 "surface is provided (%p), ignoring it",
2827 state.surface.get());
2828
Dominik Laskowski075d3172018-05-24 15:50:06 -07002829 displayId = state.displayId;
2830 LOG_ALWAYS_FATAL_IF(!displayId);
2831 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 producer = bqProducer;
2833 }
2834
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002835 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002836 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002838 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002840 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002841 LOG_ALWAYS_FATAL_IF(!displayId);
2842
2843 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002844 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002845 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002846 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002847 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002848 }
2849 }
2850 }
2851 }
2852 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002853
2854 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002855}
2856
Mathias Agopian87baae12012-07-31 12:38:26 -07002857void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002858{
Dan Stoza7dde5992015-05-22 09:51:44 -07002859 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002860 mCurrentState.traverseInZOrder([](Layer* layer) {
2861 layer->notifyAvailableFrames();
2862 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002863
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 /*
2865 * Traversal of the children
2866 * (perform the transaction for each of them if needed)
2867 */
2868
Robert Carr720e5062018-07-30 17:45:14 -07002869 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002870 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002871 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002873 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874
2875 const uint32_t flags = layer->doTransaction(0);
2876 if (flags & Layer::eVisibleRegion)
2877 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002878
2879 if (flags & Layer::eInputInfoChanged) {
2880 inputChanged = true;
2881 }
Robert Carr2047fae2016-11-28 14:09:09 -08002882 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 }
2884
2885 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002886 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 */
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002890 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002891 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002895 // The transform hint might have changed for some layers
2896 // (either because a display has changed, or because a layer
2897 // as changed).
2898 //
2899 // Walk through all the layers in currentLayers,
2900 // and update their transform hint.
2901 //
2902 // If a layer is visible only on a single display, then that
2903 // display is used to calculate the hint, otherwise we use the
2904 // default display.
2905 //
2906 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2907 // the hint is set before we acquire a buffer from the surface texture.
2908 //
2909 // NOTE: layer transactions have taken place already, so we use their
2910 // drawing state. However, SurfaceFlinger's own transaction has not
2911 // happened yet, so we must use the current state layer list
2912 // (soon to become the drawing state list).
2913 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002915 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002916 bool first = true;
2917 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002918 // NOTE: we rely on the fact that layers are sorted by
2919 // layerStack first (so we don't have to traverse the list
2920 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002922 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002923 currentlayerStack = layerStack;
2924 // figure out if this layerstack is mirrored
2925 // (more than one display) if so, pick the default display,
2926 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 hintDisplay = nullptr;
2928 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002929 if (display->getCompositionDisplay()
2930 ->belongsInOutput(layer->getLayerStack(),
2931 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 if (hintDisplay) {
2933 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002934 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002935 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002937 }
2938 }
2939 }
2940 }
Chet Haase91d25932013-04-11 15:24:55 -07002941
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002943 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2944 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002945
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946 // could be null when this layer is using a layerStack
2947 // that is not visible on any display. Also can occur at
2948 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002949 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002950 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002951
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002953 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002954 if (hintDisplay) {
2955 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002956 }
Robert Carr2047fae2016-11-28 14:09:09 -08002957
2958 first = false;
2959 });
Mathias Agopian84300952012-11-21 16:02:13 -08002960 }
2961
2962
Mathias Agopian3559b072012-08-15 13:46:03 -07002963 /*
2964 * Perform our own transaction if needed
2965 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966
2967 if (mLayersAdded) {
2968 mLayersAdded = false;
2969 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002970 mVisibleRegionsDirty = true;
2971 }
2972
2973 // some layers might have been removed, so
2974 // we need to update the regions they're exposing.
2975 if (mLayersRemoved) {
2976 mLayersRemoved = false;
2977 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002978 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002980 // this layer is not visible anymore
2981 // TODO: we could traverse the tree from front to back and
2982 // compute the actual visible region
2983 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 Region visibleReg;
2985 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002986 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002987 }
Robert Carr2047fae2016-11-28 14:09:09 -08002988 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 }
2990
2991 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002992
Vishnu Nairde19f852018-12-18 16:11:53 -08002993 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002994 updateInputWindows();
2995 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002996 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002997
Riley Andrews03414a12014-07-01 14:22:59 -07002998 updateCursorAsync();
2999}
3000
Robert Carr720e5062018-07-30 17:45:14 -07003001void SurfaceFlinger::updateInputWindows() {
3002 ATRACE_CALL();
3003
Vishnu Nairde19f852018-12-18 16:11:53 -08003004 if (mInputFlinger == nullptr) {
3005 return;
3006 }
3007
Robert Carr720e5062018-07-30 17:45:14 -07003008 Vector<InputWindowInfo> inputHandles;
3009
3010 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3011 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003012 // When calculating the screen bounds we ignore the transparent region since it may
3013 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003014 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003015 }
3016 });
3017 mInputFlinger->setInputWindows(inputHandles);
3018}
3019
chaviwfbe5d9c2018-12-26 12:23:37 -08003020void SurfaceFlinger::executeInputWindowCommands() {
3021 if (!mInputFlinger) {
3022 return;
3023 }
3024
3025 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3026 if (transferTouchFocusCommand.fromToken != nullptr &&
3027 transferTouchFocusCommand.toToken != nullptr &&
3028 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3029 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3030 transferTouchFocusCommand.toToken);
3031 }
3032 }
3033
3034 mInputWindowCommands.clear();
3035}
3036
Riley Andrews03414a12014-07-01 14:22:59 -07003037void SurfaceFlinger::updateCursorAsync()
3038{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003039 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003040 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003041 continue;
3042 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3045 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003046 }
3047 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048}
3049
chaviw61626f22018-11-15 16:26:27 -08003050void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3051 if (layer->hasReadyFrame()) {
3052 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3053 if (layer->shouldPresentNow(expectedPresentTime)) {
3054 bool ignored = false;
3055 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3056 }
3057 }
3058 layer->releasePendingBuffer(systemTime());
3059}
3060
Mathias Agopian4fec8732012-06-29 14:12:52 -07003061void SurfaceFlinger::commitTransaction()
3062{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003063 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003064 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 for (const auto& l : mLayersPendingRemoval) {
3066 recordBufferingStats(l->getName().string(),
3067 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003068
3069 // We need to release the HWC layers when the Layer is removed
3070 // from the current state otherwise the HWC layer just continues
3071 // showing at its last configured state until we eventually
3072 // abandon the buffer queue.
3073 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003074 l->destroyHwcLayersForAllDisplays();
3075 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003076 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 }
3078 mLayersPendingRemoval.clear();
3079 }
3080
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003081 // If this transaction is part of a window animation then the next frame
3082 // we composite should be considered an animation as well.
3083 mAnimCompositionPending = mAnimTransactionPending;
3084
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003086 // clear the "changed" flags in current state
3087 mCurrentState.colorMatrixChanged = false;
3088
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 mDrawingState.traverseInZOrder([](Layer* layer) {
3090 layer->commitChildList();
3091 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003092 mTransactionPending = false;
3093 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095}
3096
Lloyd Pique32cbe282018-10-19 13:09:22 -07003097void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003098 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003099 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003101
Lloyd Pique32cbe282018-10-19 13:09:22 -07003102 auto display = displayDevice->getCompositionDisplay();
3103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 Region aboveOpaqueLayers;
3105 Region aboveCoveredLayers;
3106 Region dirty;
3107
Mathias Agopian87baae12012-07-31 12:38:26 -07003108 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109
Robert Carr2047fae2016-11-28 14:09:09 -08003110 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003111 // start with the whole surface at its current location
3112 const Layer::State& s(layer->getDrawingState());
3113
Jesse Hall01e29052013-02-19 16:13:35 -08003114 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003115 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003116 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003117 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003118
Mathias Agopianab028732010-03-16 16:41:46 -07003119 /*
3120 * opaqueRegion: area of a surface that is fully opaque.
3121 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003123
3124 /*
3125 * visibleRegion: area of a surface that is visible on screen
3126 * and not fully transparent. This is essentially the layer's
3127 * footprint minus the opaque regions above it.
3128 * Areas covered by a translucent surface are considered visible.
3129 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003131
3132 /*
3133 * coveredRegion: area of a surface that is covered by all
3134 * visible regions above it (which includes the translucent areas).
3135 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003137
Jesse Halla8026d22012-09-25 13:25:04 -07003138 /*
3139 * transparentRegion: area of a surface that is hinted to be completely
3140 * transparent. This is only used to tell when the layer has no visible
3141 * non-transparent regions and can be removed from the layer list. It
3142 * does not affect the visibleRegion of this layer or any layers
3143 * beneath it. The hint may not be correct if apps don't respect the
3144 * SurfaceView restrictions (which, sadly, some don't).
3145 */
3146 Region transparentRegion;
3147
Mathias Agopianab028732010-03-16 16:41:46 -07003148
3149 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003150 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003151 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003152 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003155 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003156 if (!visibleRegion.isEmpty()) {
3157 // Remove the transparent area from the visible region
3158 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003159 if (tr.preserveRects()) {
3160 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003161 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003162 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003163 // transformation too complex, can't do the
3164 // transparent region optimization.
3165 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003166 }
Mathias Agopianab028732010-03-16 16:41:46 -07003167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168
Mathias Agopianab028732010-03-16 16:41:46 -07003169 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003171 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003172 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003173 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003174 // the opaque region is the layer's footprint
3175 opaqueRegion = visibleRegion;
3176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 }
3178 }
3179
Robert Carre5f4f692018-01-12 13:12:28 -08003180 if (visibleRegion.isEmpty()) {
3181 layer->clearVisibilityRegions();
3182 return;
3183 }
3184
Mathias Agopianab028732010-03-16 16:41:46 -07003185 // Clip the covered region to the visible region
3186 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3187
3188 // Update aboveCoveredLayers for next (lower) layer
3189 aboveCoveredLayers.orSelf(visibleRegion);
3190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 // subtract the opaque region covered by the layers above us
3192 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193
3194 // compute this layer's dirty region
3195 if (layer->contentDirty) {
3196 // we need to invalidate the whole region
3197 dirty = visibleRegion;
3198 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003199 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 layer->contentDirty = false;
3201 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003202 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003203 * the exposed region consists of two components:
3204 * 1) what's VISIBLE now and was COVERED before
3205 * 2) what's EXPOSED now less what was EXPOSED before
3206 *
3207 * note that (1) is conservative, we start with the whole
3208 * visible region but only keep what used to be covered by
3209 * something -- which mean it may have been exposed.
3210 *
3211 * (2) handles areas that were not covered by anything but got
3212 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003213 */
Mathias Agopianab028732010-03-16 16:41:46 -07003214 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003215 const Region oldVisibleRegion = layer->visibleRegion;
3216 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003217 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3218 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 }
3220 dirty.subtractSelf(aboveOpaqueLayers);
3221
3222 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003223 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224
Mathias Agopianab028732010-03-16 16:41:46 -07003225 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003227
Jesse Halla8026d22012-09-25 13:25:04 -07003228 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 layer->setVisibleRegion(visibleRegion);
3230 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003231 layer->setVisibleNonTransparentRegion(
3232 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003233 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234
Mathias Agopian87baae12012-07-31 12:38:26 -07003235 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236}
3237
Chia-I Wuab0c3192017-08-01 11:29:00 -07003238void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003239 for (const auto& [token, displayDevice] : mDisplays) {
3240 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003241 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003242 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003243 }
3244 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003245}
3246
Daniel Solomon42d04562019-01-20 21:03:19 -08003247void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3248 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3249 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3250 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3251 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3252 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3253 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3254 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3255 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3256 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3257 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3258 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3259 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3260}
3261
Dan Stoza6b9454d2014-11-07 16:00:59 -08003262bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003264 ALOGV("handlePageFlip");
3265
Brian Andersond6927fb2016-07-23 23:37:30 -07003266 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267
Mathias Agopian4fec8732012-06-29 14:12:52 -07003268 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003269 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003270 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003271
3272 // Store the set of layers that need updates. This set must not change as
3273 // buffers are being latched, as this could result in a deadlock.
3274 // Example: Two producers share the same command stream and:
3275 // 1.) Layer 0 is latched
3276 // 2.) Layer 0 gets a new frame
3277 // 2.) Layer 1 gets a new frame
3278 // 3.) Layer 1 is latched.
3279 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3280 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003281 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003282 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003283 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003284 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3285 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003286 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003287 } else {
3288 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003289 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003290 } else {
3291 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003292 }
Robert Carr2047fae2016-11-28 14:09:09 -08003293 });
3294
Lloyd Piquef2c79392018-12-20 16:23:33 -08003295 if (!mLayersWithQueuedFrames.empty()) {
3296 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3297 // writes to Layer current state. See also b/119481871
3298 Mutex::Autolock lock(mStateLock);
3299
3300 for (auto& layer : mLayersWithQueuedFrames) {
3301 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3302 layer->useSurfaceDamage();
3303 invalidateLayerStack(layer, dirty);
3304 if (layer->isBufferLatched()) {
3305 newDataLatched = true;
3306 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003307 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003308 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003309
Alec Mouri86770e52018-09-24 22:40:58 +00003310 // Clear the renderengine fence here...
3311 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3312 // clear instead of sp::clear.
3313 getBE().flushFence = Fence::NO_FENCE;
3314
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003315 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003316
Vishnu Nairde19f852018-12-18 16:11:53 -08003317 if (visibleRegions) {
3318 // Update input window info if the layer receives its first buffer.
3319 updateInputWindows();
3320 }
3321
Dan Stoza6b9454d2014-11-07 16:00:59 -08003322 // If we will need to wake up at some time in the future to deal with a
3323 // queued frame that shouldn't be displayed during this vsync period, wake
3324 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003325 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003326 signalLayerUpdate();
3327 }
3328
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003329 // enter boot animation on first buffer latch
3330 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3331 ALOGI("Enter boot animation");
3332 mBootStage = BootStage::BOOTANIMATION;
3333 }
3334
Dan Stoza6b9454d2014-11-07 16:00:59 -08003335 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003336 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337}
3338
Mathias Agopianad456f92011-01-13 17:53:01 -08003339void SurfaceFlinger::invalidateHwcGeometry()
3340{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003341 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003342}
3343
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003345 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346 auto display = displayDevice->getCompositionDisplay();
3347
Dan Stoza71433162014-02-04 16:22:36 -08003348 // We only need to actually compose the display if:
3349 // 1) It is being handled by hardware composer, which may need this to
3350 // keep its virtual display state machine in sync, or
3351 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003352 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003353 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003354 return;
3355 }
3356
Dan Stoza9e56aa02015-11-02 13:00:03 -08003357 ALOGV("doDisplayComposition");
Alec Mouri79108df2019-02-04 19:33:44 +00003358 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003359
3360 // swap buffers (presentation)
Alec Mouri79108df2019-02-04 19:33:44 +00003361 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362}
3363
Alec Mouri79108df2019-02-04 19:33:44 +00003364bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003365 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003366
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367 auto display = displayDevice->getCompositionDisplay();
3368 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003369 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370
3371 const Region bounds(displayState.bounds);
3372 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003373 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003374 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003375
Peiyong Lind3788632018-09-18 16:01:31 -07003376 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003377 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003378
Alec Mouri79108df2019-02-04 19:33:44 +00003379 // Framebuffer will live in this scope for GPU composition.
3380 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003381
Dan Stoza9e56aa02015-11-02 13:00:03 -08003382 if (hasClientComposition) {
3383 ALOGV("hasClientComposition");
3384
Alec Mouri79108df2019-02-04 19:33:44 +00003385 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003386
3387 if (buf == nullptr) {
3388 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3389 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003390 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003391 return false;
3392 }
3393
Alec Mouri79108df2019-02-04 19:33:44 +00003394 // Bind the framebuffer in this scope.
3395 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3396 buf->getNativeBuffer());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003397
Alec Mouri79108df2019-02-04 19:33:44 +00003398 if (fbo->getStatus() != NO_ERROR) {
3399 ALOGW("Binding buffer for display [%s] failed with status: %d",
3400 displayDevice->getDisplayName().c_str(), fbo->getStatus());
3401 return false;
3402 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003403
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003404 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003405 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003406 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003407 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003408 }
Alec Mouri79108df2019-02-04 19:33:44 +00003409 getRenderEngine().setOutputDataSpace(outputDataspace);
3410 getRenderEngine().setDisplayMaxLuminance(
3411 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003412
Lloyd Pique441d5042018-10-18 16:49:51 -07003413 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003414 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003415 getHwComposer()
3416 .hasDisplayCapability(displayId,
3417 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003418
Peiyong Lind3788632018-09-18 16:01:31 -07003419 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003420 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3421 if (applyColorMatrix) {
Alec Mouri79108df2019-02-04 19:33:44 +00003422 colorMatrix = mDrawingState.colorMatrix;
3423 }
3424
3425 display->getRenderSurface()->setViewportAndProjection();
3426
3427 // Never touch the framebuffer if we don't have any framebuffer layers
3428 if (hasDeviceComposition) {
3429 // when using overlays, we assume a fully transparent framebuffer
3430 // NOTE: we could reduce how much we need to clear, for instance
3431 // remove where there are opaque FB layers. however, on some
3432 // GPUs doing a "clean slate" clear might be more efficient.
3433 // We'll revisit later if needed.
3434 getRenderEngine().clearWithColor(0, 0, 0, 0);
3435 } else {
3436 // we start with the whole screen area and remove the scissor part
3437 // we're left with the letterbox region
3438 // (common case is that letterbox ends-up being empty)
3439 const Region letterbox = bounds.subtract(displayState.scissor);
3440
3441 // compute the area to clear
3442 const Region region = displayState.undefinedRegion.merge(letterbox);
3443
3444 // screen is already cleared here
3445 if (!region.isEmpty()) {
3446 // can happen with SurfaceView
3447 drawWormhole(region);
3448 }
3449 }
3450
3451 const Rect& bounds = displayState.bounds;
3452 const Rect& scissor = displayState.scissor;
3453 if (scissor != bounds) {
3454 // scissor doesn't match the screen's dimensions, so we
3455 // need to clear everything outside of it and enable
3456 // the GL scissor so we don't draw anything where we shouldn't
3457
3458 // enable scissor for this frame
3459 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003460 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003461 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003462
Mathias Agopian85d751c2012-08-29 16:59:24 -07003463 /*
3464 * and then, render the layers targeted at the framebuffer
3465 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003466
Dan Stoza9e56aa02015-11-02 13:00:03 -08003467 ALOGV("Rendering client layers");
Alec Mouri79108df2019-02-04 19:33:44 +00003468 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003469 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003470 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri79108df2019-02-04 19:33:44 +00003471 const Region clip(bounds.intersect(displayTransform.transform(layer->visibleRegion)));
David Sodmanc1498e62018-09-12 14:36:26 -07003472 ALOGV("Layer: %s", layer->getName().string());
3473 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003474 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003475 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003476 case HWC2::Composition::Cursor:
3477 case HWC2::Composition::Device:
3478 case HWC2::Composition::Sideband:
3479 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003480 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003481 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003482 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003483 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003484 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003485 // never clear the very first layer since we're
3486 // guaranteed the FB is already cleared
Alec Mouri79108df2019-02-04 19:33:44 +00003487 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003488 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003490 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003491 case HWC2::Composition::Client: {
Alec Mouri79108df2019-02-04 19:33:44 +00003492 if (layer->hasColorTransform()) {
3493 mat4 tmpMatrix;
3494 if (applyColorMatrix) {
3495 tmpMatrix = mDrawingState.colorMatrix;
3496 }
3497 tmpMatrix *= layer->getColorTransform();
3498 getRenderEngine().setColorTransform(tmpMatrix);
3499 } else {
3500 getRenderEngine().setColorTransform(colorMatrix);
Peiyong Lind3788632018-09-18 16:01:31 -07003501 }
Alec Mouri79108df2019-02-04 19:33:44 +00003502 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003503 break;
3504 }
3505 default:
3506 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003507 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003508 } else {
3509 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003510 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003511 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003512 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003513
Alec Mouri79108df2019-02-04 19:33:44 +00003514 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003515 if (hasClientComposition) {
Alec Mouri79108df2019-02-04 19:33:44 +00003516 getRenderEngine().setColorTransform(mat4());
3517 getRenderEngine().disableScissor();
3518 display->getRenderSurface()->finishBuffer();
3519 // Clear out error flags here so that we don't wait until next
3520 // composition to log.
3521 getRenderEngine().checkErrors();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003522 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003523 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524}
3525
Chia-I Wu28e3a252018-09-07 12:05:02 -07003526void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003527 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003528 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529}
3530
Dan Stoza7d89d062015-04-30 13:29:25 -07003531status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003532 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003533 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003535 const sp<Layer>& parent,
3536 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003537{
Dan Stoza7d89d062015-04-30 13:29:25 -07003538 // add this layer to the current state list
3539 {
3540 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003541 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003542 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3543 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003544 return NO_MEMORY;
3545 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003546 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003547 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003548 } else if (parent == nullptr) {
3549 lbc->onRemovedFromCurrentState();
3550 } else if (parent->isRemovedFromCurrentState()) {
3551 parent->addChild(lbc);
3552 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003553 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003554 parent->addChild(lbc);
3555 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003556
Yiwei Zhang243b3782018-05-15 17:40:04 -07003557 if (gbc != nullptr) {
3558 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3559 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3560 mMaxGraphicBufferProducerListSize,
3561 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3562 mGraphicBufferProducerList.size(),
3563 mMaxGraphicBufferProducerListSize, mNumLayers);
3564 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003565 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003566 }
3567
Mathias Agopian96f08192010-06-02 23:28:45 -07003568 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003569 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003570
Dan Stoza7d89d062015-04-30 13:29:25 -07003571 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003572}
3573
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003574uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003575 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003576}
3577
Mathias Agopian3f844832013-08-07 21:24:32 -07003578uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003579 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580}
3581
Mathias Agopian3f844832013-08-07 21:24:32 -07003582uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003583 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003584}
3585
3586uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003587 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003588 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003589 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003591 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 }
3593 return old;
3594}
3595
Marissa Wall713b63f2018-10-17 15:42:43 -07003596bool SurfaceFlinger::flushTransactionQueues() {
3597 Mutex::Autolock _l(mStateLock);
3598 auto it = mTransactionQueues.begin();
3599 while (it != mTransactionQueues.end()) {
3600 auto& [applyToken, transactionQueue] = *it;
3601
3602 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3604 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003605 break;
3606 }
chaviw273171b2018-12-26 11:46:30 -08003607 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003608 transactionQueue.pop();
3609 }
3610
3611 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3612 }
3613 return mTransactionQueues.empty();
3614}
3615
chaviwca27f252018-02-06 16:46:39 -08003616bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3617 for (const ComposerState& state : states) {
3618 // Here we need to check that the interface we're given is indeed
3619 // one of our own. A malicious client could give us a nullptr
3620 // IInterface, or one of its own or even one of our own but a
3621 // different type. All these situations would cause us to crash.
3622 if (state.client == nullptr) {
3623 return true;
3624 }
3625
3626 sp<IBinder> binder = IInterface::asBinder(state.client);
3627 if (binder == nullptr) {
3628 return true;
3629 }
3630
3631 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3632 return true;
3633 }
3634 }
3635 return false;
3636}
3637
Marissa Wall17b4e452018-12-26 16:32:34 -08003638bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3639 const Vector<ComposerState>& states) {
3640 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3641 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3642 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3643 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3644 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3645 return false;
3646 }
3647
Marissa Wall713b63f2018-10-17 15:42:43 -07003648 for (const ComposerState& state : states) {
3649 const layer_state_t& s = state.state;
3650 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3651 continue;
3652 }
3653 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003654 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003655 }
3656 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003657 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003658}
3659
3660void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3661 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003662 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003663 const InputWindowCommands& inputWindowCommands,
3664 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003665 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003666 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003667
chaviwca27f252018-02-06 16:46:39 -08003668 if (containsAnyInvalidClientState(states)) {
3669 return;
3670 }
3671
Marissa Wall713b63f2018-10-17 15:42:43 -07003672 // If its TransactionQueue already has a pending TransactionState or if it is pending
3673 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003674 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3675 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003676 setTransactionFlags(eTransactionNeeded);
3677 return;
3678 }
3679
chaviw273171b2018-12-26 11:46:30 -08003680 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003681}
3682
3683void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003684 const Vector<DisplayState>& displays, uint32_t flags,
3685 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003686 uint32_t transactionFlags = 0;
3687
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003688 if (flags & eAnimation) {
3689 // For window updates that are part of an animation we must wait for
3690 // previous animation "frames" to be handled.
3691 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003692 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003693 if (CC_UNLIKELY(err != NO_ERROR)) {
3694 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003695 // caller after a few seconds.
3696 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3697 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003698 mAnimTransactionPending = false;
3699 break;
3700 }
3701 }
3702 }
3703
chaviwca27f252018-02-06 16:46:39 -08003704 for (const DisplayState& display : displays) {
3705 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003706 }
3707
Marissa Walle2ffb422018-10-12 11:33:52 -07003708 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003709 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003710 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003711 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003712 // If the state doesn't require a traversal and there are callbacks, send them now
3713 if (!(clientStateFlags & eTraversalNeeded)) {
3714 mTransactionCompletedThread.sendCallbacks();
3715 }
3716 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003717
chaviw273171b2018-12-26 11:46:30 -08003718 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3719
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003720 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3721 // anyway. This can be used as a flush mechanism for previous async transactions.
3722 // Empty animation transaction can be used to simulate back-pressure, so also force a
3723 // transaction for empty animation transactions.
3724 if (transactionFlags == 0 &&
3725 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003726 transactionFlags = eTransactionNeeded;
3727 }
3728
Mathias Agopian386aa982011-11-07 21:58:03 -08003729 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003730 if (mInterceptor->isEnabled()) {
3731 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003732 }
Irvel468051e2016-06-13 16:44:44 -07003733
Mathias Agopian386aa982011-11-07 21:58:03 -08003734 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003735 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3736 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003737 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003738
3739 // if this is a synchronous transaction, wait for it to take effect
3740 // before returning.
3741 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003742 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003743 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003744 if (flags & eAnimation) {
3745 mAnimTransactionPending = true;
3746 }
3747 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003748 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3749 if (CC_UNLIKELY(err != NO_ERROR)) {
3750 // just in case something goes wrong in SF, return to the
3751 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003752 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3753 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003754 break;
3755 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757 }
3758}
3759
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003760uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3761 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3762 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003763
Mathias Agopiane57f2922012-08-09 16:29:12 -07003764 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003765 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3766
3767 const uint32_t what = s.what;
3768 if (what & DisplayState::eSurfaceChanged) {
3769 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3770 state.surface = s.surface;
3771 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003772 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003774 if (what & DisplayState::eLayerStackChanged) {
3775 if (state.layerStack != s.layerStack) {
3776 state.layerStack = s.layerStack;
3777 flags |= eDisplayTransactionNeeded;
3778 }
3779 }
3780 if (what & DisplayState::eDisplayProjectionChanged) {
3781 if (state.orientation != s.orientation) {
3782 state.orientation = s.orientation;
3783 flags |= eDisplayTransactionNeeded;
3784 }
3785 if (state.frame != s.frame) {
3786 state.frame = s.frame;
3787 flags |= eDisplayTransactionNeeded;
3788 }
3789 if (state.viewport != s.viewport) {
3790 state.viewport = s.viewport;
3791 flags |= eDisplayTransactionNeeded;
3792 }
3793 }
3794 if (what & DisplayState::eDisplaySizeChanged) {
3795 if (state.width != s.width) {
3796 state.width = s.width;
3797 flags |= eDisplayTransactionNeeded;
3798 }
3799 if (state.height != s.height) {
3800 state.height = s.height;
3801 flags |= eDisplayTransactionNeeded;
3802 }
3803 }
3804
Mathias Agopiane57f2922012-08-09 16:29:12 -07003805 return flags;
3806}
3807
Robert Carrd4ae7f32018-06-07 16:10:57 -07003808bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3809 IPCThreadState* ipc = IPCThreadState::self();
3810 const int pid = ipc->getCallingPid();
3811 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003812 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003813 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003814 return false;
3815 }
3816 return true;
3817}
3818
chaviwca27f252018-02-06 16:46:39 -08003819uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3820 const layer_state_t& s = composerState.state;
3821 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3822
Mathias Agopian13127d82013-03-05 17:47:11 -08003823 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003824 if (layer == nullptr) {
3825 return 0;
3826 }
3827
chaviw8b3871a2017-11-01 17:41:01 -07003828 uint32_t flags = 0;
3829
Garfield Tan8a3083e2018-12-03 13:21:07 -08003830 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003831 bool geometryAppliesWithResize =
3832 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003833
3834 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3835 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003836 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003837 layer->pushPendingState();
3838 }
3839
chaviw8b3871a2017-11-01 17:41:01 -07003840 if (what & layer_state_t::ePositionChanged) {
3841 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3842 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003843 }
chaviw8b3871a2017-11-01 17:41:01 -07003844 }
3845 if (what & layer_state_t::eLayerChanged) {
3846 // NOTE: index needs to be calculated before we update the state
3847 const auto& p = layer->getParent();
3848 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003849 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003850 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003851 mCurrentState.layersSortedByZ.removeAt(idx);
3852 mCurrentState.layersSortedByZ.add(layer);
3853 // we need traversal (state changed)
3854 // AND transaction (list changed)
3855 flags |= eTransactionNeeded|eTraversalNeeded;
3856 }
chaviw8b3871a2017-11-01 17:41:01 -07003857 } else {
3858 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003859 flags |= eTransactionNeeded|eTraversalNeeded;
3860 }
3861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 }
3863 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003864 // NOTE: index needs to be calculated before we update the state
3865 const auto& p = layer->getParent();
3866 if (p == nullptr) {
3867 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3868 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3869 mCurrentState.layersSortedByZ.removeAt(idx);
3870 mCurrentState.layersSortedByZ.add(layer);
3871 // we need traversal (state changed)
3872 // AND transaction (list changed)
3873 flags |= eTransactionNeeded|eTraversalNeeded;
3874 }
3875 } else {
3876 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3877 flags |= eTransactionNeeded|eTraversalNeeded;
3878 }
chaviw8b3871a2017-11-01 17:41:01 -07003879 }
3880 }
3881 if (what & layer_state_t::eSizeChanged) {
3882 if (layer->setSize(s.w, s.h)) {
3883 flags |= eTraversalNeeded;
3884 }
3885 }
3886 if (what & layer_state_t::eAlphaChanged) {
3887 if (layer->setAlpha(s.alpha))
3888 flags |= eTraversalNeeded;
3889 }
3890 if (what & layer_state_t::eColorChanged) {
3891 if (layer->setColor(s.color))
3892 flags |= eTraversalNeeded;
3893 }
Peiyong Lind3788632018-09-18 16:01:31 -07003894 if (what & layer_state_t::eColorTransformChanged) {
3895 if (layer->setColorTransform(s.colorTransform)) {
3896 flags |= eTraversalNeeded;
3897 }
3898 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003899 if (what & layer_state_t::eBackgroundColorChanged) {
3900 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3901 flags |= eTraversalNeeded;
3902 }
3903 }
chaviw8b3871a2017-11-01 17:41:01 -07003904 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003905 // TODO: b/109894387
3906 //
3907 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3908 // rotation. To see the problem observe that if we have a square parent, and a child
3909 // of the same size, then we rotate the child 45 degrees around it's center, the child
3910 // must now be cropped to a non rectangular 8 sided region.
3911 //
3912 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3913 // private API, and the WindowManager only uses rotation in one case, which is on a top
3914 // level layer in which cropping is not an issue.
3915 //
3916 // However given that abuse of rotation matrices could lead to surfaces extending outside
3917 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3918 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3919 // transformations.
3920 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003921 flags |= eTraversalNeeded;
3922 }
3923 if (what & layer_state_t::eTransparentRegionChanged) {
3924 if (layer->setTransparentRegionHint(s.transparentRegion))
3925 flags |= eTraversalNeeded;
3926 }
3927 if (what & layer_state_t::eFlagsChanged) {
3928 if (layer->setFlags(s.flags, s.mask))
3929 flags |= eTraversalNeeded;
3930 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003931 if (what & layer_state_t::eCropChanged_legacy) {
3932 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003933 flags |= eTraversalNeeded;
3934 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003935 if (what & layer_state_t::eCornerRadiusChanged) {
3936 if (layer->setCornerRadius(s.cornerRadius))
3937 flags |= eTraversalNeeded;
3938 }
chaviw8b3871a2017-11-01 17:41:01 -07003939 if (what & layer_state_t::eLayerStackChanged) {
3940 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3941 // We only allow setting layer stacks for top level layers,
3942 // everything else inherits layer stack from its parent.
3943 if (layer->hasParent()) {
3944 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3945 layer->getName().string());
3946 } else if (idx < 0) {
3947 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3948 "that also does not appear in the top level layer list. Something"
3949 " has gone wrong.", layer->getName().string());
3950 } else if (layer->setLayerStack(s.layerStack)) {
3951 mCurrentState.layersSortedByZ.removeAt(idx);
3952 mCurrentState.layersSortedByZ.add(layer);
3953 // we need traversal (state changed)
3954 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003955 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003956 }
3957 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003958 if (what & layer_state_t::eDeferTransaction_legacy) {
3959 if (s.barrierHandle_legacy != nullptr) {
3960 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3961 } else if (s.barrierGbp_legacy != nullptr) {
3962 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003963 if (authenticateSurfaceTextureLocked(gbp)) {
3964 const auto& otherLayer =
3965 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003966 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003967 } else {
3968 ALOGE("Attempt to defer transaction to to an"
3969 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003970 }
3971 }
chaviw8b3871a2017-11-01 17:41:01 -07003972 // We don't trigger a traversal here because if no other state is
3973 // changed, we don't want this to cause any more work
3974 }
3975 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003976 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003977 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003978 if (!hadParent) {
3979 mCurrentState.layersSortedByZ.remove(layer);
3980 }
chaviw8b3871a2017-11-01 17:41:01 -07003981 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003982 }
chaviw8b3871a2017-11-01 17:41:01 -07003983 }
3984 if (what & layer_state_t::eReparentChildren) {
3985 if (layer->reparentChildren(s.reparentHandle)) {
3986 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003987 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003988 }
chaviw8b3871a2017-11-01 17:41:01 -07003989 if (what & layer_state_t::eDetachChildren) {
3990 layer->detachChildren();
3991 }
3992 if (what & layer_state_t::eOverrideScalingModeChanged) {
3993 layer->setOverrideScalingMode(s.overrideScalingMode);
3994 // We don't trigger a traversal here because if no other state is
3995 // changed, we don't want this to cause any more work
3996 }
Marissa Wall61c58622018-07-18 10:12:20 -07003997 if (what & layer_state_t::eTransformChanged) {
3998 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4001 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4002 flags |= eTraversalNeeded;
4003 }
4004 if (what & layer_state_t::eCropChanged) {
4005 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4006 }
Marissa Wall861616d2018-10-22 12:52:23 -07004007 if (what & layer_state_t::eFrameChanged) {
4008 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4009 }
Marissa Wall61c58622018-07-18 10:12:20 -07004010 if (what & layer_state_t::eBufferChanged) {
4011 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
4012 }
4013 if (what & layer_state_t::eAcquireFenceChanged) {
4014 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4015 }
4016 if (what & layer_state_t::eDataspaceChanged) {
4017 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4018 }
4019 if (what & layer_state_t::eHdrMetadataChanged) {
4020 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4021 }
4022 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4023 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4024 }
4025 if (what & layer_state_t::eApiChanged) {
4026 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4027 }
4028 if (what & layer_state_t::eSidebandStreamChanged) {
4029 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4030 }
Robert Carr720e5062018-07-30 17:45:14 -07004031 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004032 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4033 layer->setInputInfo(s.inputInfo);
4034 flags |= eTraversalNeeded;
4035 } else {
4036 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4037 }
Robert Carr720e5062018-07-30 17:45:14 -07004038 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004039 if (what & layer_state_t::eMetadataChanged) {
4040 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4041 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004042 std::vector<sp<CallbackHandle>> callbackHandles;
4043 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4044 mTransactionCompletedThread.run();
4045 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4046 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4047 }
4048 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004049 if (what & layer_state_t::eCachedBufferChanged) {
4050 sp<GraphicBuffer> buffer =
4051 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4052 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4053 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004054 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4055 // Do not put anything that updates layer state or modifies flags after
4056 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004057 return flags;
4058}
4059
chaviw273171b2018-12-26 11:46:30 -08004060uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4061 uint32_t flags = 0;
4062 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4063 flags |= eTraversalNeeded;
4064 }
4065
4066 mInputWindowCommands.merge(inputWindowCommands);
4067 return flags;
4068}
4069
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004070status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4071 uint32_t h, PixelFormat format, uint32_t flags,
4072 LayerMetadata metadata, sp<IBinder>* handle,
4073 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004074 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004075 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004076 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004078 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004079
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004080 status_t result = NO_ERROR;
4081
4082 sp<Layer> layer;
4083
Cody Northropbc755282017-03-31 12:00:08 -06004084 String8 uniqueName = getUniqueLayerName(name);
4085
Mathias Agopian3165cc22012-08-08 19:42:09 -07004086 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004087 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004088 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4089 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004092 case ISurfaceComposerClient::eFXSurfaceBufferState:
4093 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4094 break;
chaviw13fdc492017-06-27 12:40:18 -07004095 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004096 // check if buffer size is set for color layer.
4097 if (w > 0 || h > 0) {
4098 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4099 int(w), int(h));
4100 return BAD_VALUE;
4101 }
4102
chaviw13fdc492017-06-27 12:40:18 -07004103 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004104 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004105 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004107 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004108 // check if buffer size is set for container layer.
4109 if (w > 0 || h > 0) {
4110 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4111 int(w), int(h));
4112 return BAD_VALUE;
4113 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004114 result = createContainerLayer(client,
4115 uniqueName, w, h, flags,
4116 handle, &layer);
4117 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004118 default:
4119 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 break;
4121 }
4122
Dan Stoza7d89d062015-04-30 13:29:25 -07004123 if (result != NO_ERROR) {
4124 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004126
Chia-I Wuab0c3192017-08-01 11:29:00 -07004127 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4128 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004129 if (metadata.has(METADATA_WINDOW_TYPE)) {
4130 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4131 if (windowType == 441731) {
4132 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4133 layer->setPrimaryDisplayOnly();
4134 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004135 }
4136
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004137 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004138
Robert Carrb89ea9d2018-12-10 13:01:14 -08004139 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4140 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4141 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004142 if (result != NO_ERROR) {
4143 return result;
4144 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004145 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004146
4147 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149}
4150
Cody Northropbc755282017-03-31 12:00:08 -06004151String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4152{
4153 bool matchFound = true;
4154 uint32_t dupeCounter = 0;
4155
4156 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4157 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4158
Dan Stoza436ccf32018-06-21 12:10:12 -07004159 // Grab the state lock since we're accessing mCurrentState
4160 Mutex::Autolock lock(mStateLock);
4161
Cody Northropbc755282017-03-31 12:00:08 -06004162 // Loop over layers until we're sure there is no matching name
4163 while (matchFound) {
4164 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004166 if (layer->getName() == uniqueName) {
4167 matchFound = true;
4168 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4169 }
4170 });
4171 }
4172
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004173 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4174 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004175
4176 return uniqueName;
4177}
4178
Marissa Wallfd668622018-05-10 10:21:13 -07004179status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4180 uint32_t w, uint32_t h, uint32_t flags,
4181 PixelFormat& format, sp<IBinder>* handle,
4182 sp<IGraphicBufferProducer>* gbp,
4183 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004185 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 case PIXEL_FORMAT_TRANSPARENT:
4187 case PIXEL_FORMAT_TRANSLUCENT:
4188 format = PIXEL_FORMAT_RGBA_8888;
4189 break;
4190 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004191 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 break;
4193 }
4194
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004195 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004196 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004197 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004199 *handle = layer->getHandle();
4200 *gbp = layer->getProducer();
4201 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203
Marissa Wallfd668622018-05-10 10:21:13 -07004204 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004205 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206}
4207
Marissa Wall61c58622018-07-18 10:12:20 -07004208status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4209 uint32_t w, uint32_t h, uint32_t flags,
4210 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004211 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004212 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004213 *handle = layer->getHandle();
4214 *outLayer = layer;
4215
4216 return NO_ERROR;
4217}
4218
chaviw13fdc492017-06-27 12:40:18 -07004219status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004220 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004221 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004223 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004224 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004225 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004226}
4227
Robert Carr6b3f6c52018-08-13 13:05:17 -07004228status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4229 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4230 sp<IBinder>* handle, sp<Layer>* outLayer)
4231{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004232 *outLayer =
4233 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004234 *handle = (*outLayer)->getHandle();
4235 return NO_ERROR;
4236}
4237
4238
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004239void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004240 mLayersPendingRemoval.add(layer);
4241 mLayersRemoved = true;
4242 setTransactionFlags(eTransactionNeeded);
4243}
4244
Robert Carr695d5282018-12-18 15:27:58 -08004245void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004246{
Robert Carr2e102c92018-10-23 12:11:15 -07004247 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004248 // If a layer has a parent, we allow it to out-live it's handle
4249 // with the idea that the parent holds a reference and will eventually
4250 // be cleaned up. However no one cleans up the top-level so we do so
4251 // here.
4252 if (layer->getParent() == nullptr) {
4253 mCurrentState.layersSortedByZ.remove(layer);
4254 }
4255 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004256 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004257}
4258
Mathias Agopianb60314a2012-04-10 22:09:54 -07004259// ---------------------------------------------------------------------------
4260
Andy McFadden13a082e2012-08-24 10:16:42 -07004261void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004262 const auto display = getDefaultDisplayDeviceLocked();
4263 if (!display) return;
4264
4265 const sp<IBinder> token = display->getDisplayToken().promote();
4266 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004267
Jesse Hall01e29052013-02-19 16:13:35 -08004268 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004269 Vector<ComposerState> state;
4270 Vector<DisplayState> displays;
4271 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004272 d.what = DisplayState::eDisplayProjectionChanged |
4273 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004274 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004275 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004276 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004277 d.frame.makeInvalid();
4278 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004279 d.width = 0;
4280 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004281 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004282 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004283
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004285
Dominik Laskowski83b88212018-12-11 13:34:06 -08004286 const nsecs_t vsyncPeriod = getVsyncPeriod();
4287 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004288
Brian Andersond0010582017-03-07 13:20:31 -08004289 // Use phase of 0 since phase is not known.
4290 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004291 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004292 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004293}
4294
4295void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004296 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004297 postMessageAsync(
4298 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004299}
4300
Dominik Laskowskie9774092018-12-11 10:04:24 -08004301void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 if (display->isVirtual()) {
4303 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304 return;
4305 }
4306
Dominik Laskowski075d3172018-05-24 15:50:06 -07004307 const auto displayId = display->getId();
4308 LOG_ALWAYS_FATAL_IF(!displayId);
4309
Dominik Laskowski34157762018-10-31 13:07:19 -07004310 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311
4312 int currentMode = display->getPowerMode();
4313 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004314 return;
4315 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 display->setPowerMode(mode);
4318
Lloyd Pique4dccc412018-01-22 17:21:36 -08004319 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004320 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004321 }
4322
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004324 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004327 if (mUseScheduler) {
4328 mScheduler->onScreenAcquired(mAppConnectionHandle);
4329 } else {
4330 mEventThread->onScreenAcquired();
4331 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004332 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004333 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004334
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004335 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004336 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004337 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004338
4339 struct sched_param param = {0};
4340 param.sched_priority = 1;
4341 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4342 ALOGW("Couldn't set SCHED_FIFO on display on");
4343 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004344 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004345 // Turn off the display
4346 struct sched_param param = {0};
4347 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4348 ALOGW("Couldn't set SCHED_OTHER on display off");
4349 }
4350
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004351 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004352 if (mUseScheduler) {
4353 mScheduler->disableHardwareVsync(true);
4354 } else {
4355 disableHardwareVsync(true); // also cancels any in-progress resync
4356 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004357 if (mUseScheduler) {
4358 mScheduler->onScreenReleased(mAppConnectionHandle);
4359 } else {
4360 mEventThread->onScreenReleased();
4361 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004362 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004363
Dominik Laskowski075d3172018-05-24 15:50:06 -07004364 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004365 mVisibleRegionsDirty = true;
4366 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004367 } else if (mode == HWC_POWER_MODE_DOZE ||
4368 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004369 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004370 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004372 if (mUseScheduler) {
4373 mScheduler->onScreenAcquired(mAppConnectionHandle);
4374 } else {
4375 mEventThread->onScreenAcquired();
4376 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004377 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004378 }
4379 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4380 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004382 if (mUseScheduler) {
4383 mScheduler->disableHardwareVsync(true);
4384 } else {
4385 disableHardwareVsync(true); // also cancels any in-progress resync
4386 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004387 if (mUseScheduler) {
4388 mScheduler->onScreenReleased(mAppConnectionHandle);
4389 } else {
4390 mEventThread->onScreenReleased();
4391 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004392 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004393 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004394 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004395 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004396 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004397 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004398
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004399 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004400 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004401 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004402 // Update refresh rate stats.
4403 mRefreshRateStats->setPowerMode(mode);
4404 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004405 }
4406
Dominik Laskowski34157762018-10-31 13:07:19 -07004407 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004408}
4409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004411 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004412 const auto display = getDisplayDevice(displayToken);
4413 if (!display) {
4414 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4415 displayToken.get());
4416 } else if (display->isVirtual()) {
4417 ALOGW("Attempt to set power mode %d for virtual display", mode);
4418 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004419 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004420 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004422}
4423
4424// ---------------------------------------------------------------------------
4425
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4427 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004429
Mathias Agopianbd115332013-04-18 16:41:04 -07004430 IPCThreadState* ipc = IPCThreadState::self();
4431 const int pid = ipc->getCallingPid();
4432 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004433
Mathias Agopianbd115332013-04-18 16:41:04 -07004434 if ((uid != AID_SHELL) &&
4435 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4437 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004439 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004440 // (this would indicate SF is stuck, but we want to be able to
4441 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004442 status_t err = mStateLock.timedLock(s2ns(1));
4443 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004444 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result,
4446 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4447 "(no locks held)\n",
4448 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004449 }
4450
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004452
Dominik Laskowskic2867142019-01-21 11:33:38 -08004453 static const std::unordered_map<std::string, Dumper> dumpers = {
4454 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4455 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4456 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4457 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4458 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4459 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4460 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4461 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4462 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4463 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4464 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4465 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4466 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004467 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004468 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4469 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004472
Dominik Laskowskic2867142019-01-21 11:33:38 -08004473 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4474 (it->second)(args, asProto, result);
4475 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004476 if (asProto) {
4477 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4478 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4479 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004481 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004482 }
4483
Mathias Agopian9795c422009-08-26 16:36:26 -07004484 if (locked) {
4485 mStateLock.unlock();
4486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004489 return NO_ERROR;
4490}
4491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 mCurrentState.traverseInZOrder(
4494 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004495}
4496
Dominik Laskowskic2867142019-01-21 11:33:38 -08004497void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004498 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004499
Dominik Laskowskic2867142019-01-21 11:33:38 -08004500 if (args.size() > 1) {
4501 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004502 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004503 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004504 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004505 }
Robert Carr2047fae2016-11-28 14:09:09 -08004506 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004507 } else {
4508 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509 }
4510}
4511
Dominik Laskowskic2867142019-01-21 11:33:38 -08004512void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004513 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004514 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004515 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004516 }
Robert Carr2047fae2016-11-28 14:09:09 -08004517 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004518
Svetoslavd85084b2014-03-20 10:28:31 -07004519 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004520}
4521
Dominik Laskowskic2867142019-01-21 11:33:38 -08004522void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4523 mTimeStats->parseArgs(asProto, args, result);
4524}
4525
Jamie Gennis6547ff42013-07-16 20:12:42 -07004526// This should only be called from the main thread. Otherwise it would need
4527// the lock and should use mCurrentState rather than mDrawingState.
4528void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004530 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004531 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004532
4533 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4534}
4535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004537 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004538
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004539 if (isLayerTripleBufferingDisabled())
4540 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4543 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4544 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4545 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4546 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4547 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004548 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004549}
4550
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004552 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004553 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004554 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004555 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004556
4557 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4558
4559 if (mUseScheduler) {
4560 mScheduler->dump(mAppConnectionHandle, result);
4561 } else {
4562 mEventThread->dump(result);
4563 }
4564}
4565
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4567 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004568 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4569 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004570 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004571 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004573 }
David Sodman4a36e932017-11-07 14:29:47 -08004574 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004575 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004576 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4578 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004579}
4580
Dan Stozae77c7662016-05-13 11:37:28 -07004581void SurfaceFlinger::recordBufferingStats(const char* layerName,
4582 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004583 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4584 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004585 for (const auto& segment : history) {
4586 if (!segment.usedThirdBuffer) {
4587 stats.twoBufferTime += segment.totalTime;
4588 }
4589 if (segment.occupancyAverage < 1.0f) {
4590 stats.doubleBufferedTime += segment.totalTime;
4591 } else if (segment.occupancyAverage < 2.0f) {
4592 stats.tripleBufferedTime += segment.totalTime;
4593 }
4594 ++stats.numSegments;
4595 stats.totalTime += segment.totalTime;
4596 }
4597}
4598
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4600 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004601
4602 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4603 const size_t count = currentLayers.size();
4604 for (size_t i=0 ; i<count ; i++) {
4605 currentLayers[i]->dumpFrameEvents(result);
4606 }
4607}
4608
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004610 result.append("Buffering stats:\n");
4611 result.append(" [Layer name] <Active time> <Two buffer> "
4612 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004613 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004614 typedef std::tuple<std::string, float, float, float> BufferTuple;
4615 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004616 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004617 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004618 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004619 if (stats.numSegments == 0) {
4620 continue;
4621 }
4622 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4623 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4624 stats.totalTime;
4625 float doubleBufferRatio = static_cast<float>(
4626 stats.doubleBufferedTime) / stats.totalTime;
4627 float tripleBufferRatio = static_cast<float>(
4628 stats.tripleBufferedTime) / stats.totalTime;
4629 sorted.insert({activeTime, {name, twoBufferRatio,
4630 doubleBufferRatio, tripleBufferRatio}});
4631 }
4632 for (const auto& sortedPair : sorted) {
4633 float activeTime = sortedPair.first;
4634 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4636 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004637 }
4638 result.append("\n");
4639}
4640
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004642 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004643 const auto displayId = display->getId();
4644 if (!displayId) {
4645 continue;
4646 }
4647 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004648 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649 continue;
4650 }
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result,
4653 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4654 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004655 uint8_t port;
4656 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004657 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 result.append("no identification data\n");
4659 continue;
4660 }
4661
4662 if (!isEdid(data)) {
4663 result.append("unknown identification data: ");
4664 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004666 }
4667 result.append("\n");
4668 continue;
4669 }
4670
4671 const auto edid = parseEdid(data);
4672 if (!edid) {
4673 result.append("invalid EDID: ");
4674 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004676 }
4677 result.append("\n");
4678 continue;
4679 }
4680
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004682 result.append(edid->displayName.data(), edid->displayName.length());
4683 result.append("\"\n");
4684 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004685}
4686
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4688 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4689 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4690 StringAppendF(&result, "DisplayColorSetting: %s\n",
4691 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004692
4693 // TODO: print out if wide-color mode is active or not
4694
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004695 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004696 const auto displayId = display->getId();
4697 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004698 continue;
4699 }
4700
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004702 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004703 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004705 }
4706
Lloyd Pique32cbe282018-10-19 13:09:22 -07004707 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 StringAppendF(&result, " Current color mode: %s (%d)\n",
4709 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004710 }
4711 result.append("\n");
4712}
4713
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004715 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004716 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4717 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004718 continue;
4719 }
4720
Dominik Laskowski05275f12018-11-01 15:03:24 -07004721 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4723 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004724 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 compositionInfo.dump(result, nullptr);
4726 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004727 }
4728 }
David Sodman7e4ae112018-02-09 15:02:28 -08004729}
4730
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004731LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004732 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004733 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4734 const State& state = useDrawing ? mDrawingState : mCurrentState;
4735 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004736 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004737 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004738 });
4739
4740 return layersProto;
4741}
4742
Lloyd Pique32cbe282018-10-19 13:09:22 -07004743LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004745
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004746 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004747 resolution->set_w(displayDevice.getWidth());
4748 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004749
Lloyd Pique32cbe282018-10-19 13:09:22 -07004750 auto display = displayDevice.getCompositionDisplay();
4751 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004752
Lloyd Pique32cbe282018-10-19 13:09:22 -07004753 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4754 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4755 layersProto.set_global_transform(displayState.orientation);
4756
4757 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004759 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004761 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004762 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004763 }
4764 });
4765
4766 return layersProto;
4767}
4768
Dominik Laskowskic2867142019-01-21 11:33:38 -08004769void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4770 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004771 Colorizer colorizer(colorize);
4772
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773 // figure out if we're stuck somewhere
4774 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004775 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4777
4778 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004779 * Dump library configuration.
4780 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781
4782 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004783 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004784 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004785 appendSfConfigString(result);
4786 appendUiConfigString(result);
4787 appendGuiConfigString(result);
4788 result.append("\n");
4789
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004790 result.append("\nDisplay identification data:\n");
4791 dumpDisplayIdentificationData(result);
4792
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004793 result.append("\nWide-Color information:\n");
4794 dumpWideColorInfo(result);
4795
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004796 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004797 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004798 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004799 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004800 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004801
Andy McFadden41d67d72014-04-25 16:58:34 -07004802 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004803 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004804 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004805 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004806 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004807
Dan Stozab90cf072015-03-05 11:05:59 -08004808 dumpStaticScreenStats(result);
4809 result.append("\n");
4810
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004812
Dan Stozae77c7662016-05-13 11:37:28 -07004813 dumpBufferingStats(result);
4814
Andy McFadden4803b742012-09-24 19:07:20 -07004815 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816 * Dump the visible layer list
4817 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004818 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4820 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4821 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004823
Chia-I Wu2f884132018-09-13 15:17:58 -07004824 {
4825 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4826 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004828 result.append("\n");
4829 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
David Sodman7e4ae112018-02-09 15:02:28 -08004831 result.append("\nFrame-Composition information:\n");
4832 dumpFrameCompositionInfo(result);
4833 result.append("\n");
4834
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004836 * Dump Display state
4837 */
4838
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004840 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004841 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004844 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004845 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004846
4847 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848 * Dump SurfaceFlinger global state
4849 */
4850
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004851 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004852 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004853 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004855 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004856
Dominik Laskowski075d3172018-05-24 15:50:06 -07004857 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004858 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4859 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4861 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004862 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result,
4864 " transaction-flags : %08x\n"
4865 " gpu_to_cpu_unsupported : %d\n",
4866 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004867
Dominik Laskowski075d3172018-05-24 15:50:06 -07004868 if (const auto displayId = getInternalDisplayId();
4869 displayId && getHwComposer().isConnected(*displayId)) {
4870 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result,
4872 " refresh-rate : %f fps\n"
4873 " x-dpi : %f\n"
4874 " y-dpi : %f\n",
4875 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4876 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004877 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004880
Dan Stozae22aec72016-08-01 13:20:59 -07004881 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004882 * Tracing state
4883 */
4884 mTracing.dump(result);
4885 result.append("\n");
4886
4887 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004888 * HWC layer minidump
4889 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004890 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 const auto displayId = display->getId();
4892 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004893 continue;
4894 }
4895
Yiwei Zhang5434a782018-12-05 18:06:32 -08004896 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004897 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004898 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004899 result.append("\n");
4900 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004901
4902 /*
4903 * Dump HWComposer state
4904 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004905 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004906 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004907 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004908 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004910 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911
4912 /*
4913 * Dump gralloc state
4914 */
4915 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4916 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004917
4918 /*
4919 * Dump VrFlinger state if in use.
4920 */
4921 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4922 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004923 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004924 result.append("\n");
4925 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004926
4927 /**
4928 * Scheduler dump state.
4929 */
4930 if (mUseScheduler) {
4931 result.append("\nScheduler state:\n");
4932 result.append(mScheduler->doDump() + "\n");
4933 result.append(mRefreshRateStats->doDump() + "\n");
4934 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935}
4936
Dominik Laskowski075d3172018-05-24 15:50:06 -07004937const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004938 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004940 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004941 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004942 }
4943 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944
Dominik Laskowski34157762018-10-31 13:07:19 -07004945 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004946 static const Vector<sp<Layer>> empty;
4947 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004948}
4949
Keun young Park63f165f2012-08-31 10:53:36 -07004950bool SurfaceFlinger::startDdmConnection()
4951{
4952 void* libddmconnection_dso =
4953 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4954 if (!libddmconnection_dso) {
4955 return false;
4956 }
4957 void (*DdmConnection_start)(const char* name);
4958 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004959 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004960 if (!DdmConnection_start) {
4961 dlclose(libddmconnection_dso);
4962 return false;
4963 }
4964 (*DdmConnection_start)(getServiceName());
4965 return true;
4966}
4967
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968void SurfaceFlinger::updateColorMatrixLocked() {
4969 mat4 colorMatrix;
4970 if (mGlobalSaturationFactor != 1.0f) {
4971 // Rec.709 luma coefficients
4972 float3 luminance{0.213f, 0.715f, 0.072f};
4973 luminance *= 1.0f - mGlobalSaturationFactor;
4974 mat4 saturationMatrix = mat4(
4975 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4976 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4977 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4978 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4979 );
4980 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4981 } else {
4982 colorMatrix = mClientColorMatrix * mDaltonizer();
4983 }
4984
4985 if (mCurrentState.colorMatrix != colorMatrix) {
4986 mCurrentState.colorMatrix = colorMatrix;
4987 mCurrentState.colorMatrixChanged = true;
4988 setTransactionFlags(eTransactionNeeded);
4989 }
4990}
4991
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004992status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004993#pragma clang diagnostic push
4994#pragma clang diagnostic error "-Wswitch-enum"
4995 switch (static_cast<ISurfaceComposerTag>(code)) {
4996 // These methods should at minimum make sure that the client requested
4997 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004998 case BOOT_FINISHED:
4999 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 case CREATE_DISPLAY:
5001 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005002 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005003 case GET_ACTIVE_COLOR_MODE:
5004 case GET_ANIMATION_FRAME_STATS:
5005 case GET_HDR_CAPABILITIES:
5006 case SET_ACTIVE_CONFIG:
5007 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005008 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005009 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005010 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005011 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5012 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005013 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5014 IPCThreadState* ipc = IPCThreadState::self();
5015 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5016 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005017 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 }
Robert Carr1db73f62016-12-21 12:58:51 -08005019 return OK;
5020 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005021 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005022 IPCThreadState* ipc = IPCThreadState::self();
5023 const int pid = ipc->getCallingPid();
5024 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005025 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5026 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005027 return PERMISSION_DENIED;
5028 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005031 // Used by apps to hook Choreographer to SurfaceFlinger.
5032 case CREATE_DISPLAY_EVENT_CONNECTION:
5033 // The following calls are currently used by clients that do not
5034 // request necessary permissions. However, they do not expose any secret
5035 // information, so it is OK to pass them.
5036 case AUTHENTICATE_SURFACE:
5037 case GET_ACTIVE_CONFIG:
5038 case GET_BUILT_IN_DISPLAY:
5039 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005040 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005041 case GET_DISPLAY_CONFIGS:
5042 case GET_DISPLAY_STATS:
5043 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5044 // Calling setTransactionState is safe, because you need to have been
5045 // granted a reference to Client* and Handle* to do anything with it.
5046 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005047 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005048 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005049 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005050 case GET_PROTECTED_CONTENT_SUPPORT:
5051 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005052 case UNCACHE_BUFFER:
5053 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 return OK;
5055 }
5056 case CAPTURE_LAYERS:
5057 case CAPTURE_SCREEN: {
5058 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005059 IPCThreadState* ipc = IPCThreadState::self();
5060 const int pid = ipc->getCallingPid();
5061 const int uid = ipc->getCallingUid();
5062 if ((uid != AID_GRAPHICS) &&
5063 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5064 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5065 return PERMISSION_DENIED;
5066 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067 return OK;
5068 }
5069 // The following codes are deprecated and should never be allowed to access SF.
5070 case CONNECT_DISPLAY_UNUSED:
5071 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5072 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5073 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005074 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005076
5077 // These codes are used for the IBinder protocol to either interrogate the recipient
5078 // side of the transaction for its canonical interface descriptor or to dump its state.
5079 // We let them pass by default.
5080 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5081 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5082 code == IBinder::SYSPROPS_TRANSACTION) {
5083 return OK;
5084 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005085 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005087 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005088 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5089 return OK;
5090 }
5091 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5092 return PERMISSION_DENIED;
5093#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005094}
5095
Ana Krulec13be8ad2018-08-21 02:43:56 +00005096status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5097 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005098 status_t credentialCheck = CheckTransactCodeCredentials(code);
5099 if (credentialCheck != OK) {
5100 return credentialCheck;
5101 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005103 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5104 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005105 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005106 IPCThreadState* ipc = IPCThreadState::self();
5107 const int uid = ipc->getCallingUid();
5108 if (CC_UNLIKELY(uid != AID_SYSTEM
5109 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005110 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005111 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005112 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005113 return PERMISSION_DENIED;
5114 }
5115 int n;
5116 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005117 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005118 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005119 return NO_ERROR;
5120 case 1002: // SHOW_UPDATES
5121 n = data.readInt32();
5122 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005123 invalidateHwcGeometry();
5124 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005127 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005128 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005129 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005130 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005131 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005132 setTransactionFlags(
5133 eTransactionNeeded|
5134 eDisplayTransactionNeeded|
5135 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005136 return NO_ERROR;
5137 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005138 case 1006:{ // send empty update
5139 signalRefresh();
5140 return NO_ERROR;
5141 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005142 case 1008: // toggle use of hw composer
5143 n = data.readInt32();
5144 mDebugDisableHWC = n ? 1 : 0;
5145 invalidateHwcGeometry();
5146 repaintEverything();
5147 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005148 case 1009: // toggle use of transform hint
5149 n = data.readInt32();
5150 mDebugDisableTransformHint = n ? 1 : 0;
5151 invalidateHwcGeometry();
5152 repaintEverything();
5153 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005154 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005155 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 reply->writeInt32(0);
5157 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005158 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005159 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005160 return NO_ERROR;
5161 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005162 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005163 if (!display) {
5164 return NAME_NOT_FOUND;
5165 }
5166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005167 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 return NO_ERROR;
5169 }
5170 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005171 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005172 // daltonize
5173 n = data.readInt32();
5174 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005175 case 1:
5176 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5177 break;
5178 case 2:
5179 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5180 break;
5181 case 3:
5182 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5183 break;
5184 default:
5185 mDaltonizer.setType(ColorBlindnessType::None);
5186 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005187 }
5188 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005189 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005190 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005191 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005192 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005193
5194 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005195 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005196 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005197 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005198 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005199 // apply a color matrix
5200 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005201 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005202 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005203 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005204 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005205 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005206 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005207 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005208 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005209 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005210 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005211
5212 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5213 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005214 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005215 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5216 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5217 }
5218
Chia-I Wu28f320b2018-05-03 11:02:56 -07005219 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005220 return NO_ERROR;
5221 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005222 // This is an experimental interface
5223 // Needs to be shifted to proper binder interface when we productize
5224 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005225 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005226 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005227 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005228 return NO_ERROR;
5229 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005230 case 1017: {
5231 n = data.readInt32();
5232 mForceFullDamage = static_cast<bool>(n);
5233 return NO_ERROR;
5234 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005235 case 1018: { // Modify Choreographer's phase offset
5236 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005237 if (mUseScheduler) {
5238 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5239 } else {
5240 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5241 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005242 return NO_ERROR;
5243 }
5244 case 1019: { // Modify SurfaceFlinger's phase offset
5245 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005246 if (mUseScheduler) {
5247 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5248 } else {
5249 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5250 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005251 return NO_ERROR;
5252 }
Irvel468051e2016-06-13 16:44:44 -07005253 case 1020: { // Layer updates interceptor
5254 n = data.readInt32();
5255 if (n) {
5256 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005257 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005258 }
5259 else{
5260 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005261 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005262 }
5263 return NO_ERROR;
5264 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005265 case 1021: { // Disable HWC virtual displays
5266 n = data.readInt32();
5267 mUseHwcVirtualDisplays = !n;
5268 return NO_ERROR;
5269 }
Romain Guy0147a172017-06-01 13:53:56 -07005270 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005271 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005272 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005273
Chia-I Wu28f320b2018-05-03 11:02:56 -07005274 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005275 return NO_ERROR;
5276 }
Romain Guy54f154a2017-10-24 21:40:32 +01005277 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005278 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005279 invalidateHwcGeometry();
5280 repaintEverything();
5281 return NO_ERROR;
5282 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005283 // Deprecate, use 1030 to check whether the device is color managed.
5284 case 1024: {
5285 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005286 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005287 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005288 n = data.readInt32();
5289 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005290 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005291 mTracing.enable();
5292 doTracing("tracing.enable");
5293 reply->writeInt32(NO_ERROR);
5294 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005295 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005296 status_t err = mTracing.disable();
5297 reply->writeInt32(err);
5298 }
5299 return NO_ERROR;
5300 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005301 case 1026: { // Get layer tracing status
5302 reply->writeBool(mTracing.isEnabled());
5303 return NO_ERROR;
5304 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005305 // Is a DisplayColorSetting supported?
5306 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005307 const auto display = getDefaultDisplayDevice();
5308 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005309 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005310 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005311
5312 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5313 switch (setting) {
5314 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005315 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005316 break;
5317 case DisplayColorSetting::UNMANAGED:
5318 reply->writeBool(true);
5319 break;
5320 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005321 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005322 break;
5323 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005324 reply->writeBool(
5325 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005326 break;
5327 }
5328 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005329 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005330 // Is VrFlinger active?
5331 case 1028: {
5332 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005333 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005334 return NO_ERROR;
5335 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005336 // Is device color managed?
5337 case 1030: {
5338 reply->writeBool(useColorManagement);
5339 return NO_ERROR;
5340 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005341 // Override default composition data space
5342 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5343 // && adb shell stop zygote && adb shell start zygote
5344 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5345 // adb shell stop zygote && adb shell start zygote
5346 case 1031: {
5347 Mutex::Autolock _l(mStateLock);
5348 n = data.readInt32();
5349 if (n) {
5350 n = data.readInt32();
5351 if (n) {
5352 Dataspace dataspace = static_cast<Dataspace>(n);
5353 if (!validateCompositionDataspace(dataspace)) {
5354 return BAD_VALUE;
5355 }
5356 mDefaultCompositionDataspace = dataspace;
5357 }
5358 n = data.readInt32();
5359 if (n) {
5360 Dataspace dataspace = static_cast<Dataspace>(n);
5361 if (!validateCompositionDataspace(dataspace)) {
5362 return BAD_VALUE;
5363 }
5364 mWideColorGamutCompositionDataspace = dataspace;
5365 }
5366 } else {
5367 // restore composition data space.
5368 mDefaultCompositionDataspace = defaultCompositionDataspace;
5369 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5370 }
5371 return NO_ERROR;
5372 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005373 }
5374 }
5375 return err;
5376}
5377
Steven Thomas6d8110b2017-08-31 18:24:21 -07005378void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005379 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005380 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005381}
5382
Ana Krulec7d1d6832018-12-27 11:10:09 -08005383void SurfaceFlinger::repaintEverythingForHWC() {
5384 mRepaintEverything = true;
5385 mEventQueue->invalidateForHWC();
5386}
5387
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5389class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005390public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005391 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5392 ~WindowDisconnector() {
5393 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005394 }
5395
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005396private:
5397 ANativeWindow* mWindow;
5398 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005399};
5400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005401status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005402 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5403 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005404 uint32_t reqWidth, uint32_t reqHeight,
5405 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005406 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005407 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005409 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005410
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005411 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5412
Chia-I Wu20261cb2018-08-23 12:55:44 -07005413 sp<DisplayDevice> display;
5414 {
5415 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005416
Chia-I Wu20261cb2018-08-23 12:55:44 -07005417 display = getDisplayDeviceLocked(displayToken);
5418 if (!display) return BAD_VALUE;
5419
Chia-I Wucb023152018-08-28 12:57:23 -07005420 // set the requested width/height to the logical display viewport size
5421 // by default
5422 if (reqWidth == 0 || reqHeight == 0) {
5423 reqWidth = uint32_t(display->getViewport().width());
5424 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005425 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005426 }
5427
Peiyong Lin0e003c92018-09-17 11:09:51 -07005428 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5429 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005430
5431 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005432 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005433 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5434 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005435}
5436
5437status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005438 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5439 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005440 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005441 ATRACE_CALL();
5442
5443 class LayerRenderArea : public RenderArea {
5444 public:
Robert Carr578038f2018-03-09 12:25:24 -08005445 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005446 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5447 bool childrenOnly)
5448 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005449 mLayer(layer),
5450 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005451 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005452 mFlinger(flinger),
5453 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005454 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005455 Rect getBounds() const override {
5456 const Layer::State& layerState(mLayer->getDrawingState());
5457 return mLayer->getBufferSize(layerState);
5458 }
Marissa Wall61c58622018-07-18 10:12:20 -07005459 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005460 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005461 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005462 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005463 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005464 }
chaviwa76b2712017-09-20 12:02:26 -07005465 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005466 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005467 Rect getSourceCrop() const override {
5468 if (mCrop.isEmpty()) {
5469 return getBounds();
5470 } else {
5471 return mCrop;
5472 }
5473 }
Robert Carr578038f2018-03-09 12:25:24 -08005474 class ReparentForDrawing {
5475 public:
5476 const sp<Layer>& oldParent;
5477 const sp<Layer>& newParent;
5478
5479 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5480 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005481 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005482 }
Robert Carr15eae092018-03-23 13:43:53 -07005483 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005484 };
5485
5486 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005487 const Rect sourceCrop = getSourceCrop();
5488 // no need to check rotation because there is none
5489 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5490 sourceCrop.height() != getReqHeight();
5491
Robert Carr578038f2018-03-09 12:25:24 -08005492 if (!mChildrenOnly) {
5493 mTransform = mLayer->getTransform().inverse();
5494 drawLayers();
5495 } else {
5496 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005497 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005498 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5499 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005500
5501 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5502 drawLayers();
5503 }
5504 }
chaviwa76b2712017-09-20 12:02:26 -07005505
chaviwa76b2712017-09-20 12:02:26 -07005506 private:
chaviw7206d492017-11-10 16:16:12 -08005507 const sp<Layer> mLayer;
5508 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005509
5510 // In the "childrenOnly" case we reparent the children to a screenshot
5511 // layer which has no properties set and which does not draw.
5512 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005513 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005514 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005515
5516 SurfaceFlinger* mFlinger;
5517 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005518 };
5519
5520 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5521 auto parent = layerHandle->owner.promote();
5522
Robert Carr2e102c92018-10-23 12:11:15 -07005523 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005524 ALOGE("captureLayers called with a removed parent");
5525 return NAME_NOT_FOUND;
5526 }
5527
Robert Carr578038f2018-03-09 12:25:24 -08005528 const int uid = IPCThreadState::self()->getCallingUid();
5529 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005530 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005531 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5532 return PERMISSION_DENIED;
5533 }
5534
chaviw7206d492017-11-10 16:16:12 -08005535 Rect crop(sourceCrop);
5536 if (sourceCrop.width() <= 0) {
5537 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005538 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005539 }
5540
5541 if (sourceCrop.height() <= 0) {
5542 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005543 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005544 }
5545
5546 int32_t reqWidth = crop.width() * frameScale;
5547 int32_t reqHeight = crop.height() * frameScale;
5548
Chia-I Wu20261cb2018-08-23 12:55:44 -07005549 // really small crop or frameScale
5550 if (reqWidth <= 0) {
5551 reqWidth = 1;
5552 }
5553 if (reqHeight <= 0) {
5554 reqHeight = 1;
5555 }
5556
Peiyong Lin0e003c92018-09-17 11:09:51 -07005557 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005558
Robert Carr578038f2018-03-09 12:25:24 -08005559 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005560 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5561 if (!layer->isVisible()) {
5562 return;
Robert Carr578038f2018-03-09 12:25:24 -08005563 } else if (childrenOnly && layer == parent.get()) {
5564 return;
chaviwa76b2712017-09-20 12:02:26 -07005565 }
5566 visitor(layer);
5567 });
5568 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005569 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005570}
5571
5572status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5573 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005574 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005575 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005576 bool useIdentityTransform) {
5577 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005578
Peiyong Lin0e003c92018-09-17 11:09:51 -07005579 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005580 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5581 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005582 *outBuffer =
5583 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5584 static_cast<android_pixel_format>(reqPixelFormat), 1,
5585 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005586
5587 // This mutex protects syncFd and captureResult for communication of the return values from the
5588 // main thread back to this Binder thread
5589 std::mutex captureMutex;
5590 std::condition_variable captureCondition;
5591 std::unique_lock<std::mutex> captureLock(captureMutex);
5592 int syncFd = -1;
5593 std::optional<status_t> captureResult;
5594
Robert Carr03480e22018-01-04 16:02:06 -08005595 const int uid = IPCThreadState::self()->getCallingUid();
5596 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5597
Dominik Laskowski8c001672018-05-30 16:52:06 -07005598 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005599 // If there is a refresh pending, bug out early and tell the binder thread to try again
5600 // after the refresh.
5601 if (mRefreshPending) {
5602 ATRACE_NAME("Skipping screenshot for now");
5603 std::unique_lock<std::mutex> captureLock(captureMutex);
5604 captureResult = std::make_optional<status_t>(EAGAIN);
5605 captureCondition.notify_one();
5606 return;
5607 }
5608
5609 status_t result = NO_ERROR;
5610 int fd = -1;
5611 {
5612 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005613 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005614 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5615 useIdentityTransform, forSystem, &fd);
5616 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005617 }
5618
5619 {
5620 std::unique_lock<std::mutex> captureLock(captureMutex);
5621 syncFd = fd;
5622 captureResult = std::make_optional<status_t>(result);
5623 captureCondition.notify_one();
5624 }
5625 });
5626
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005627 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005629 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005630 while (*captureResult == EAGAIN) {
5631 captureResult.reset();
5632 result = postMessageAsync(message);
5633 if (result != NO_ERROR) {
5634 return result;
5635 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005636 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005637 }
5638 result = *captureResult;
5639 }
5640
5641 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005642 sync_wait(syncFd, -1);
5643 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005645
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005646 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005647}
5648
chaviwa76b2712017-09-20 12:02:26 -07005649void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005650 TraverseLayersFunction traverseLayers,
Alec Mouri79108df2019-02-04 19:33:44 +00005651 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005652 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005653
Alec Mouri79108df2019-02-04 19:33:44 +00005654 auto& engine(getRenderEngine());
5655
chaviwa76b2712017-09-20 12:02:26 -07005656 const auto reqWidth = renderArea.getReqWidth();
5657 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005658 const auto sourceCrop = renderArea.getSourceCrop();
5659 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005660
Alec Mouri79108df2019-02-04 19:33:44 +00005661 engine.setOutputDataSpace(renderArea.getReqDataSpace());
5662 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005663
Alec Mouri79108df2019-02-04 19:33:44 +00005664 // make sure to clear all GL error flags
5665 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005666
Alec Mouri79108df2019-02-04 19:33:44 +00005667 // set-up our viewport
5668 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
5669 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005670
chaviw50da5042018-04-09 13:49:37 -07005671 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Alec Mouri79108df2019-02-04 19:33:44 +00005672 // redraw the screen entirely...
5673 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005674
chaviwa76b2712017-09-20 12:02:26 -07005675 traverseLayers([&](Layer* layer) {
Alec Mouri79108df2019-02-04 19:33:44 +00005676 engine.setColorTransform(layer->getColorTransform());
5677 layer->draw(renderArea, useIdentityTransform);
5678 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005679 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005680}
5681
chaviwa76b2712017-09-20 12:02:26 -07005682status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5683 TraverseLayersFunction traverseLayers,
5684 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005685 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005686 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005687 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005688 ATRACE_CALL();
5689
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005690 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005691
5692 traverseLayers([&](Layer* layer) {
5693 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5694 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005695
Robert Carr03480e22018-01-04 16:02:06 -08005696 // We allow the system server to take screenshots of secure layers for
5697 // use in situations like the Screen-rotation animation and place
5698 // the impetus on WindowManager to not persist them.
5699 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005700 ALOGW("FB is protected: PERMISSION_DENIED");
5701 return PERMISSION_DENIED;
5702 }
Alec Mouri79108df2019-02-04 19:33:44 +00005703 auto& engine(getRenderEngine());
5704
5705 // this binds the given EGLImage as a framebuffer for the
5706 // duration of this scope.
5707 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
5708 if (bufferBond.getStatus() != NO_ERROR) {
5709 ALOGE("got ANWB binding error while taking screenshot");
5710 return INVALID_OPERATION;
5711 }
5712
5713 // this will in fact render into our dequeued buffer
5714 // via an FBO, which means we didn't have to create
5715 // an EGLSurface and therefore we're not
5716 // dependent on the context's EGLConfig.
5717 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
5718
5719 base::unique_fd syncFd = engine.flush();
5720 if (syncFd < 0) {
5721 engine.finish();
5722 }
5723 *outSyncFd = syncFd.release();
5724
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005725 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005726}
5727
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005728// ---------------------------------------------------------------------------
5729
Dan Stoza412903f2017-04-27 13:42:17 -07005730void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5731 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005732}
5733
Dan Stoza412903f2017-04-27 13:42:17 -07005734void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5735 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005736}
5737
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005738void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005739 const LayerVector::Visitor& visitor) {
5740 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005741 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005742 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005743 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005744 continue;
5745 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005746 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005747 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005748 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005749 return;
5750 }
chaviwa76b2712017-09-20 12:02:26 -07005751 if (!layer->isVisible()) {
5752 return;
5753 }
5754 visitor(layer);
5755 });
5756 }
5757}
5758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005759}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005760
Lloyd Pique074e8122018-07-26 12:57:23 -07005761
Mathias Agopian3f844832013-08-07 21:24:32 -07005762#if defined(__gl_h_)
5763#error "don't include gl/gl.h in this file"
5764#endif
5765
5766#if defined(__gl2_h_)
5767#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005768#endif