blob: e869d5f78e9efd60ad9c5d8756cb7150ee23135d [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 Mouri0f714832018-11-12 15:31:06 -080017//#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 Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070081#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080082#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070083#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070084#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087
Steven Thomasb02664d2017-07-26 18:48:28 -070088#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070089#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070090#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070091#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070092#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070094#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070095#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/EventControlThread.h"
97#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070098#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070099#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700100#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800101#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102
Mathias Agopianff2ed702013-09-01 21:36:12 -0700103#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700104
David Sodman7e4ae112018-02-09 15:02:28 -0800105#include "android-base/stringprintf.h"
106
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800108#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700109#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900111#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112
chaviw1d044282017-09-27 12:19:28 -0700113#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900114#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800116namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700117
Jaesoo Lee43518572017-01-23 19:03:16 +0900118using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800121using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700122using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700123using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800124using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700125using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700126using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127
Steven Thomasb02664d2017-07-26 18:48:28 -0700128namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700129
130#pragma clang diagnostic push
131#pragma clang diagnostic error "-Wswitch-enum"
132
133bool isWideColorMode(const ColorMode colorMode) {
134 switch (colorMode) {
135 case ColorMode::DISPLAY_P3:
136 case ColorMode::ADOBE_RGB:
137 case ColorMode::DCI_P3:
138 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700139 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700140 case ColorMode::BT2100_PQ:
141 case ColorMode::BT2100_HLG:
142 return true;
143 case ColorMode::NATIVE:
144 case ColorMode::STANDARD_BT601_625:
145 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
146 case ColorMode::STANDARD_BT601_525:
147 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
148 case ColorMode::STANDARD_BT709:
149 case ColorMode::SRGB:
150 return false;
151 }
152 return false;
153}
154
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700155ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
156 switch (rotation) {
157 case ISurfaceComposer::eRotateNone:
158 return ui::Transform::ROT_0;
159 case ISurfaceComposer::eRotate90:
160 return ui::Transform::ROT_90;
161 case ISurfaceComposer::eRotate180:
162 return ui::Transform::ROT_180;
163 case ISurfaceComposer::eRotate270:
164 return ui::Transform::ROT_270;
165 }
166 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
167 return ui::Transform::ROT_0;
168}
169
Peiyong Linfca547f2018-07-09 13:03:33 -0700170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Peiyong Lin9d846a52018-11-05 13:18:20 -0800185// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
186bool validateCompositionDataspace(Dataspace dataspace) {
187 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
188}
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190} // namespace anonymous
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192// ---------------------------------------------------------------------------
193
Mathias Agopian99b49842011-06-27 16:05:52 -0700194const String16 sHardwareTest("android.permission.HARDWARE_TEST");
195const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
196const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
197const String16 sDump("android.permission.DUMP");
198
Daniel Solomon42d04562019-01-20 21:03:19 -0800199constexpr float kSrgbRedX = 0.4123f;
200constexpr float kSrgbRedY = 0.2126f;
201constexpr float kSrgbRedZ = 0.0193f;
202constexpr float kSrgbGreenX = 0.3576f;
203constexpr float kSrgbGreenY = 0.7152f;
204constexpr float kSrgbGreenZ = 0.1192f;
205constexpr float kSrgbBlueX = 0.1805f;
206constexpr float kSrgbBlueY = 0.0722f;
207constexpr float kSrgbBlueZ = 0.9506f;
208constexpr float kSrgbWhiteX = 0.9505f;
209constexpr float kSrgbWhiteY = 1.0000f;
210constexpr float kSrgbWhiteZ = 1.0891f;
211
Mathias Agopian99b49842011-06-27 16:05:52 -0700212// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700213int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800216bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800217bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800218int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600219bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700220int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700221bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700222bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700223Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
225Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
226ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700227
Kalle Raitaa099a242017-01-11 11:17:29 -0800228std::string getHwcServiceName() {
229 char value[PROPERTY_VALUE_MAX] = {};
230 property_get("debug.sf.hwc_service_name", value, "default");
231 ALOGI("Using HWComposer service: '%s'", value);
232 return std::string(value);
233}
234
235bool useTrebleTestingOverride() {
236 char value[PROPERTY_VALUE_MAX] = {};
237 property_get("debug.sf.treble_testing_override", value, "false");
238 ALOGI("Treble testing override: '%s'", value);
239 return std::string(value) == "true";
240}
241
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
243 switch(displayColorSetting) {
244 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800248 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Enhanced");
250 default:
251 return std::string("Unknown ") +
252 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800253 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254}
255
David Sodmanbc815282017-11-05 18:57:52 -0800256SurfaceFlingerBE::SurfaceFlingerBE()
257 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800258 mFrameBuckets(),
259 mTotalTime(0),
260 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800261 mComposerSequenceId(0) {
262}
263
Lloyd Pique90c115d2018-09-18 21:39:42 -0700264SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
265 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800266 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700268 mTransactionPending(false),
269 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700270 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700271 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800273 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800275 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800276 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800277 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700279 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700280 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700281 mDebugInTransaction(0),
282 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700283 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800284 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700285 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700286 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800287 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800288 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800289 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700290 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700291 mMainThreadId(std::this_thread::get_id()),
292 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800293
Lloyd Pique90c115d2018-09-18 21:39:42 -0700294SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
295 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800296 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800305
Steven Thomas050b2c82017-03-06 11:45:16 -0800306 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 mDefaultCompositionDataspace =
316 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
317 mWideColorGamutCompositionDataspace =
318 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
319 defaultCompositionDataspace = mDefaultCompositionDataspace;
320 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
321 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
322 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
323 wideColorGamutCompositionPixelFormat =
324 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700325
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900326 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800327
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
329 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
330 switch (tmpPrimaryDisplayOrientation) {
331 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900337 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
343 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800345
Lloyd Pique90c115d2018-09-18 21:39:42 -0700346 mPrimaryDispSync =
347 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
348 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700349
Daniel Solomon42d04562019-01-20 21:03:19 -0800350 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
351 if (surfaceFlingerConfigsServiceV1_2) {
352 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
353 [&](auto tmpPrimaries) {
354 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
355 });
356 } else {
357 initDefaultDisplayNativePrimaries();
358 }
359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 // debugging stuff...
361 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopianb4b17302013-03-20 18:36:41 -0700363 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700364 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 property_get("debug.sf.showupdates", value, "0");
367 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700369 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000370
371 // DDMS debugging deprecated (b/120782499)
372 property_get("debug.sf.ddms", value, "0");
373 int debugDdms = atoi(value);
374 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700375
376 property_get("debug.sf.disable_backpressure", value, "0");
377 mPropagateBackpressure = !atoi(value);
378 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700379
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800380 property_get("debug.sf.enable_hwc_vds", value, "0");
381 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800382 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800383
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800384 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800385 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800386 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700387
Yiwei Zhang243b3782018-05-15 17:40:04 -0700388 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700389 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
390 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
391
Ana Krulec98b5b242018-08-10 15:03:23 -0700392 property_get("debug.sf.use_scheduler", value, "0");
393 mUseScheduler = atoi(value);
394
Ana Krulec757f63a2019-01-25 10:46:18 -0800395 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
396 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700397
Romain Guy11d63f42017-07-20 12:47:14 -0700398 // We should be reading 'persist.sys.sf.color_saturation' here
399 // but since /data may be encrypted, we need to wait until after vold
400 // comes online to attempt to read the property. The property is
401 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800402
403 if (useTrebleTestingOverride()) {
404 // Without the override SurfaceFlinger cannot connect to HIDL
405 // services that are not listed in the manifests. Considered
406 // deriving the setting from the set service name, but it
407 // would be brittle if the name that's not 'default' is used
408 // for production purposes later on.
409 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
410 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413void SurfaceFlinger::onFirstRef()
414{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800415 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418SurfaceFlinger::~SurfaceFlinger()
419{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420}
421
Dan Stozac7014012014-02-14 15:03:43 -0800422void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423{
424 // the window manager died on us. prepare its eulogy.
425
Andy McFadden13a082e2012-08-24 10:16:42 -0700426 // restore initial conditions (default device unblank, etc)
427 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428
429 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700430 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431}
432
Robert Carr1db73f62016-12-21 12:58:51 -0800433static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700434 status_t err = client->initCheck();
435 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800436 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 }
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return nullptr;
439}
440
441sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
442 return initClient(new Client(this));
443}
444
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700445sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
446 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447{
448 class DisplayToken : public BBinder {
449 sp<SurfaceFlinger> flinger;
450 virtual ~DisplayToken() {
451 // no more references, this display must be terminated
452 Mutex::Autolock _l(flinger->mStateLock);
453 flinger->mCurrentState.displays.removeItem(this);
454 flinger->setTransactionFlags(eDisplayTransactionNeeded);
455 }
456 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700457 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 : flinger(flinger) {
459 }
460 };
461
462 sp<BBinder> token = new DisplayToken(this);
463
464 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 // Display ID is assigned when virtual display is allocated by HWC.
466 DisplayDeviceState state;
467 state.isSecure = secure;
468 state.displayName = displayName;
469 mCurrentState.displays.add(token, state);
470 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 return token;
472}
473
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700474void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 Mutex::Autolock _l(mStateLock);
476
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
478 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 return;
481 }
482
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
484 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 ALOGE("destroyDisplay called for non-virtual display");
486 return;
487 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 mInterceptor->saveDisplayDeletion(state.sequenceId);
489 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 setTransactionFlags(eDisplayTransactionNeeded);
491}
492
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 std::optional<DisplayId> displayId;
495
496 if (id == HWC_DISPLAY_PRIMARY) {
497 displayId = getInternalDisplayId();
498 } else if (id == HWC_DISPLAY_EXTERNAL) {
499 displayId = getExternalDisplayId();
500 }
501
502 if (!displayId) {
503 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800504 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506
507 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508}
509
Ady Abraham37965d42018-11-01 13:43:32 -0700510status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
511 if (!outGetColorManagement) {
512 return BAD_VALUE;
513 }
514 *outGetColorManagement = useColorManagement;
515 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700516}
517
Lloyd Pique441d5042018-10-18 16:49:51 -0700518HWComposer& SurfaceFlinger::getHwComposer() const {
519 return mCompositionEngine->getHwComposer();
520}
521
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700522renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
523 return mCompositionEngine->getRenderEngine();
524}
525
Lloyd Pique70d91362018-10-18 16:02:55 -0700526compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
527 return *mCompositionEngine.get();
528}
529
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530void SurfaceFlinger::bootFinished()
531{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700532 if (mStartPropertySetThread->join() != NO_ERROR) {
533 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535 const nsecs_t now = systemTime();
536 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000537 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538
539 // wait patiently for the window manager death
540 const String16 name("window");
541 sp<IBinder> window(defaultServiceManager()->getService(name));
542 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700543 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544 }
Robert Carr720e5062018-07-30 17:45:14 -0700545 sp<IBinder> input(defaultServiceManager()->getService(
546 String16("inputflinger")));
547 if (input == nullptr) {
548 ALOGE("Failed to link to input service");
549 } else {
550 mInputFlinger = interface_cast<IInputFlinger>(input);
551 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552
Steven Thomas050b2c82017-03-06 11:45:16 -0800553 if (mVrFlinger) {
554 mVrFlinger->OnBootFinished();
555 }
556
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700558 // formerly we would just kill the process, but we now ask it to exit so it
559 // can choose where to stop the animation.
560 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700561
562 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
563 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
564 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700565
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 postMessageAsync(new LambdaMessage([this] {
567 readPersistentProperties();
568 mBootStage = BootStage::FINISHED;
569 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800570}
571
Dan Stoza436ccf32018-06-21 12:10:12 -0700572uint32_t SurfaceFlinger::getNewTexture() {
573 {
574 std::lock_guard lock(mTexturePoolMutex);
575 if (!mTexturePool.empty()) {
576 uint32_t name = mTexturePool.back();
577 mTexturePool.pop_back();
578 ATRACE_INT("TexturePoolSize", mTexturePool.size());
579 return name;
580 }
581
582 // The pool was too small, so increase it for the future
583 ++mTexturePoolSize;
584 }
585
586 // The pool was empty, so we need to get a new texture name directly using a
587 // blocking call to the main thread
588 uint32_t name = 0;
589 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
590 return name;
591}
592
Mathias Agopian3f844832013-08-07 21:24:32 -0700593void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700594 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700595}
596
Wei Wangf9b05ee2017-07-19 20:59:39 -0700597// Do not call property_set on main thread which will be blocked by init
598// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700600 ALOGI( "SurfaceFlinger's main thread ready to run. "
601 "Initializing graphics H/W...");
602
Ana Krulec757f63a2019-01-25 10:46:18 -0800603 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606
Dominik Laskowski83b88212018-12-11 13:34:06 -0800607 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700610 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700611 mScheduler = getFactory().createScheduler([this](bool enabled) {
612 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
613 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800614 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
615 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
616 mPhaseOffsets->setRefreshRateType(
617 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700618
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800620 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800621 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700622 impl::EventThread::InterceptVSyncsCallback());
623 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800624 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800625 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mInterceptor->saveVSyncEvent(timestamp);
627 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800628
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700630 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
631 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 } else {
633 mEventThreadSource =
634 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800635 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 mEventThread =
637 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800642 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 [this](nsecs_t timestamp) {
647 mInterceptor->saveVSyncEvent(timestamp);
648 },
649 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800650 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
652 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653
Steven Thomasb02664d2017-07-26 18:48:28 -0700654 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700655 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700656 renderEngineFeature |= (useColorManagement ?
657 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700658 renderEngineFeature |= (useContextPriority ?
659 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700660
661 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700662 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700663 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700665
666 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
667 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700668 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
669 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800670 // Process any initial hotplug and resulting display changes.
671 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 const auto display = getDefaultDisplayDeviceLocked();
673 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700674 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800676
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700679 // This callback is called from the vr flinger dispatch thread. We
680 // need to call signalTransaction(), which requires holding
681 // mStateLock when we're not on the main thread. Acquiring
682 // mStateLock from the vr flinger dispatch thread might trigger a
683 // deadlock in surface flinger (see b/66916578), so post a message
684 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
687 mVrFlingerRequestsDisplay = requestDisplay;
688 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
692 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 .value_or(0),
695 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (!mVrFlinger) {
697 ALOGE("Failed to start vrflinger");
698 }
699 }
700
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700702 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700703
Mathias Agopian92a979a2012-08-02 18:32:23 -0700704 // initialize our drawing state
705 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700706
Andy McFadden13a082e2012-08-24 10:16:42 -0700707 // set initial conditions (e.g. unblank default device)
708 initializeDisplays();
709
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700710 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700713
714 const bool presentFenceReliable =
715 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
716 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717
718 if (mStartPropertySetThread->Start() != NO_ERROR) {
719 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Ana Krulec7d1d6832018-12-27 11:10:09 -0800722 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800723 mScheduler->setExpiredIdleTimerCallback([this]() {
724 mPhaseOffsets->setRefreshRateType(
725 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
726 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
727 mVsyncModulator.setPhaseOffsets(early, gl, late);
728 setRefreshRateTo(60.f /* fps */);
729 });
730 mScheduler->setResetIdleTimerCallback([this]() {
731 mPhaseOffsets->setRefreshRateType(
732 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
733 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
734 mVsyncModulator.setPhaseOffsets(early, gl, late);
735 setRefreshRateTo(90.f /* fps */);
736 });
Ana Krulecb43429d2019-01-09 14:28:51 -0800737 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
738 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800739 }
740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700742}
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 Mutex::Autolock _l(mStateLock);
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747 char value[PROPERTY_VALUE_MAX];
748
749 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100753
754 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700755 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700756}
757
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Start boot animation service by setting a property mailbox
760 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 if (mStartPropertySetThread->join() != NO_ERROR) {
764 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800776// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800777
Jamie Gennis582270d2011-08-17 18:19:00 -0700778bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800779 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800780 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800781 return authenticateSurfaceTextureLocked(bufferProducer);
782}
783
784bool SurfaceFlinger::authenticateSurfaceTextureLocked(
785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800786 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800787 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800788}
789
Brian Anderson6b376712017-04-04 10:51:39 -0700790status_t SurfaceFlinger::getSupportedFrameTimestamps(
791 std::vector<FrameEvent>* outSupported) const {
792 *outSupported = {
793 FrameEvent::REQUESTED_PRESENT,
794 FrameEvent::ACQUIRE,
795 FrameEvent::LATCH,
796 FrameEvent::FIRST_REFRESH_START,
797 FrameEvent::LAST_REFRESH_START,
798 FrameEvent::GPU_COMPOSITION_DONE,
799 FrameEvent::DEQUEUE_READY,
800 FrameEvent::RELEASE,
801 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700804 if (!getHwComposer().hasCapability(
805 HWC2::Capability::PresentFenceIsNotReliable)) {
806 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
807 }
808 return NO_ERROR;
809}
810
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
812 Vector<DisplayInfo>* configs) {
813 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 const auto displayId = getPhysicalDisplayId(displayToken);
818 if (!displayId) {
819 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700820 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 // TODO: Not sure if display density should handled by SF any longer
823 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700826 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800827 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 }
830 return density;
831 }
832 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("ro.sf.lcd_density"); }
837 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Steven Thomas6d8110b2017-08-31 18:24:21 -0700841 ConditionalLock _l(mStateLock,
842 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 DisplayInfo info = DisplayInfo();
845
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 float xdpi = hwConfig->getDpiX();
847 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
851 // Default display viewport to display width and height
852 info.viewportW = info.w;
853 info.viewportH = info.h;
854
Dominik Laskowski075d3172018-05-24 15:50:06 -0700855 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 // The density of the device is provided by a build property
857 float density = Density::getBuildDensity() / 160.0f;
858 if (density == 0) {
859 // the build doesn't provide a density -- this is wrong!
860 // use xdpi instead
861 ALOGE("ro.sf.lcd_density must be defined as a build property");
862 density = xdpi / 160.0f;
863 }
864 if (Density::getEmuDensity()) {
865 // if "qemu.sf.lcd_density" is specified, it overrides everything
866 xdpi = ydpi = density = Density::getEmuDensity();
867 density /= 160.0f;
868 }
869 info.density = density;
870
871 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872 const auto display = getDefaultDisplayDeviceLocked();
873 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700874
875 // This is for screenrecord
876 const Rect viewport = display->getViewport();
877 if (viewport.isValid()) {
878 info.viewportW = uint32_t(viewport.getWidth());
879 info.viewportH = uint32_t(viewport.getHeight());
880 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 } else {
882 // TODO: where should this value come from?
883 static const int TV_DENSITY = 213;
884 info.density = TV_DENSITY / 160.0f;
885 info.orientation = 0;
886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 info.xdpi = xdpi;
889 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800891 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892
Andy McFadden91b2ca82014-06-13 14:04:23 -0700893 // This is how far in advance a buffer must be queued for
894 // presentation at a given time. If you want a buffer to appear
895 // on the screen at time N, you must submit the buffer before
896 // (N - presentationDeadline).
897 //
898 // Normally it's one full refresh period (to give SF a chance to
899 // latch the buffer), but this can be reduced by configuring a
900 // DispSync offset. Any additional delays introduced by the hardware
901 // composer or panel must be accounted for here.
902 //
903 // We add an additional 1ms to allow for processing time and
904 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800905 info.presentationDeadline =
906 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907
908 // All non-virtual displays are currently considered secure.
909 info.secure = true;
910
Dominik Laskowski075d3172018-05-24 15:50:06 -0700911 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700912 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800913 std::swap(info.w, info.h);
914 }
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700917 }
918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 return NO_ERROR;
920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
923 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
Ana Krulece588e312018-09-18 12:32:24 -0700927 if (mUseScheduler) {
928 mScheduler->getDisplayStatInfo(stats);
929 } else {
930 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
931 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
932 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700933 return NO_ERROR;
934}
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
937 const auto display = getDisplayDevice(displayToken);
938 if (!display) {
939 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800940 return BAD_VALUE;
941 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Ana Krulec7d1d6832018-12-27 11:10:09 -0800946status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
947 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800948 postMessageAsync(new LambdaMessage(
949 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950 return NO_ERROR;
951}
952
953status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
954 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800955 postMessageSync(new LambdaMessage(
956 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800957 return NO_ERROR;
958}
959
960void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
961 Vector<DisplayInfo> configs;
962 getDisplayConfigs(displayToken, &configs);
963 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
964 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
965 return;
966 }
967
968 const auto display = getDisplayDevice(displayToken);
969 if (!display) {
970 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
971 displayToken.get());
972 return;
973 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700974 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800975 ALOGW("Attempt to set active config %d for virtual display", mode);
976 return;
977 }
978 int currentDisplayPowerMode = display->getPowerMode();
979 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
980 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700981 return;
982 }
983
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700984 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700985 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800986 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987 return;
988 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800989 if (mUseScheduler) {
990 mRefreshRateStats->setConfigMode(mode);
991 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700992
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993 const auto displayId = display->getId();
994 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998
Ana Krulec7d1d6832018-12-27 11:10:09 -0800999 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001000 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001001}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1004 Vector<ColorMode>* outColorModes) {
1005 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001006 return BAD_VALUE;
1007 }
1008
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009 const auto displayId = getPhysicalDisplayId(displayToken);
1010 if (!displayId) {
1011 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001012 }
1013
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001015 {
1016 ConditionalLock _l(mStateLock,
1017 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001018 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001019 }
Michael Wright28f24d02016-07-12 13:30:53 -07001020 outColorModes->clear();
1021 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1022
1023 return NO_ERROR;
1024}
1025
Daniel Solomon42d04562019-01-20 21:03:19 -08001026status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1027 ui::DisplayPrimaries &primaries) {
1028 if (!displayToken) {
1029 return BAD_VALUE;
1030 }
1031
1032 // Currently we only support this API for a single internal display.
1033 if (getInternalDisplayToken() != displayToken) {
1034 return BAD_VALUE;
1035 }
1036
1037 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1038 return NO_ERROR;
1039}
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1042 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001043 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001044 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001046}
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001049 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 Vector<ColorMode> modes;
1051 getDisplayColorModes(displayToken, &modes);
1052 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1053 if (mode < ColorMode::NATIVE || !exists) {
1054 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1055 decodeColorMode(mode).c_str(), mode, displayToken.get());
1056 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 const auto display = getDisplayDevice(displayToken);
1059 if (!display) {
1060 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 } else if (display->isVirtual()) {
1063 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1064 decodeColorMode(mode).c_str(), mode);
1065 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001066 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1067 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 }
1069 }));
1070
Michael Wright28f24d02016-07-12 13:30:53 -07001071 return NO_ERROR;
1072}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001073
Svetoslavd85084b2014-03-20 10:28:31 -07001074status_t SurfaceFlinger::clearAnimationFrameStats() {
1075 Mutex::Autolock _l(mStateLock);
1076 mAnimFrameTracker.clearStats();
1077 return NO_ERROR;
1078}
1079
1080status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.getStats(outStats);
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1087 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 Mutex::Autolock _l(mStateLock);
1089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090 const auto display = getDisplayDeviceLocked(displayToken);
1091 if (!display) {
1092 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 return BAD_VALUE;
1094 }
1095
Peiyong Linfb069302018-04-25 14:34:31 -07001096 // At this point the DisplayDeivce should already be set up,
1097 // meaning the luminance information is already queried from
1098 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001100 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1101 capabilities.getDesiredMaxLuminance(),
1102 capabilities.getDesiredMaxAverageLuminance(),
1103 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001104
1105 return NO_ERROR;
1106}
1107
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001108status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1109 ui::PixelFormat* outFormat,
1110 ui::Dataspace* outDataspace,
1111 uint8_t* outComponentMask) const {
1112 if (!outFormat || !outDataspace || !outComponentMask) {
1113 return BAD_VALUE;
1114 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001115 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001116 if (!display || !display->getId()) {
1117 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1118 return BAD_VALUE;
1119 }
1120 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1121 outDataspace, outComponentMask);
1122}
1123
Kevin DuBois74e53772018-11-19 10:52:38 -08001124status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1125 bool enable, uint8_t componentMask,
1126 uint64_t maxFrames) const {
1127 const auto display = getDisplayDevice(displayToken);
1128 if (!display || !display->getId()) {
1129 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1130 return BAD_VALUE;
1131 }
1132
1133 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1134 componentMask, maxFrames);
1135}
1136
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001137status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1138 uint64_t maxFrames, uint64_t timestamp,
1139 DisplayedFrameStats* outStats) const {
1140 const auto display = getDisplayDevice(displayToken);
1141 if (!display || !display->getId()) {
1142 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1143 return BAD_VALUE;
1144 }
1145
1146 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1147 outStats);
1148}
1149
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001150status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1151 if (!outSupported) {
1152 return BAD_VALUE;
1153 }
1154 *outSupported = getRenderEngine().supportsProtectedContent();
1155 return NO_ERROR;
1156}
1157
Marissa Wallebc2c052019-01-16 19:16:55 -08001158status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1159 int32_t* outBufferId) {
1160 if (!outBufferId) {
1161 return BAD_VALUE;
1162 }
1163 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1164 return NO_ERROR;
1165}
1166
1167status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1168 mBufferStateLayerCache.release(token, bufferId);
1169 return NO_ERROR;
1170}
1171
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001172status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1173 bool* outIsWideColorDisplay) const {
1174 if (!displayToken || !outIsWideColorDisplay) {
1175 return BAD_VALUE;
1176 }
1177 Mutex::Autolock _l(mStateLock);
1178 const auto display = getDisplayDeviceLocked(displayToken);
1179 if (!display) {
1180 return BAD_VALUE;
1181 }
1182 *outIsWideColorDisplay = display->hasWideColorGamut();
1183 return NO_ERROR;
1184}
1185
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001186status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001187 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189
Chia-I Wu90f669f2017-10-05 14:24:41 -07001190 if (mInjectVSyncs == enable) {
1191 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001192 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001193
Dominik Laskowski83b88212018-12-11 13:34:06 -08001194 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001195
Ana Krulec98b5b242018-08-10 15:03:23 -07001196 // TODO(akrulec): Part of the Injector should be refactored, so that it
1197 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198 if (enable) {
1199 ALOGV("VSync Injections enabled");
1200 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001201 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001202 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001203 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001204 impl::EventThread::InterceptVSyncsCallback(),
1205 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001206 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001207 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 } else {
1209 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001210 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001211 }
1212
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001213 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001214 }));
1215
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001216 return NO_ERROR;
1217}
1218
1219status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001220 Mutex::Autolock _l(mStateLock);
1221
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001222 if (!mInjectVSyncs) {
1223 ALOGE("VSync Injections not enabled");
1224 return BAD_VALUE;
1225 }
1226 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1227 ALOGV("Injecting VSync inside SurfaceFlinger");
1228 mVSyncInjector->onInjectSyncEvent(when);
1229 }
1230 return NO_ERROR;
1231}
1232
Lloyd Pique755e3192018-01-31 16:46:15 -08001233status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1234 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001235 // Try to acquire a lock for 1s, fail gracefully
1236 const status_t err = mStateLock.timedLock(s2ns(1));
1237 const bool locked = (err == NO_ERROR);
1238 if (!locked) {
1239 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1240 return TIMED_OUT;
1241 }
1242
1243 outLayers->clear();
1244 mCurrentState.traverseInZOrder([&](Layer* layer) {
1245 outLayers->push_back(layer->getLayerDebugInfo());
1246 });
1247
1248 mStateLock.unlock();
1249 return NO_ERROR;
1250}
1251
Peiyong Linc6780972018-10-28 15:24:08 -07001252status_t SurfaceFlinger::getCompositionPreference(
1253 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1254 Dataspace* outWideColorGamutDataspace,
1255 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001256 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001257 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001258 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001259 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001260 return NO_ERROR;
1261}
1262
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001263// ----------------------------------------------------------------------------
1264
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001265sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1266 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001267 auto resyncCallback = makeResyncCallback([this] {
1268 Mutex::Autolock lock(mStateLock);
1269 return getVsyncPeriod();
1270 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001271
Ana Krulec98b5b242018-08-10 15:03:23 -07001272 if (mUseScheduler) {
1273 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001275 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001276 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001277 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001278 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001279 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001280 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001281 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001282 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001283 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001284 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001285}
1286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288
1289void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001290 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001291}
1292
1293void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001294 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001295}
1296
1297void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001298 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001299}
1300
1301void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001302 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001303 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001304}
1305
1306status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001307 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001308 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001309}
1310
1311status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001312 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001313 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314 if (res == NO_ERROR) {
1315 msg->wait();
1316 }
1317 return res;
1318}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001319
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001320void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001321 do {
1322 waitForEvent();
1323 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324}
1325
Dominik Laskowski83b88212018-12-11 13:34:06 -08001326nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1327 const auto displayId = getInternalDisplayId();
1328 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1329 return 0;
1330 }
1331
1332 const auto config = getHwComposer().getActiveConfig(*displayId);
1333 return config ? config->getVsyncPeriod() : 0;
1334}
1335
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336void SurfaceFlinger::enableHardwareVsync() {
1337 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001339 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001342 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343}
1344
Dominik Laskowski83b88212018-12-11 13:34:06 -08001345void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 Mutex::Autolock _l(mHWVsyncLock);
1347
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348 if (makeAvailable) {
1349 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001350 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1351 if (mUseScheduler) {
1352 mScheduler->makeHWSyncAvailable(true);
1353 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001354 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001355 // Hardware vsync is not currently available, so abort the resync
1356 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001357 return;
1358 }
1359
Dominik Laskowski83b88212018-12-11 13:34:06 -08001360 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001361 return;
1362 }
1363
Ana Krulece588e312018-09-18 12:32:24 -07001364 if (mUseScheduler) {
1365 mScheduler->setVsyncPeriod(period);
1366 } else {
1367 mPrimaryDispSync->reset();
1368 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369
Ana Krulece588e312018-09-18 12:32:24 -07001370 if (!mPrimaryHWVsyncEnabled) {
1371 mPrimaryDispSync->beginResync();
1372 mEventControlThread->setVsyncEnabled(true);
1373 mPrimaryHWVsyncEnabled = true;
1374 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375 }
1376}
1377
Jesse Hall948fe0c2013-10-14 12:56:09 -07001378void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379 Mutex::Autolock _l(mHWVsyncLock);
1380 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001381 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001382 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 mPrimaryHWVsyncEnabled = false;
1384 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001385 if (makeUnavailable) {
1386 mHWVsyncAvailable = false;
1387 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001388}
1389
Dominik Laskowski83b88212018-12-11 13:34:06 -08001390void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001391 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001392
Dan Stoza57164302017-05-08 14:03:54 -07001393 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001394 const nsecs_t last = lastResyncTime.exchange(now);
1395
1396 if (now - last > kIgnoreDelay) {
1397 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001398 }
1399}
1400
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001401void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1402 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001403 ATRACE_NAME("SF onVsync");
1404
Steven Thomas3cfac282017-02-06 12:29:30 -08001405 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001407 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 return;
1409 }
1410
Dominik Laskowski075d3172018-05-24 15:50:06 -07001411 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001412 return;
1413 }
1414
Dominik Laskowski075d3172018-05-24 15:50:06 -07001415 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001416 // For now, we don't do anything with external display vsyncs.
1417 return;
1418 }
1419
Ana Krulece588e312018-09-18 12:32:24 -07001420 if (mUseScheduler) {
1421 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001422 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001423 bool needsHwVsync = false;
1424 { // Scope for the lock
1425 Mutex::Autolock _l(mHWVsyncLock);
1426 if (mPrimaryHWVsyncEnabled) {
1427 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1428 }
1429 }
1430
1431 if (needsHwVsync) {
1432 enableHardwareVsync();
1433 } else {
1434 disableHardwareVsync(false);
1435 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001436 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001437}
1438
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001439void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001440 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1441 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001442}
1443
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444void SurfaceFlinger::setRefreshRateTo(float newFps) {
1445 const auto displayId = getInternalDisplayId();
1446 if (!displayId || mBootStage != BootStage::FINISHED) {
1447 return;
1448 }
1449 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1450 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1451 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1452 // refresh cycle.
1453
1454 // Don't do any updating if the current fps is the same as the new one.
1455 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1456 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1457 if (currentVsyncPeriod == 0) {
1458 return;
1459 }
1460 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1461 // floating numbers.
1462 const float currentFps = 1e9 / currentVsyncPeriod;
1463 if (std::abs(currentFps - newFps) <= 1) {
1464 return;
1465 }
1466
1467 auto configs = getHwComposer().getConfigs(*displayId);
1468 for (int i = 0; i < configs.size(); i++) {
1469 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1470 if (vsyncPeriod == 0) {
1471 continue;
1472 }
1473 const float fps = 1e9 / vsyncPeriod;
1474 // TODO(b/113612090): There should be a better way at determining which config
1475 // has the right refresh rate.
1476 if (std::abs(fps - newFps) <= 1) {
1477 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1478 if (!display) return;
1479 // This is posted in async function to avoid deadlock when getDisplayDevice
1480 // requires mStateLock.
1481 setActiveConfigAsync(display, i);
1482 ATRACE_INT("FPS", newFps);
1483 }
1484 }
1485}
1486
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001487void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001488 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001489 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001490 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491
Lloyd Piqueba04e622017-12-14 17:11:26 -08001492 // Ignore events that do not have the right sequenceId.
1493 if (sequenceId != getBE().mComposerSequenceId) {
1494 return;
1495 }
1496
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 // Only lock if we're not on the main thread. This function is normally
1498 // called on a hwbinder thread, but for the primary display it's called on
1499 // the main thread with the state lock already held, so don't attempt to
1500 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001501 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001504
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001505 if (std::this_thread::get_id() == mMainThreadId) {
1506 // Process all pending hot plug events immediately if we are on the main thread.
1507 processDisplayHotplugEventsLocked();
1508 }
1509
Lloyd Piqueba04e622017-12-14 17:11:26 -08001510 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001511}
1512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001514 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001515 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001517 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001518 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001519}
1520
Dominik Laskowski075d3172018-05-24 15:50:06 -07001521void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001522 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001524 if (const auto displayId = getInternalDisplayId()) {
1525 getHwComposer().setVsyncEnabled(*displayId,
1526 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1527 }
Mathias Agopian86303202012-07-24 22:46:10 -07001528}
1529
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001531void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001532 if (mUseScheduler) {
1533 mScheduler->disableHardwareVsync(true);
1534 } else {
1535 disableHardwareVsync(true);
1536 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001537 // Clear the drawing state so that the logic inside of
1538 // handleTransactionLocked will fire. It will determine the delta between
1539 // mCurrentState and mDrawingState and re-apply all changes when we make the
1540 // transition.
1541 mDrawingState.displays.clear();
1542 mDisplays.clear();
1543}
1544
Steven Thomas050b2c82017-03-06 11:45:16 -08001545void SurfaceFlinger::updateVrFlinger() {
1546 if (!mVrFlinger)
1547 return;
1548 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001549 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001550 return;
1551 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 ALOGE("Vr flinger is only supported for remote hardware composer"
1555 " service connections. Ignoring request to transition to vr"
1556 " flinger.");
1557 mVrFlingerRequestsDisplay = false;
1558 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001559 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001560
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562
Steven Thomas0123ac62018-07-12 11:32:34 -07001563 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001564 LOG_ALWAYS_FATAL_IF(!display);
1565 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001566 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1567 // called below. Clear the reference now so we don't accidentally use it
1568 // later.
1569 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001572 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 // Delete the current instance before creating the new one
1577 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1578 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1579 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1580 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581
Lloyd Pique441d5042018-10-18 16:49:51 -07001582 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001583 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001584
1585 if (vrFlingerRequestsDisplay) {
1586 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001587 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588
1589 mVisibleRegionsDirty = true;
1590 invalidateHwcGeometry();
1591
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001592 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001593 display = getDefaultDisplayDeviceLocked();
1594 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001595 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001596
Steven Thomasb02664d2017-07-26 18:48:28 -07001597 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001598 const nsecs_t vsyncPeriod = getVsyncPeriod();
1599 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001600
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001601 // The present fences returned from vr_hwc are not an accurate
1602 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001603 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001604 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1605 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001606 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001607 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001608 !hasSyncFramework);
1609 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001610
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 // Use phase of 0 since phase is not known.
1612 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001613 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001614 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001615
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001617
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001618 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001619 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001620}
1621
Mathias Agopian4fec8732012-06-29 14:12:52 -07001622void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001623 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001624 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001626 if (mUseScheduler) {
1627 // This call is made each time SF wakes up and creates a new frame.
1628 mScheduler->incrementFrameCounter();
1629 }
Dan Stoza50182882016-07-08 12:02:20 -07001630 bool frameMissed = !mHadClientComposition &&
1631 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 (mPreviousPresentFence->getSignalTime() ==
1633 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001634 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001635 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001636 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001637 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001638 if (mPropagateBackpressure) {
1639 signalLayerUpdate();
1640 break;
1641 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001642 }
Dan Stoza50182882016-07-08 12:02:20 -07001643
Steven Thomas050b2c82017-03-06 11:45:16 -08001644 // Now that we're going to make it to the handleMessageTransaction()
1645 // call below it's safe to call updateVrFlinger(), which will
1646 // potentially trigger a display handoff.
1647 updateVrFlinger();
1648
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649 bool refreshNeeded = handleMessageTransaction();
1650 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001651 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001652 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001653 // Signal a refresh if a transaction modified the window state,
1654 // a new buffer was latched, or if HWC has requested a full
1655 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001656 signalRefresh();
1657 }
1658 break;
1659 }
1660 case MessageQueue::REFRESH: {
1661 handleMessageRefresh();
1662 break;
1663 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001664 }
1665}
1666
Dan Stoza6b9454d2014-11-07 16:00:59 -08001667bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001668 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001669
1670 // Apply any ready transactions in the queues if there are still transactions that have not been
1671 // applied, wake up during the next vsync period and check again
1672 bool transactionNeeded = false;
1673 if (!flushTransactionQueues()) {
1674 transactionNeeded = true;
1675 }
1676
Mathias Agopian4fec8732012-06-29 14:12:52 -07001677 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001678 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001679 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001680
1681 if (transactionNeeded) {
1682 setTransactionFlags(eTransactionNeeded);
1683 }
1684
1685 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001686}
1687
Mathias Agopian4fec8732012-06-29 14:12:52 -07001688void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001690
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001691 mRefreshPending = false;
1692
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001693 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001694 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001695 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001696 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697 for (const auto& [token, display] : mDisplays) {
1698 beginFrame(display);
1699 prepareFrame(display);
1700 doDebugFlashRegions(display, repaintEverything);
1701 doComposition(display, repaintEverything);
1702 }
1703
Adrian Roos1e1a1282017-11-01 19:05:31 +01001704 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001705 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706
1707 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001708 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001709
Dan Stozabfbffeb2016-07-21 14:49:33 -07001710 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001711 for (const auto& [token, displayDevice] : mDisplays) {
1712 auto display = displayDevice->getCompositionDisplay();
1713 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001714 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001716 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001717
Alec Mouri86770e52018-09-24 22:40:58 +00001718 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001719 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001720 if (mHadClientComposition) {
1721 base::unique_fd flushFence(getRenderEngine().flush());
1722 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1723 getBE().flushFence = new Fence(std::move(flushFence));
1724 } else {
1725 // Cleanup for hygiene.
1726 getBE().flushFence = Fence::NO_FENCE;
1727 }
1728 }
1729
Jorim Jaggi90535212018-05-23 23:44:06 +02001730 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001731
David Sodman7e4ae112018-02-09 15:02:28 -08001732 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001733 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001734 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001735 compositionInfo.hwc.hwcLayer = nullptr;
1736 }
David Sodmanba340492018-08-05 21:51:33 -07001737 }
David Sodman7e4ae112018-02-09 15:02:28 -08001738
1739 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001741
David Sodmanfa9b2af2017-12-24 13:28:59 -08001742
1743bool SurfaceFlinger::handleMessageInvalidate() {
1744 ATRACE_CALL();
1745 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001746}
1747
David Sodman79bba0e2018-08-05 18:07:49 -07001748void SurfaceFlinger::calculateWorkingSet() {
1749 ATRACE_CALL();
1750 ALOGV(__FUNCTION__);
1751
David Sodman79bba0e2018-08-05 18:07:49 -07001752 // build the h/w work list
1753 if (CC_UNLIKELY(mGeometryInvalid)) {
1754 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001755 for (const auto& [token, displayDevice] : mDisplays) {
1756 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001757 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001758 if (!displayId) {
1759 continue;
1760 }
David Sodman79bba0e2018-08-05 18:07:49 -07001761
Lloyd Pique32cbe282018-10-19 13:09:22 -07001762 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 for (size_t i = 0; i < currentLayers.size(); i++) {
1764 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001765
Dominik Laskowski075d3172018-05-24 15:50:06 -07001766 if (!layer->hasHwcLayer(*displayId)) {
1767 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1768 layer->forceClientComposition(*displayId);
1769 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001770 }
1771 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772
Lloyd Pique32cbe282018-10-19 13:09:22 -07001773 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 if (mDebugDisableHWC || mDebugRegion) {
1775 layer->forceClientComposition(*displayId);
1776 }
David Sodman79bba0e2018-08-05 18:07:49 -07001777 }
1778 }
1779 }
1780
1781 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 for (const auto& [token, displayDevice] : mDisplays) {
1783 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001784 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001786 continue;
1787 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001788 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001789
1790 if (mDrawingState.colorMatrixChanged) {
1791 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001792 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001793 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001795 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001796 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1797 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001798 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001799 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001800 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1801 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001802 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001803 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001804 }
1805
Peiyong Lind3788632018-09-18 16:01:31 -07001806 // TODO(b/111562338) remove when composer 2.3 is shipped.
1807 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001809 }
1810
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001811 if (layer->getRoundedCornerState().radius > 0.0f) {
1812 layer->forceClientComposition(*displayId);
1813 }
1814
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001816 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001817 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001818 continue;
1819 }
1820
Lloyd Pique32cbe282018-10-19 13:09:22 -07001821 const auto& displayState = display->getState();
1822 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1823 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001824 }
1825
Peiyong Lin13effd12018-07-24 17:01:47 -07001826 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001827 ColorMode colorMode;
1828 Dataspace dataSpace;
1829 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001830 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001832 }
1833 }
1834
1835 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001836
1837 for (const auto& [token, display] : mDisplays) {
1838 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001839 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001840 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001841
1842 if (displayId) {
1843 if (!layer->setHwcLayer(*displayId)) {
1844 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1845 }
1846 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001847 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001848
Dominik Laskowski05275f12018-11-01 15:03:24 -07001849 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001850 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1851 }
1852 }
David Sodman79bba0e2018-08-05 18:07:49 -07001853}
1854
Lloyd Pique32cbe282018-10-19 13:09:22 -07001855void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1856 bool repaintEverything) {
1857 auto display = displayDevice->getCompositionDisplay();
1858 const auto& displayState = display->getState();
1859
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860 // is debugging enabled
1861 if (CC_LIKELY(!mDebugRegion))
1862 return;
1863
Lloyd Pique32cbe282018-10-19 13:09:22 -07001864 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001865 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08001866 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001867 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001868 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001869 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001870 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871
Alec Mouri0f714832018-11-12 15:31:06 -08001872 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 }
1874 }
1875
Lloyd Pique32cbe282018-10-19 13:09:22 -07001876 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877
1878 if (mDebugRegion > 1) {
1879 usleep(mDebugRegion * 1000);
1880 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001881
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883}
1884
Adrian Roos1e1a1282017-11-01 19:05:31 +01001885void SurfaceFlinger::doTracing(const char* where) {
1886 ATRACE_CALL();
1887 ATRACE_NAME(where);
1888 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001889 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001890 }
1891}
1892
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001893void SurfaceFlinger::logLayerStats() {
1894 ATRACE_CALL();
1895 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001896 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 if (display->isPrimary()) {
1898 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001899 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001900 }
1901 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001902
1903 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001904 }
1905}
1906
David Sodman2b406362017-12-15 13:33:47 -08001907void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001908{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 ATRACE_CALL();
1910 ALOGV("preComposition");
1911
David Sodman2b406362017-12-15 13:33:47 -08001912 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1913
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001915 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001916 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001917 needExtraInvalidate = true;
1918 }
Robert Carr2047fae2016-11-28 14:09:09 -08001919 });
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 if (needExtraInvalidate) {
1922 signalLayerUpdate();
1923 }
1924}
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1927 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 // Update queue of past composite+present times and determine the
1929 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001930 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001932 while (!getBE().mCompositePresentTimes.empty()) {
1933 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 // Cached values should have been updated before calling this method,
1935 // which helps avoid duplicate syscalls.
1936 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1937 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1938 break;
1939 }
1940 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001941 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 }
1943
1944 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001945 while (getBE().mCompositePresentTimes.size() > 16) {
1946 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 }
1948
Ana Krulece588e312018-09-18 12:32:24 -07001949 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001950}
1951
Ana Krulece588e312018-09-18 12:32:24 -07001952void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1953 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Integer division and modulo round toward 0 not -inf, so we need to
1955 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001956 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1957 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1958 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959
Ana Krulec757f63a2019-01-25 10:46:18 -08001960 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001961 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001962 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001963 }
1964
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965 // Snap the latency to a value that removes scheduling jitter from the
1966 // composition and present times, which often have >1ms of jitter.
1967 // Reducing jitter is important if an app attempts to extrapolate
1968 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001971 nsecs_t bias = stats.vsyncPeriod / 2;
1972 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1973 nsecs_t snappedCompositeToPresentLatency =
1974 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
David Sodman99974d22017-11-28 12:04:33 -08001976 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001977 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1978 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001979 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980}
1981
Ady Abraham8164d482019-01-11 14:47:59 -08001982// debug patch for b/119477596 - add stack guards to catch stack
1983// corruptions and disable clang optimizations.
1984// The code below is temporary and planned to be removed once stack
1985// corruptions are found.
1986#pragma clang optimize off
1987class StackGuard {
1988public:
1989 StackGuard(const char* name, const char* func, int line) {
1990 guarders.reserve(MIN_CAPACITY);
1991 guarders.push_back({this, name, func, line});
1992 validate();
1993 }
1994 ~StackGuard() {
1995 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1996 if (i->guard == this) {
1997 guarders.erase(i);
1998 break;
1999 }
2000 }
2001 }
2002
2003 static void validate() {
2004 for (const auto& guard : guarders) {
2005 if (guard.guard->cookie != COOKIE_VALUE) {
2006 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2007 CallStack stack(LOG_TAG);
2008 abort();
2009 }
2010 }
2011 }
2012
2013private:
2014 uint64_t cookie = COOKIE_VALUE;
2015 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2016 static constexpr size_t MIN_CAPACITY = 16;
2017
2018 struct GuarderElement {
2019 StackGuard* guard;
2020 const char* name;
2021 const char* func;
2022 int line;
2023 };
2024
2025 static std::vector<GuarderElement> guarders;
2026};
2027std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2028
2029#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2030
2031#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002032void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002033{
Ady Abraham8164d482019-01-11 14:47:59 -08002034 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 ATRACE_CALL();
2036 ALOGV("postComposition");
2037
Brian Anderson3546a3f2016-07-14 11:51:14 -07002038 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002039 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002041 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002042 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002043 }
Ady Abraham8164d482019-01-11 14:47:59 -08002044 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002045
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002046 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002047 const auto displayDevice = getDefaultDisplayDeviceLocked();
2048 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049
David Sodman73beded2017-11-15 11:56:06 -08002050 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002052 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2053
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002056 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2057 ->getRenderSurface()
2058 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002059 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002060 } else {
2061 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2062 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063
Ady Abraham8164d482019-01-11 14:47:59 -08002064 ASSERT_ON_STACK_GUARD();
2065
David Sodman73beded2017-11-15 11:56:06 -08002066 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2068 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002069 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002070 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002071 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002072
Ana Krulece588e312018-09-18 12:32:24 -07002073 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002074 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002075 if (mUseScheduler) {
2076 mScheduler->getDisplayStatInfo(&stats);
2077 } else {
2078 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2079 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2080 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081
Ady Abraham8164d482019-01-11 14:47:59 -08002082 ASSERT_ON_STACK_GUARD();
2083
David Sodman2b406362017-12-15 13:33:47 -08002084 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002085 // when we started doing work for this frame, but that should be okay
2086 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002087 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002088 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002089 DEFINE_STACK_GUARD(compositorTiming);
2090
Brian Andersond0010582017-03-07 13:20:31 -08002091 {
David Sodman99974d22017-11-28 12:04:33 -08002092 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002093 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002094 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002095
2096 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002097 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098
Robert Carr2047fae2016-11-28 14:09:09 -08002099 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 bool frameLatched =
2101 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2102 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002103 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002104 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002105 recordBufferingStats(layer->getName().string(),
2106 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002107 }
Ady Abraham8164d482019-01-11 14:47:59 -08002108 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002109 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002110
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002111 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002112 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002113 if (mUseScheduler) {
2114 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002115 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002116 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002117 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2118 enableHardwareVsync();
2119 } else {
2120 disableHardwareVsync(false);
2121 }
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002123 }
2124 }
2125
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002126 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002127 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2128 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002129 if (mUseScheduler) {
2130 mScheduler->enableHardwareVsync();
2131 } else {
2132 enableHardwareVsync();
2133 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002134 }
2135 }
2136
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
2138
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002139 if (mAnimCompositionPending) {
2140 mAnimCompositionPending = false;
2141
Brian Anderson4e606e32017-03-16 15:34:57 -07002142 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002143 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002144 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002145
2146 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002148 // The HWC doesn't support present fences, so use the refresh
2149 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 const nsecs_t presentTime =
2151 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002152 DEFINE_STACK_GUARD(presentTime);
2153
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002154 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002155 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002156 }
2157 mAnimFrameTracker.advanceFrame();
2158 }
Dan Stozab90cf072015-03-05 11:05:59 -08002159
Ady Abraham8164d482019-01-11 14:47:59 -08002160 ASSERT_ON_STACK_GUARD();
2161
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002162 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002163 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002164 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002165 }
2166
Ady Abraham8164d482019-01-11 14:47:59 -08002167 ASSERT_ON_STACK_GUARD();
2168
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002169 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002170
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
2172
Lloyd Pique32cbe282018-10-19 13:09:22 -07002173 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2174 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002175 return;
2176 }
2177
2178 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002179 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002180 if (mHasPoweredOff) {
2181 mHasPoweredOff = false;
2182 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002183 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002184 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002185 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002186 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002187 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2188 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002189 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002190 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002191 }
David Sodman4a36e932017-11-07 14:29:47 -08002192 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002193
2194 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002195 }
David Sodman4a36e932017-11-07 14:29:47 -08002196 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002198
2199 {
2200 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002201 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002202 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002203 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002204 if (refillCount > 0) {
2205 const size_t offset = mTexturePool.size();
2206 mTexturePool.resize(mTexturePoolSize);
2207 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2208 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2209 }
Ady Abraham8164d482019-01-11 14:47:59 -08002210 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002211 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002212
Marissa Wallfda30bb2018-10-12 11:34:28 -07002213 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002214 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002215
2216 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002217}
Ady Abraham8164d482019-01-11 14:47:59 -08002218#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002219
2220void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002221 ATRACE_CALL();
2222 ALOGV("rebuildLayerStacks");
2223
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002224 // We need to clear these out now as these may be holding on to a
2225 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2226 // also holds a reference. When the set of visible layers is recomputed,
2227 // some layers may be destroyed if the only thing keeping them alive was
2228 // that list of visible layers associated with each display. The layer
2229 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2230 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2231 for (const auto& [token, display] : mDisplays) {
2232 getBE().mCompositionInfo[token].clear();
2233 }
2234
Mathias Agopiancd60f992012-08-16 16:28:27 -07002235 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002236 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002237 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002238 mVisibleRegionsDirty = false;
2239 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002240
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002241 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002242 const auto& displayDevice = pair.second;
2243 auto display = displayDevice->getCompositionDisplay();
2244 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 Region opaqueRegion;
2246 Region dirtyRegion;
2247 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002248 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002249 const ui::Transform& tr = displayState.transform;
2250 const Rect bounds = displayState.bounds;
2251 if (displayState.isEnabled) {
2252 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253
Jeff Sharkey76488112017-02-27 14:15:18 -07002254 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002255 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002256 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002257 if (display->belongsInOutput(layer->getLayerStack(),
2258 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 Region drawRegion(tr.transform(
2260 layer->visibleNonTransparentRegion));
2261 drawRegion.andSelf(bounds);
2262 if (!drawRegion.isEmpty()) {
2263 layersSortedByZ.add(layer);
2264 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002265 // Clear out the HWC layer if this layer was
2266 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002267 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002268 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002269 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002270 // WM changes display->layerStack upon sleep/awake.
2271 // Here we make sure we delete the HWC layers even if
2272 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002274 }
2275
2276 // If a layer is not going to get a release fence because
2277 // it is invisible, but it is also going to release its
2278 // old buffer, add it to the list of layers needing
2279 // fences.
2280 if (hwcLayerDestroyed) {
2281 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2282 mLayersWithQueuedFrames.cend(), layer);
2283 if (found != mLayersWithQueuedFrames.cend()) {
2284 layersNeedingFences.add(layer);
2285 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002286 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002287 });
2288 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002289 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2290 displayDevice->setLayersNeedingFences(layersNeedingFences);
2291
2292 Region undefinedRegion{bounds};
2293 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2294
2295 display->editState().undefinedRegion = undefinedRegion;
2296 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002297 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002298 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002299}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002300
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002302// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002303// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002305// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306// The returned HDR data space is one of
2307// - Dataspace::UNKNOWN
2308// - Dataspace::BT2020_HLG
2309// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2311 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002312 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 *outHdrDataSpace = Dataspace::UNKNOWN;
2314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002316 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317 case Dataspace::V0_SCRGB:
2318 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002319 case Dataspace::BT2020:
2320 case Dataspace::BT2020_ITU:
2321 case Dataspace::BT2020_LINEAR:
2322 case Dataspace::DISPLAY_BT2020:
2323 bestDataSpace = Dataspace::DISPLAY_BT2020;
2324 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002326 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 case Dataspace::BT2020_PQ:
2329 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002332 case Dataspace::BT2020_HLG:
2333 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334 // When there's mixed PQ content and HLG content, we set the HDR
2335 // data space to be BT2020_PQ and convert HLG to PQ.
2336 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2337 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002338 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339 break;
2340 default:
2341 break;
2342 }
Romain Guy54f154a2017-10-24 21:40:32 +01002343 }
2344
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002346}
2347
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2350 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2352 *outMode = ColorMode::NATIVE;
2353 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002356 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002357
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002361 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2362
Peiyong Lindfde5112018-06-05 10:58:41 -07002363 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002364 const bool isHdr =
2365 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002366 if (isHdr) {
2367 bestDataSpace = hdrDataSpace;
2368 }
2369
Chia-I Wu0d711262018-05-21 15:19:35 -07002370 RenderIntent intent;
2371 switch (mDisplayColorSetting) {
2372 case DisplayColorSetting::MANAGED:
2373 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002374 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002375 break;
2376 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002377 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002378 break;
2379 default: // vendor display color setting
2380 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2381 break;
2382 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002383
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002384 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002385}
2386
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2388 auto display = displayDevice->getCompositionDisplay();
2389 const auto& displayState = display->getState();
2390
Alec Mouri0f714832018-11-12 15:31:06 -08002391 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2393 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002394
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 // If nothing has changed (!dirty), don't recompose.
2396 // If something changed, but we don't currently have any visible layers,
2397 // and didn't when we last did a composition, then skip it this time.
2398 // The second rule does two things:
2399 // - When all layers are removed from a display, we'll emit one black
2400 // frame, then nothing more until we get new layers.
2401 // - When a display is created with a private layer stack, we won't
2402 // emit any black frames until a layer is added to the layer stack.
2403 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 const char flagPrefix[] = {'-', '+'};
2406 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2408 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2409 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2410 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002411
Lloyd Pique31cb2942018-10-19 17:23:03 -07002412 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002416 }
2417}
2418
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2420 auto display = displayDevice->getCompositionDisplay();
2421 const auto& displayState = display->getState();
2422
2423 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002424 return;
David Sodman2b406362017-12-15 13:33:47 -08002425 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426
Lloyd Pique31cb2942018-10-19 17:23:03 -07002427 status_t result = display->getRenderSurface()->prepareFrame(
2428 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002430 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002431}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002432
Lloyd Pique32cbe282018-10-19 13:09:22 -07002433void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002434 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 ALOGV("doComposition");
2436
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 auto display = displayDevice->getCompositionDisplay();
2438 const auto& displayState = display->getState();
2439
2440 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002441 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002442 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002443
David Sodmanfa9b2af2017-12-24 13:28:59 -08002444 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002446
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002448 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002449 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451}
2452
David Sodmanfa9b2af2017-12-24 13:28:59 -08002453void SurfaceFlinger::postFrame()
2454{
2455 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002456 const auto display = getDefaultDisplayDeviceLocked();
2457 if (display && getHwComposer().isConnected(*display->getId())) {
2458 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2460 logFrameStats();
2461 }
2462 }
2463}
2464
Lloyd Pique32cbe282018-10-19 13:09:22 -07002465void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002466 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002468
Lloyd Pique32cbe282018-10-19 13:09:22 -07002469 auto display = displayDevice->getCompositionDisplay();
2470 const auto& displayState = display->getState();
2471 const auto displayId = display->getId();
2472
David Sodmanfa9b2af2017-12-24 13:28:59 -08002473 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002474
Lloyd Pique32cbe282018-10-19 13:09:22 -07002475 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 if (displayId) {
2477 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002478 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002479 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002481 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002482
Chia-I Wu7b549592017-11-15 09:14:57 -08002483 // The layer buffer from the previous frame (if any) is released
2484 // by HWC only when the release fence from this frame (if any) is
2485 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 if (displayId && layer->hasHwcLayer(*displayId)) {
2487 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2488 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002489 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002490
2491 // If the layer was client composited in the previous frame, we
2492 // need to merge with the previous client target acquire fence.
2493 // Since we do not track that, always merge with the current
2494 // client target acquire fence when it is available, even though
2495 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002496 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002497 releaseFence =
2498 Fence::merge("LayerRelease", releaseFence,
2499 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002500 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002501
David Sodman15094112018-10-11 09:39:37 -07002502 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002503 }
Chia-I Wu83806892017-11-16 10:50:20 -08002504
2505 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002507 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002508 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002510 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002511 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002512 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002513 }
2514 }
2515
Dominik Laskowski075d3172018-05-24 15:50:06 -07002516 if (displayId) {
2517 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002518 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520}
2521
Mathias Agopian87baae12012-07-31 12:38:26 -07002522void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523{
Mathias Agopian841cde52012-03-01 15:44:37 -08002524 ATRACE_CALL();
2525
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002526 // here we keep a copy of the drawing state (that is the state that's
2527 // going to be overwritten by handleTransactionLocked()) outside of
2528 // mStateLock so that the side-effects of the State assignment
2529 // don't happen with mStateLock held (which can cause deadlocks).
2530 State drawingState(mDrawingState);
2531
Mathias Agopianca4d3602011-05-19 15:38:14 -07002532 Mutex::Autolock _l(mStateLock);
2533 const nsecs_t now = systemTime();
2534 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535
Mathias Agopianca4d3602011-05-19 15:38:14 -07002536 // Here we're guaranteed that some transaction flags are set
2537 // so we can call handleTransactionLocked() unconditionally.
2538 // We call getTransactionFlags(), which will also clear the flags,
2539 // with mStateLock held to guarantee that mCurrentState won't change
2540 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002541
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002542 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002543 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002544 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002545
Mathias Agopianca4d3602011-05-19 15:38:14 -07002546 mLastTransactionTime = systemTime() - now;
2547 mDebugInTransaction = 0;
2548 invalidateHwcGeometry();
2549 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002550}
2551
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2553 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 const std::optional<DisplayIdentificationInfo> info =
2555 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558 continue;
2559 }
2560
Lloyd Piqueba04e622017-12-14 17:11:26 -08002561 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002563 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 mPhysicalDisplayTokens[info->id] = new BBinder();
2565 DisplayDeviceState state;
2566 state.displayId = info->id;
2567 state.isSecure = true; // All physical displays are currently considered secure.
2568 state.displayName = info->name;
2569 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2570 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002571 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002573 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002574
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2576 if (index >= 0) {
2577 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2578 mInterceptor->saveDisplayDeletion(state.sequenceId);
2579 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002580 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582 }
2583
2584 processDisplayChangesLocked();
2585 }
2586
2587 mPendingHotplugEvents.clear();
2588}
2589
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002590void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2591 bool connected) {
2592 if (mUseScheduler) {
2593 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2594 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2595 } else {
2596 mEventThread->onHotplugReceived(displayType, connected);
2597 mSFEventThread->onHotplugReceived(displayType, connected);
2598 }
2599}
2600
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002603 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 const sp<IGraphicBufferProducer>& producer) {
2605 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002606 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002608 creationArgs.isSecure = state.isSecure;
2609 creationArgs.displaySurface = dispSurface;
2610 creationArgs.hasWideColorGamut = false;
2611 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002612
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2614 creationArgs.isPrimary = isInternalDisplay;
2615
2616 if (useColorManagement && displayId) {
2617 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002619 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002622
Dominik Laskowski7e045462018-05-30 13:02:02 -07002623 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002625 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 }
tangrobin6753a022018-08-10 10:58:54 +08002627 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 if (displayId) {
2630 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002631 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002633 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
Lloyd Pique90c115d2018-09-18 21:39:42 -07002635 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002637 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639 // Make sure that composition can never be stalled by a virtual display
2640 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002641 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002642 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2644 }
2645
Dominik Laskowski075d3172018-05-24 15:50:06 -07002646 creationArgs.displayInstallOrientation =
2647 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002648
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002650 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
Lloyd Pique90c115d2018-09-18 21:39:42 -07002652 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653
2654 if (maxFrameBufferAcquiredBuffers >= 3) {
2655 nativeWindowSurface->preallocateBuffers();
2656 }
2657
2658 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002659 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002662 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002664 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2665 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 if (!state.isVirtual()) {
2667 LOG_ALWAYS_FATAL_IF(!displayId);
2668 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002669 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002671 display->setLayerStack(state.layerStack);
2672 display->setProjection(state.orientation, state.viewport, state.frame);
2673 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676}
2677
Lloyd Pique347200f2017-12-14 17:00:15 -08002678void SurfaceFlinger::processDisplayChangesLocked() {
2679 // here we take advantage of Vector's copy-on-write semantics to
2680 // improve performance by skipping the transaction entirely when
2681 // know that the lists are identical
2682 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2683 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2684 if (!curr.isIdenticalTo(draw)) {
2685 mVisibleRegionsDirty = true;
2686 const size_t cc = curr.size();
2687 size_t dc = draw.size();
2688
2689 // find the displays that were removed
2690 // (ie: in drawing state but not in current state)
2691 // also handle displays that changed
2692 // (ie: displays that are in both lists)
2693 for (size_t i = 0; i < dc;) {
2694 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2695 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002696 // Save display IDs before disconnecting.
2697 const auto internalDisplayId = getInternalDisplayId();
2698 const auto externalDisplayId = getExternalDisplayId();
2699
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002702 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002704 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002705 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002706 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002707 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002708 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 } else {
2711 // this display is in both lists. see if something changed.
2712 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2715 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2716 if (state_binder != draw_binder) {
2717 // changing the surface is like destroying and
2718 // recreating the DisplayDevice, so we just remove it
2719 // from the drawing state, so that it get re-added
2720 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002722 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 mDrawingState.displays.removeItemsAt(i);
2726 dc--;
2727 // at this point we must loop to the next item
2728 continue;
2729 }
2730
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002733 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 }
2735 if ((state.orientation != draw[i].orientation) ||
2736 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 }
2739 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 }
2742 }
2743 }
2744 ++i;
2745 }
2746
2747 // find displays that were added
2748 // (ie: in current state but not in drawing state)
2749 for (size_t i = 0; i < cc; i++) {
2750 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2751 const DisplayDeviceState& state(curr[i]);
2752
Lloyd Pique542307f2018-10-19 13:24:08 -07002753 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 sp<IGraphicBufferProducer> producer;
2755 sp<IGraphicBufferProducer> bqProducer;
2756 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002757 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002758
Dominik Laskowski075d3172018-05-24 15:50:06 -07002759 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002760 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 // Virtual displays without a surface are dormant:
2762 // they have external state (layer stack, projection,
2763 // etc.) but no internal state (i.e. a DisplayDevice).
2764 if (state.surface != nullptr) {
2765 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 int width = 0;
2768 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2769 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2770 int height = 0;
2771 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2772 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2773 int intFormat = 0;
2774 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2775 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002776 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777
Dominik Laskowski075d3172018-05-24 15:50:06 -07002778 displayId =
2779 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 }
2781
2782 // TODO: Plumb requested format back up to consumer
2783
2784 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002785 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 bqProducer, bqConsumer,
2787 state.displayName);
2788
2789 dispSurface = vds;
2790 producer = vds;
2791 }
2792 } else {
2793 ALOGE_IF(state.surface != nullptr,
2794 "adding a supported display, but rendering "
2795 "surface is provided (%p), ignoring it",
2796 state.surface.get());
2797
Dominik Laskowski075d3172018-05-24 15:50:06 -07002798 displayId = state.displayId;
2799 LOG_ALWAYS_FATAL_IF(!displayId);
2800 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 producer = bqProducer;
2802 }
2803
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002804 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002805 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002807 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002808 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002809 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810 LOG_ALWAYS_FATAL_IF(!displayId);
2811
2812 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002813 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002815 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002816 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 }
2818 }
2819 }
2820 }
2821 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002822
2823 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002824}
2825
Mathias Agopian87baae12012-07-31 12:38:26 -07002826void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002827{
Dan Stoza7dde5992015-05-22 09:51:44 -07002828 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002829 mCurrentState.traverseInZOrder([](Layer* layer) {
2830 layer->notifyAvailableFrames();
2831 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002832
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 /*
2834 * Traversal of the children
2835 * (perform the transaction for each of them if needed)
2836 */
2837
Robert Carr720e5062018-07-30 17:45:14 -07002838 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002839 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002840 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002842 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843
2844 const uint32_t flags = layer->doTransaction(0);
2845 if (flags & Layer::eVisibleRegion)
2846 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002847
2848 if (flags & Layer::eInputInfoChanged) {
2849 inputChanged = true;
2850 }
Robert Carr2047fae2016-11-28 14:09:09 -08002851 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 }
2853
2854 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002855 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 */
2857
Mathias Agopiane57f2922012-08-09 16:29:12 -07002858 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002859 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002860 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002861 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002863 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002864 // The transform hint might have changed for some layers
2865 // (either because a display has changed, or because a layer
2866 // as changed).
2867 //
2868 // Walk through all the layers in currentLayers,
2869 // and update their transform hint.
2870 //
2871 // If a layer is visible only on a single display, then that
2872 // display is used to calculate the hint, otherwise we use the
2873 // default display.
2874 //
2875 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2876 // the hint is set before we acquire a buffer from the surface texture.
2877 //
2878 // NOTE: layer transactions have taken place already, so we use their
2879 // drawing state. However, SurfaceFlinger's own transaction has not
2880 // happened yet, so we must use the current state layer list
2881 // (soon to become the drawing state list).
2882 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002884 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002885 bool first = true;
2886 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002887 // NOTE: we rely on the fact that layers are sorted by
2888 // layerStack first (so we don't have to traverse the list
2889 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002891 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002892 currentlayerStack = layerStack;
2893 // figure out if this layerstack is mirrored
2894 // (more than one display) if so, pick the default display,
2895 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 hintDisplay = nullptr;
2897 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002898 if (display->getCompositionDisplay()
2899 ->belongsInOutput(layer->getLayerStack(),
2900 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 if (hintDisplay) {
2902 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002903 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002906 }
2907 }
2908 }
2909 }
Chet Haase91d25932013-04-11 15:24:55 -07002910
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002911 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002912 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2913 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002914
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002915 // could be null when this layer is using a layerStack
2916 // that is not visible on any display. Also can occur at
2917 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002918 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002919 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002920
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002921 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002922 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002923 if (hintDisplay) {
2924 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002925 }
Robert Carr2047fae2016-11-28 14:09:09 -08002926
2927 first = false;
2928 });
Mathias Agopian84300952012-11-21 16:02:13 -08002929 }
2930
2931
Mathias Agopian3559b072012-08-15 13:46:03 -07002932 /*
2933 * Perform our own transaction if needed
2934 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935
2936 if (mLayersAdded) {
2937 mLayersAdded = false;
2938 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002939 mVisibleRegionsDirty = true;
2940 }
2941
2942 // some layers might have been removed, so
2943 // we need to update the regions they're exposing.
2944 if (mLayersRemoved) {
2945 mLayersRemoved = false;
2946 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002947 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002948 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002949 // this layer is not visible anymore
2950 // TODO: we could traverse the tree from front to back and
2951 // compute the actual visible region
2952 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002953 Region visibleReg;
2954 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002955 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002956 }
Robert Carr2047fae2016-11-28 14:09:09 -08002957 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 }
2959
2960 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002961
Vishnu Nairde19f852018-12-18 16:11:53 -08002962 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002963 updateInputWindows();
2964 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002965 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002966
Riley Andrews03414a12014-07-01 14:22:59 -07002967 updateCursorAsync();
2968}
2969
Robert Carr720e5062018-07-30 17:45:14 -07002970void SurfaceFlinger::updateInputWindows() {
2971 ATRACE_CALL();
2972
Vishnu Nairde19f852018-12-18 16:11:53 -08002973 if (mInputFlinger == nullptr) {
2974 return;
2975 }
2976
Robert Carr720e5062018-07-30 17:45:14 -07002977 Vector<InputWindowInfo> inputHandles;
2978
2979 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2980 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002981 // When calculating the screen bounds we ignore the transparent region since it may
2982 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002983 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002984 }
2985 });
2986 mInputFlinger->setInputWindows(inputHandles);
2987}
2988
chaviwfbe5d9c2018-12-26 12:23:37 -08002989void SurfaceFlinger::executeInputWindowCommands() {
2990 if (!mInputFlinger) {
2991 return;
2992 }
2993
2994 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2995 if (transferTouchFocusCommand.fromToken != nullptr &&
2996 transferTouchFocusCommand.toToken != nullptr &&
2997 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2998 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2999 transferTouchFocusCommand.toToken);
3000 }
3001 }
3002
3003 mInputWindowCommands.clear();
3004}
3005
Riley Andrews03414a12014-07-01 14:22:59 -07003006void SurfaceFlinger::updateCursorAsync()
3007{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003008 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003009 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003010 continue;
3011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003013 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3014 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003015 }
3016 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003017}
3018
chaviw61626f22018-11-15 16:26:27 -08003019void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3020 if (layer->hasReadyFrame()) {
3021 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3022 if (layer->shouldPresentNow(expectedPresentTime)) {
3023 bool ignored = false;
3024 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3025 }
3026 }
3027 layer->releasePendingBuffer(systemTime());
3028}
3029
Mathias Agopian4fec8732012-06-29 14:12:52 -07003030void SurfaceFlinger::commitTransaction()
3031{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003032 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003033 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 for (const auto& l : mLayersPendingRemoval) {
3035 recordBufferingStats(l->getName().string(),
3036 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003037
3038 // We need to release the HWC layers when the Layer is removed
3039 // from the current state otherwise the HWC layer just continues
3040 // showing at its last configured state until we eventually
3041 // abandon the buffer queue.
3042 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003043 l->destroyHwcLayersForAllDisplays();
3044 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003045 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 }
3047 mLayersPendingRemoval.clear();
3048 }
3049
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003050 // If this transaction is part of a window animation then the next frame
3051 // we composite should be considered an animation as well.
3052 mAnimCompositionPending = mAnimTransactionPending;
3053
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003055 // clear the "changed" flags in current state
3056 mCurrentState.colorMatrixChanged = false;
3057
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 mDrawingState.traverseInZOrder([](Layer* layer) {
3059 layer->commitChildList();
3060 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003061 mTransactionPending = false;
3062 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003063 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064}
3065
Lloyd Pique32cbe282018-10-19 13:09:22 -07003066void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003068 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003069 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003070
Lloyd Pique32cbe282018-10-19 13:09:22 -07003071 auto display = displayDevice->getCompositionDisplay();
3072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 Region aboveOpaqueLayers;
3074 Region aboveCoveredLayers;
3075 Region dirty;
3076
Mathias Agopian87baae12012-07-31 12:38:26 -07003077 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078
Robert Carr2047fae2016-11-28 14:09:09 -08003079 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003080 // start with the whole surface at its current location
3081 const Layer::State& s(layer->getDrawingState());
3082
Jesse Hall01e29052013-02-19 16:13:35 -08003083 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003084 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003085 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003086 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003087
Mathias Agopianab028732010-03-16 16:41:46 -07003088 /*
3089 * opaqueRegion: area of a surface that is fully opaque.
3090 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003092
3093 /*
3094 * visibleRegion: area of a surface that is visible on screen
3095 * and not fully transparent. This is essentially the layer's
3096 * footprint minus the opaque regions above it.
3097 * Areas covered by a translucent surface are considered visible.
3098 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003100
3101 /*
3102 * coveredRegion: area of a surface that is covered by all
3103 * visible regions above it (which includes the translucent areas).
3104 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003106
Jesse Halla8026d22012-09-25 13:25:04 -07003107 /*
3108 * transparentRegion: area of a surface that is hinted to be completely
3109 * transparent. This is only used to tell when the layer has no visible
3110 * non-transparent regions and can be removed from the layer list. It
3111 * does not affect the visibleRegion of this layer or any layers
3112 * beneath it. The hint may not be correct if apps don't respect the
3113 * SurfaceView restrictions (which, sadly, some don't).
3114 */
3115 Region transparentRegion;
3116
Mathias Agopianab028732010-03-16 16:41:46 -07003117
3118 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003119 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003120 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003124 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003125 if (!visibleRegion.isEmpty()) {
3126 // Remove the transparent area from the visible region
3127 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003128 if (tr.preserveRects()) {
3129 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003130 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003131 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003132 // transformation too complex, can't do the
3133 // transparent region optimization.
3134 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003135 }
Mathias Agopianab028732010-03-16 16:41:46 -07003136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137
Mathias Agopianab028732010-03-16 16:41:46 -07003138 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003140 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003141 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003142 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003143 // the opaque region is the layer's footprint
3144 opaqueRegion = visibleRegion;
3145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 }
3147 }
3148
Robert Carre5f4f692018-01-12 13:12:28 -08003149 if (visibleRegion.isEmpty()) {
3150 layer->clearVisibilityRegions();
3151 return;
3152 }
3153
Mathias Agopianab028732010-03-16 16:41:46 -07003154 // Clip the covered region to the visible region
3155 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3156
3157 // Update aboveCoveredLayers for next (lower) layer
3158 aboveCoveredLayers.orSelf(visibleRegion);
3159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 // subtract the opaque region covered by the layers above us
3161 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
3163 // compute this layer's dirty region
3164 if (layer->contentDirty) {
3165 // we need to invalidate the whole region
3166 dirty = visibleRegion;
3167 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003168 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 layer->contentDirty = false;
3170 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003171 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003172 * the exposed region consists of two components:
3173 * 1) what's VISIBLE now and was COVERED before
3174 * 2) what's EXPOSED now less what was EXPOSED before
3175 *
3176 * note that (1) is conservative, we start with the whole
3177 * visible region but only keep what used to be covered by
3178 * something -- which mean it may have been exposed.
3179 *
3180 * (2) handles areas that were not covered by anything but got
3181 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003182 */
Mathias Agopianab028732010-03-16 16:41:46 -07003183 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003184 const Region oldVisibleRegion = layer->visibleRegion;
3185 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003186 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3187 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188 }
3189 dirty.subtractSelf(aboveOpaqueLayers);
3190
3191 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003192 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193
Mathias Agopianab028732010-03-16 16:41:46 -07003194 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003196
Jesse Halla8026d22012-09-25 13:25:04 -07003197 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 layer->setVisibleRegion(visibleRegion);
3199 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003200 layer->setVisibleNonTransparentRegion(
3201 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003202 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203
Mathias Agopian87baae12012-07-31 12:38:26 -07003204 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205}
3206
Chia-I Wuab0c3192017-08-01 11:29:00 -07003207void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003208 for (const auto& [token, displayDevice] : mDisplays) {
3209 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003210 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003211 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003212 }
3213 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003214}
3215
Daniel Solomon42d04562019-01-20 21:03:19 -08003216void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3217 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3218 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3219 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3220 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3221 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3222 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3223 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3224 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3225 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3226 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3227 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3228 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3229}
3230
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003233 ALOGV("handlePageFlip");
3234
Brian Andersond6927fb2016-07-23 23:37:30 -07003235 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236
Mathias Agopian4fec8732012-06-29 14:12:52 -07003237 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003238 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003239 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003240
3241 // Store the set of layers that need updates. This set must not change as
3242 // buffers are being latched, as this could result in a deadlock.
3243 // Example: Two producers share the same command stream and:
3244 // 1.) Layer 0 is latched
3245 // 2.) Layer 0 gets a new frame
3246 // 2.) Layer 1 gets a new frame
3247 // 3.) Layer 1 is latched.
3248 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3249 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003250 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003251 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003252 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003253 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3254 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003255 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003256 } else {
3257 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003259 } else {
3260 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 }
Robert Carr2047fae2016-11-28 14:09:09 -08003262 });
3263
Lloyd Piquef2c79392018-12-20 16:23:33 -08003264 if (!mLayersWithQueuedFrames.empty()) {
3265 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3266 // writes to Layer current state. See also b/119481871
3267 Mutex::Autolock lock(mStateLock);
3268
3269 for (auto& layer : mLayersWithQueuedFrames) {
3270 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3271 layer->useSurfaceDamage();
3272 invalidateLayerStack(layer, dirty);
3273 if (layer->isBufferLatched()) {
3274 newDataLatched = true;
3275 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003276 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003277 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003278
Alec Mouri86770e52018-09-24 22:40:58 +00003279 // Clear the renderengine fence here...
3280 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3281 // clear instead of sp::clear.
3282 getBE().flushFence = Fence::NO_FENCE;
3283
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003284 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003285
Vishnu Nairde19f852018-12-18 16:11:53 -08003286 if (visibleRegions) {
3287 // Update input window info if the layer receives its first buffer.
3288 updateInputWindows();
3289 }
3290
Dan Stoza6b9454d2014-11-07 16:00:59 -08003291 // If we will need to wake up at some time in the future to deal with a
3292 // queued frame that shouldn't be displayed during this vsync period, wake
3293 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003294 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003295 signalLayerUpdate();
3296 }
3297
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003298 // enter boot animation on first buffer latch
3299 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3300 ALOGI("Enter boot animation");
3301 mBootStage = BootStage::BOOTANIMATION;
3302 }
3303
Dan Stoza6b9454d2014-11-07 16:00:59 -08003304 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003305 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003306}
3307
Mathias Agopianad456f92011-01-13 17:53:01 -08003308void SurfaceFlinger::invalidateHwcGeometry()
3309{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003310 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003311}
3312
Lloyd Pique32cbe282018-10-19 13:09:22 -07003313void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003314 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003315 auto display = displayDevice->getCompositionDisplay();
3316
Dan Stoza71433162014-02-04 16:22:36 -08003317 // We only need to actually compose the display if:
3318 // 1) It is being handled by hardware composer, which may need this to
3319 // keep its virtual display state machine in sync, or
3320 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003322 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003323 return;
3324 }
3325
Dan Stoza9e56aa02015-11-02 13:00:03 -08003326 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003327 base::unique_fd readyFence;
3328 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003329
3330 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003331 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332}
3333
Alec Mouri0f714832018-11-12 15:31:06 -08003334bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3335 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003336 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003337
Lloyd Pique32cbe282018-10-19 13:09:22 -07003338 auto display = displayDevice->getCompositionDisplay();
3339 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003340 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341
3342 const Region bounds(displayState.bounds);
3343 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003344 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003345 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003346
Peiyong Lind3788632018-09-18 16:01:31 -07003347 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003348 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003349
Alec Mouri0f714832018-11-12 15:31:06 -08003350 renderengine::DisplaySettings clientCompositionDisplay;
3351 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3352 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003353
Dan Stoza9e56aa02015-11-02 13:00:03 -08003354 if (hasClientComposition) {
3355 ALOGV("hasClientComposition");
3356
Alec Mouri0f714832018-11-12 15:31:06 -08003357 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003358
3359 if (buf == nullptr) {
3360 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3361 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003362 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003363 return false;
3364 }
3365
Alec Mouri0f714832018-11-12 15:31:06 -08003366 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3367 clientCompositionDisplay.clip = displayState.scissor;
3368 const ui::Transform& displayTransform = displayState.transform;
3369 mat4 m;
3370 m[0][0] = displayTransform[0][0];
3371 m[0][1] = displayTransform[0][1];
3372 m[0][3] = displayTransform[0][2];
3373 m[1][0] = displayTransform[1][0];
3374 m[1][1] = displayTransform[1][1];
3375 m[1][3] = displayTransform[1][2];
3376 m[3][0] = displayTransform[2][0];
3377 m[3][1] = displayTransform[2][1];
3378 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379
Alec Mouri0f714832018-11-12 15:31:06 -08003380 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003381
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003382 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003383 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003384 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003385 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003386 }
Alec Mouri0f714832018-11-12 15:31:06 -08003387 clientCompositionDisplay.outputDataspace = outputDataspace;
3388 clientCompositionDisplay.maxLuminance =
3389 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003390
Lloyd Pique441d5042018-10-18 16:49:51 -07003391 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003392 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003393 getHwComposer()
3394 .hasDisplayCapability(displayId,
3395 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003396
Peiyong Lind3788632018-09-18 16:01:31 -07003397 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003398 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3399 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003400 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003401 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003402 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003403
Mathias Agopian85d751c2012-08-29 16:59:24 -07003404 /*
3405 * and then, render the layers targeted at the framebuffer
3406 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003407
Dan Stoza9e56aa02015-11-02 13:00:03 -08003408 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003410 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003411 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003412 const Region viewportRegion(displayState.viewport);
3413 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003414 ALOGV("Layer: %s", layer->getName().string());
3415 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003417 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003418 case HWC2::Composition::Cursor:
3419 case HWC2::Composition::Device:
3420 case HWC2::Composition::Sideband:
3421 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003422 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003423 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003424 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003425 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003426 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 // never clear the very first layer since we're
3428 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003429 renderengine::LayerSettings layerSettings;
3430 Region dummyRegion;
3431 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3432 layerSettings);
3433
3434 if (prepared) {
3435 layerSettings.source.buffer.buffer = nullptr;
3436 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3437 layerSettings.alpha = half(0.0);
3438 layerSettings.disableBlending = true;
3439 clientCompositionLayers.push_back(layerSettings);
3440 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003441 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003442 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003443 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003444 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003445 renderengine::LayerSettings layerSettings;
3446 bool prepared =
3447 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3448 if (prepared) {
3449 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003450 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 break;
3452 }
3453 default:
3454 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003455 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 } else {
3457 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003458 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003459 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003460 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003461
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003462 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003463 clientCompositionDisplay.clearRegion = clearRegion;
3464 if (!debugRegion.isEmpty()) {
3465 Region::const_iterator it = debugRegion.begin();
3466 Region::const_iterator end = debugRegion.end();
3467 while (it != end) {
3468 const Rect& rect = *it++;
3469 renderengine::LayerSettings layerSettings;
3470 layerSettings.source.buffer.buffer = nullptr;
3471 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3472 layerSettings.geometry.boundaries = rect.toFloatRect();
3473 layerSettings.alpha = half(1.0);
3474 clientCompositionLayers.push_back(layerSettings);
3475 }
3476 }
3477 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3478 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003479 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003480 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481}
3482
Chia-I Wu28e3a252018-09-07 12:05:02 -07003483void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003484 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003485 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486}
3487
Dan Stoza7d89d062015-04-30 13:29:25 -07003488status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003489 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003490 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003492 const sp<Layer>& parent,
3493 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003494{
Dan Stoza7d89d062015-04-30 13:29:25 -07003495 // add this layer to the current state list
3496 {
3497 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003498 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003499 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3500 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003501 return NO_MEMORY;
3502 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003503 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003504 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003505 } else if (parent == nullptr) {
3506 lbc->onRemovedFromCurrentState();
3507 } else if (parent->isRemovedFromCurrentState()) {
3508 parent->addChild(lbc);
3509 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003510 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003511 parent->addChild(lbc);
3512 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003513
Yiwei Zhang243b3782018-05-15 17:40:04 -07003514 if (gbc != nullptr) {
3515 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3516 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3517 mMaxGraphicBufferProducerListSize,
3518 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3519 mGraphicBufferProducerList.size(),
3520 mMaxGraphicBufferProducerListSize, mNumLayers);
3521 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003522 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003523 }
3524
Mathias Agopian96f08192010-06-02 23:28:45 -07003525 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003526 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003527
Dan Stoza7d89d062015-04-30 13:29:25 -07003528 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003529}
3530
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003531uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003532 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003533}
3534
Mathias Agopian3f844832013-08-07 21:24:32 -07003535uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003536 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537}
3538
Mathias Agopian3f844832013-08-07 21:24:32 -07003539uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003540 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003541}
3542
3543uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003544 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003545 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003546 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003548 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003549 }
3550 return old;
3551}
3552
Marissa Wall713b63f2018-10-17 15:42:43 -07003553bool SurfaceFlinger::flushTransactionQueues() {
3554 Mutex::Autolock _l(mStateLock);
3555 auto it = mTransactionQueues.begin();
3556 while (it != mTransactionQueues.end()) {
3557 auto& [applyToken, transactionQueue] = *it;
3558
3559 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003560 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3561 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003562 break;
3563 }
chaviw273171b2018-12-26 11:46:30 -08003564 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003565 transactionQueue.pop();
3566 }
3567
3568 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3569 }
3570 return mTransactionQueues.empty();
3571}
3572
chaviwca27f252018-02-06 16:46:39 -08003573bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3574 for (const ComposerState& state : states) {
3575 // Here we need to check that the interface we're given is indeed
3576 // one of our own. A malicious client could give us a nullptr
3577 // IInterface, or one of its own or even one of our own but a
3578 // different type. All these situations would cause us to crash.
3579 if (state.client == nullptr) {
3580 return true;
3581 }
3582
3583 sp<IBinder> binder = IInterface::asBinder(state.client);
3584 if (binder == nullptr) {
3585 return true;
3586 }
3587
3588 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3589 return true;
3590 }
3591 }
3592 return false;
3593}
3594
Marissa Wall17b4e452018-12-26 16:32:34 -08003595bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3596 const Vector<ComposerState>& states) {
3597 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3598 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3599 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3600 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3601 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3602 return false;
3603 }
3604
Marissa Wall713b63f2018-10-17 15:42:43 -07003605 for (const ComposerState& state : states) {
3606 const layer_state_t& s = state.state;
3607 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3608 continue;
3609 }
3610 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003611 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003612 }
3613 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003614 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003615}
3616
3617void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3618 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003619 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 const InputWindowCommands& inputWindowCommands,
3621 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003622 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003623 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003624
chaviwca27f252018-02-06 16:46:39 -08003625 if (containsAnyInvalidClientState(states)) {
3626 return;
3627 }
3628
Marissa Wall713b63f2018-10-17 15:42:43 -07003629 // If its TransactionQueue already has a pending TransactionState or if it is pending
3630 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003631 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3632 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003633 setTransactionFlags(eTransactionNeeded);
3634 return;
3635 }
3636
chaviw273171b2018-12-26 11:46:30 -08003637 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003638}
3639
3640void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003641 const Vector<DisplayState>& displays, uint32_t flags,
3642 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003643 uint32_t transactionFlags = 0;
3644
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003645 if (flags & eAnimation) {
3646 // For window updates that are part of an animation we must wait for
3647 // previous animation "frames" to be handled.
3648 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003649 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003650 if (CC_UNLIKELY(err != NO_ERROR)) {
3651 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003652 // caller after a few seconds.
3653 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3654 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003655 mAnimTransactionPending = false;
3656 break;
3657 }
3658 }
3659 }
3660
chaviwca27f252018-02-06 16:46:39 -08003661 for (const DisplayState& display : displays) {
3662 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003663 }
3664
Marissa Walle2ffb422018-10-12 11:33:52 -07003665 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003666 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003667 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003668 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003669 // If the state doesn't require a traversal and there are callbacks, send them now
3670 if (!(clientStateFlags & eTraversalNeeded)) {
3671 mTransactionCompletedThread.sendCallbacks();
3672 }
3673 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003674
chaviw273171b2018-12-26 11:46:30 -08003675 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3676
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003677 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3678 // anyway. This can be used as a flush mechanism for previous async transactions.
3679 // Empty animation transaction can be used to simulate back-pressure, so also force a
3680 // transaction for empty animation transactions.
3681 if (transactionFlags == 0 &&
3682 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003683 transactionFlags = eTransactionNeeded;
3684 }
3685
Mathias Agopian386aa982011-11-07 21:58:03 -08003686 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003687 if (mInterceptor->isEnabled()) {
3688 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003689 }
Irvel468051e2016-06-13 16:44:44 -07003690
Mathias Agopian386aa982011-11-07 21:58:03 -08003691 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003692 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3693 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003694 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003695
3696 // if this is a synchronous transaction, wait for it to take effect
3697 // before returning.
3698 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003699 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003700 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003701 if (flags & eAnimation) {
3702 mAnimTransactionPending = true;
3703 }
3704 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003705 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3706 if (CC_UNLIKELY(err != NO_ERROR)) {
3707 // just in case something goes wrong in SF, return to the
3708 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003709 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3710 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003711 break;
3712 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 }
3715}
3716
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003717uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3718 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3719 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003720
Mathias Agopiane57f2922012-08-09 16:29:12 -07003721 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003722 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3723
3724 const uint32_t what = s.what;
3725 if (what & DisplayState::eSurfaceChanged) {
3726 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3727 state.surface = s.surface;
3728 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003729 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003730 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003731 if (what & DisplayState::eLayerStackChanged) {
3732 if (state.layerStack != s.layerStack) {
3733 state.layerStack = s.layerStack;
3734 flags |= eDisplayTransactionNeeded;
3735 }
3736 }
3737 if (what & DisplayState::eDisplayProjectionChanged) {
3738 if (state.orientation != s.orientation) {
3739 state.orientation = s.orientation;
3740 flags |= eDisplayTransactionNeeded;
3741 }
3742 if (state.frame != s.frame) {
3743 state.frame = s.frame;
3744 flags |= eDisplayTransactionNeeded;
3745 }
3746 if (state.viewport != s.viewport) {
3747 state.viewport = s.viewport;
3748 flags |= eDisplayTransactionNeeded;
3749 }
3750 }
3751 if (what & DisplayState::eDisplaySizeChanged) {
3752 if (state.width != s.width) {
3753 state.width = s.width;
3754 flags |= eDisplayTransactionNeeded;
3755 }
3756 if (state.height != s.height) {
3757 state.height = s.height;
3758 flags |= eDisplayTransactionNeeded;
3759 }
3760 }
3761
Mathias Agopiane57f2922012-08-09 16:29:12 -07003762 return flags;
3763}
3764
Robert Carrd4ae7f32018-06-07 16:10:57 -07003765bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3766 IPCThreadState* ipc = IPCThreadState::self();
3767 const int pid = ipc->getCallingPid();
3768 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003769 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003770 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003771 return false;
3772 }
3773 return true;
3774}
3775
chaviwca27f252018-02-06 16:46:39 -08003776uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3777 const layer_state_t& s = composerState.state;
3778 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3779
Mathias Agopian13127d82013-03-05 17:47:11 -08003780 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003781 if (layer == nullptr) {
3782 return 0;
3783 }
3784
chaviw8b3871a2017-11-01 17:41:01 -07003785 uint32_t flags = 0;
3786
Garfield Tan8a3083e2018-12-03 13:21:07 -08003787 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003788 bool geometryAppliesWithResize =
3789 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003790
3791 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3792 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003793 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003794 layer->pushPendingState();
3795 }
3796
chaviw8b3871a2017-11-01 17:41:01 -07003797 if (what & layer_state_t::ePositionChanged) {
3798 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3799 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003800 }
chaviw8b3871a2017-11-01 17:41:01 -07003801 }
3802 if (what & layer_state_t::eLayerChanged) {
3803 // NOTE: index needs to be calculated before we update the state
3804 const auto& p = layer->getParent();
3805 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003806 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003807 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003808 mCurrentState.layersSortedByZ.removeAt(idx);
3809 mCurrentState.layersSortedByZ.add(layer);
3810 // we need traversal (state changed)
3811 // AND transaction (list changed)
3812 flags |= eTransactionNeeded|eTraversalNeeded;
3813 }
chaviw8b3871a2017-11-01 17:41:01 -07003814 } else {
3815 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003816 flags |= eTransactionNeeded|eTraversalNeeded;
3817 }
3818 }
chaviw8b3871a2017-11-01 17:41:01 -07003819 }
3820 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003821 // NOTE: index needs to be calculated before we update the state
3822 const auto& p = layer->getParent();
3823 if (p == nullptr) {
3824 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3825 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3826 mCurrentState.layersSortedByZ.removeAt(idx);
3827 mCurrentState.layersSortedByZ.add(layer);
3828 // we need traversal (state changed)
3829 // AND transaction (list changed)
3830 flags |= eTransactionNeeded|eTraversalNeeded;
3831 }
3832 } else {
3833 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3834 flags |= eTransactionNeeded|eTraversalNeeded;
3835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 }
3837 }
3838 if (what & layer_state_t::eSizeChanged) {
3839 if (layer->setSize(s.w, s.h)) {
3840 flags |= eTraversalNeeded;
3841 }
3842 }
3843 if (what & layer_state_t::eAlphaChanged) {
3844 if (layer->setAlpha(s.alpha))
3845 flags |= eTraversalNeeded;
3846 }
3847 if (what & layer_state_t::eColorChanged) {
3848 if (layer->setColor(s.color))
3849 flags |= eTraversalNeeded;
3850 }
Valerie Haued54efa2019-01-11 20:03:14 -08003851 if (what & layer_state_t::eColorAlphaChanged) {
3852 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3853 }
3854 if (what & layer_state_t::eColorDataspaceChanged) {
3855 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3856 }
Peiyong Lind3788632018-09-18 16:01:31 -07003857 if (what & layer_state_t::eColorTransformChanged) {
3858 if (layer->setColorTransform(s.colorTransform)) {
3859 flags |= eTraversalNeeded;
3860 }
3861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003863 // TODO: b/109894387
3864 //
3865 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3866 // rotation. To see the problem observe that if we have a square parent, and a child
3867 // of the same size, then we rotate the child 45 degrees around it's center, the child
3868 // must now be cropped to a non rectangular 8 sided region.
3869 //
3870 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3871 // private API, and the WindowManager only uses rotation in one case, which is on a top
3872 // level layer in which cropping is not an issue.
3873 //
3874 // However given that abuse of rotation matrices could lead to surfaces extending outside
3875 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3876 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3877 // transformations.
3878 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003879 flags |= eTraversalNeeded;
3880 }
3881 if (what & layer_state_t::eTransparentRegionChanged) {
3882 if (layer->setTransparentRegionHint(s.transparentRegion))
3883 flags |= eTraversalNeeded;
3884 }
3885 if (what & layer_state_t::eFlagsChanged) {
3886 if (layer->setFlags(s.flags, s.mask))
3887 flags |= eTraversalNeeded;
3888 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003889 if (what & layer_state_t::eCropChanged_legacy) {
3890 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003891 flags |= eTraversalNeeded;
3892 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003893 if (what & layer_state_t::eCornerRadiusChanged) {
3894 if (layer->setCornerRadius(s.cornerRadius))
3895 flags |= eTraversalNeeded;
3896 }
chaviw8b3871a2017-11-01 17:41:01 -07003897 if (what & layer_state_t::eLayerStackChanged) {
3898 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3899 // We only allow setting layer stacks for top level layers,
3900 // everything else inherits layer stack from its parent.
3901 if (layer->hasParent()) {
3902 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3903 layer->getName().string());
3904 } else if (idx < 0) {
3905 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3906 "that also does not appear in the top level layer list. Something"
3907 " has gone wrong.", layer->getName().string());
3908 } else if (layer->setLayerStack(s.layerStack)) {
3909 mCurrentState.layersSortedByZ.removeAt(idx);
3910 mCurrentState.layersSortedByZ.add(layer);
3911 // we need traversal (state changed)
3912 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003913 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003914 }
3915 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003916 if (what & layer_state_t::eDeferTransaction_legacy) {
3917 if (s.barrierHandle_legacy != nullptr) {
3918 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3919 } else if (s.barrierGbp_legacy != nullptr) {
3920 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003921 if (authenticateSurfaceTextureLocked(gbp)) {
3922 const auto& otherLayer =
3923 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003924 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003925 } else {
3926 ALOGE("Attempt to defer transaction to to an"
3927 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003928 }
3929 }
chaviw8b3871a2017-11-01 17:41:01 -07003930 // We don't trigger a traversal here because if no other state is
3931 // changed, we don't want this to cause any more work
3932 }
3933 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003934 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003935 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003936 if (!hadParent) {
3937 mCurrentState.layersSortedByZ.remove(layer);
3938 }
chaviw8b3871a2017-11-01 17:41:01 -07003939 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003940 }
chaviw8b3871a2017-11-01 17:41:01 -07003941 }
3942 if (what & layer_state_t::eReparentChildren) {
3943 if (layer->reparentChildren(s.reparentHandle)) {
3944 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003945 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003946 }
chaviw8b3871a2017-11-01 17:41:01 -07003947 if (what & layer_state_t::eDetachChildren) {
3948 layer->detachChildren();
3949 }
3950 if (what & layer_state_t::eOverrideScalingModeChanged) {
3951 layer->setOverrideScalingMode(s.overrideScalingMode);
3952 // We don't trigger a traversal here because if no other state is
3953 // changed, we don't want this to cause any more work
3954 }
Marissa Wall61c58622018-07-18 10:12:20 -07003955 if (what & layer_state_t::eTransformChanged) {
3956 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3959 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3960 flags |= eTraversalNeeded;
3961 }
3962 if (what & layer_state_t::eCropChanged) {
3963 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3964 }
Marissa Wall861616d2018-10-22 12:52:23 -07003965 if (what & layer_state_t::eFrameChanged) {
3966 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3967 }
Marissa Wall61c58622018-07-18 10:12:20 -07003968 if (what & layer_state_t::eBufferChanged) {
3969 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3970 }
3971 if (what & layer_state_t::eAcquireFenceChanged) {
3972 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3973 }
3974 if (what & layer_state_t::eDataspaceChanged) {
3975 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3976 }
3977 if (what & layer_state_t::eHdrMetadataChanged) {
3978 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3981 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eApiChanged) {
3984 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eSidebandStreamChanged) {
3987 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3988 }
Robert Carr720e5062018-07-30 17:45:14 -07003989 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003990 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3991 layer->setInputInfo(s.inputInfo);
3992 flags |= eTraversalNeeded;
3993 } else {
3994 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3995 }
Robert Carr720e5062018-07-30 17:45:14 -07003996 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003997 if (what & layer_state_t::eMetadataChanged) {
3998 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3999 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004000 std::vector<sp<CallbackHandle>> callbackHandles;
4001 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4002 mTransactionCompletedThread.run();
4003 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4004 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4005 }
4006 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004007 if (what & layer_state_t::eCachedBufferChanged) {
4008 sp<GraphicBuffer> buffer =
4009 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4010 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4011 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004012 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4013 // Do not put anything that updates layer state or modifies flags after
4014 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004015 return flags;
4016}
4017
chaviw273171b2018-12-26 11:46:30 -08004018uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4019 uint32_t flags = 0;
4020 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4021 flags |= eTraversalNeeded;
4022 }
4023
4024 mInputWindowCommands.merge(inputWindowCommands);
4025 return flags;
4026}
4027
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004028status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4029 uint32_t h, PixelFormat format, uint32_t flags,
4030 LayerMetadata metadata, sp<IBinder>* handle,
4031 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004032 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004033 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004034 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004036 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004037
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 status_t result = NO_ERROR;
4039
4040 sp<Layer> layer;
4041
Cody Northropbc755282017-03-31 12:00:08 -06004042 String8 uniqueName = getUniqueLayerName(name);
4043
Mathias Agopian3165cc22012-08-08 19:42:09 -07004044 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004045 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004046 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4047 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004050 case ISurfaceComposerClient::eFXSurfaceBufferState:
4051 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4052 break;
chaviw13fdc492017-06-27 12:40:18 -07004053 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004054 // check if buffer size is set for color layer.
4055 if (w > 0 || h > 0) {
4056 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4057 int(w), int(h));
4058 return BAD_VALUE;
4059 }
4060
chaviw13fdc492017-06-27 12:40:18 -07004061 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004062 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004063 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004065 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004066 // check if buffer size is set for container layer.
4067 if (w > 0 || h > 0) {
4068 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4069 int(w), int(h));
4070 return BAD_VALUE;
4071 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004072 result = createContainerLayer(client,
4073 uniqueName, w, h, flags,
4074 handle, &layer);
4075 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 default:
4077 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 break;
4079 }
4080
Dan Stoza7d89d062015-04-30 13:29:25 -07004081 if (result != NO_ERROR) {
4082 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004084
Chia-I Wuab0c3192017-08-01 11:29:00 -07004085 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4086 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004087 if (metadata.has(METADATA_WINDOW_TYPE)) {
4088 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4089 if (windowType == 441731) {
4090 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4091 layer->setPrimaryDisplayOnly();
4092 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004093 }
4094
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004095 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004096
Robert Carrb89ea9d2018-12-10 13:01:14 -08004097 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4098 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4099 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004100 if (result != NO_ERROR) {
4101 return result;
4102 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004103 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004104
4105 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107}
4108
Cody Northropbc755282017-03-31 12:00:08 -06004109String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4110{
4111 bool matchFound = true;
4112 uint32_t dupeCounter = 0;
4113
4114 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4115 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4116
Dan Stoza436ccf32018-06-21 12:10:12 -07004117 // Grab the state lock since we're accessing mCurrentState
4118 Mutex::Autolock lock(mStateLock);
4119
Cody Northropbc755282017-03-31 12:00:08 -06004120 // Loop over layers until we're sure there is no matching name
4121 while (matchFound) {
4122 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004123 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004124 if (layer->getName() == uniqueName) {
4125 matchFound = true;
4126 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4127 }
4128 });
4129 }
4130
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004131 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4132 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004133
4134 return uniqueName;
4135}
4136
Marissa Wallfd668622018-05-10 10:21:13 -07004137status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
4139 PixelFormat& format, sp<IBinder>* handle,
4140 sp<IGraphicBufferProducer>* gbp,
4141 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004143 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 case PIXEL_FORMAT_TRANSPARENT:
4145 case PIXEL_FORMAT_TRANSLUCENT:
4146 format = PIXEL_FORMAT_RGBA_8888;
4147 break;
4148 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004149 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 break;
4151 }
4152
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004153 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004154 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004155 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004157 *handle = layer->getHandle();
4158 *gbp = layer->getProducer();
4159 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161
Marissa Wallfd668622018-05-10 10:21:13 -07004162 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004163 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164}
4165
Marissa Wall61c58622018-07-18 10:12:20 -07004166status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4167 uint32_t w, uint32_t h, uint32_t flags,
4168 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004169 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004170 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004171 *handle = layer->getHandle();
4172 *outLayer = layer;
4173
4174 return NO_ERROR;
4175}
4176
chaviw13fdc492017-06-27 12:40:18 -07004177status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004178 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004179 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004181 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004182 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004183 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004184}
4185
Robert Carr6b3f6c52018-08-13 13:05:17 -07004186status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4187 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4188 sp<IBinder>* handle, sp<Layer>* outLayer)
4189{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004190 *outLayer =
4191 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004192 *handle = (*outLayer)->getHandle();
4193 return NO_ERROR;
4194}
4195
4196
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004197void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004198 mLayersPendingRemoval.add(layer);
4199 mLayersRemoved = true;
4200 setTransactionFlags(eTransactionNeeded);
4201}
4202
Robert Carr695d5282018-12-18 15:27:58 -08004203void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004204{
Robert Carr2e102c92018-10-23 12:11:15 -07004205 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004206 // If a layer has a parent, we allow it to out-live it's handle
4207 // with the idea that the parent holds a reference and will eventually
4208 // be cleaned up. However no one cleans up the top-level so we do so
4209 // here.
4210 if (layer->getParent() == nullptr) {
4211 mCurrentState.layersSortedByZ.remove(layer);
4212 }
4213 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004214 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004215}
4216
Mathias Agopianb60314a2012-04-10 22:09:54 -07004217// ---------------------------------------------------------------------------
4218
Andy McFadden13a082e2012-08-24 10:16:42 -07004219void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 const auto display = getDefaultDisplayDeviceLocked();
4221 if (!display) return;
4222
4223 const sp<IBinder> token = display->getDisplayToken().promote();
4224 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004225
Jesse Hall01e29052013-02-19 16:13:35 -08004226 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004227 Vector<ComposerState> state;
4228 Vector<DisplayState> displays;
4229 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004230 d.what = DisplayState::eDisplayProjectionChanged |
4231 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004232 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004233 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004234 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004235 d.frame.makeInvalid();
4236 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004237 d.width = 0;
4238 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004239 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004240 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004241
Dominik Laskowskie9774092018-12-11 10:04:24 -08004242 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004243
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 const nsecs_t vsyncPeriod = getVsyncPeriod();
4245 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004246
Brian Andersond0010582017-03-07 13:20:31 -08004247 // Use phase of 0 since phase is not known.
4248 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004250 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004251}
4252
4253void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004254 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 postMessageAsync(
4256 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004257}
4258
Dominik Laskowskie9774092018-12-11 10:04:24 -08004259void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 if (display->isVirtual()) {
4261 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004262 return;
4263 }
4264
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 const auto displayId = display->getId();
4266 LOG_ALWAYS_FATAL_IF(!displayId);
4267
Dominik Laskowski34157762018-10-31 13:07:19 -07004268 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004269
4270 int currentMode = display->getPowerMode();
4271 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 return;
4273 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 display->setPowerMode(mode);
4276
Lloyd Pique4dccc412018-01-22 17:21:36 -08004277 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004278 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004279 }
4280
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004282 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004283 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004285 if (mUseScheduler) {
4286 mScheduler->onScreenAcquired(mAppConnectionHandle);
4287 } else {
4288 mEventThread->onScreenAcquired();
4289 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004290 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004292
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004293 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004294 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004295 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004296
4297 struct sched_param param = {0};
4298 param.sched_priority = 1;
4299 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4300 ALOGW("Couldn't set SCHED_FIFO on display on");
4301 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004302 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004303 // Turn off the display
4304 struct sched_param param = {0};
4305 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4306 ALOGW("Couldn't set SCHED_OTHER on display off");
4307 }
4308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004310 if (mUseScheduler) {
4311 mScheduler->disableHardwareVsync(true);
4312 } else {
4313 disableHardwareVsync(true); // also cancels any in-progress resync
4314 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004315 if (mUseScheduler) {
4316 mScheduler->onScreenReleased(mAppConnectionHandle);
4317 } else {
4318 mEventThread->onScreenReleased();
4319 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004320 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004321
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 mVisibleRegionsDirty = true;
4324 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004325 } else if (mode == HWC_POWER_MODE_DOZE ||
4326 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004327 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004328 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004330 if (mUseScheduler) {
4331 mScheduler->onScreenAcquired(mAppConnectionHandle);
4332 } else {
4333 mEventThread->onScreenAcquired();
4334 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004335 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004336 }
4337 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4338 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004339 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004340 if (mUseScheduler) {
4341 mScheduler->disableHardwareVsync(true);
4342 } else {
4343 disableHardwareVsync(true); // also cancels any in-progress resync
4344 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004345 if (mUseScheduler) {
4346 mScheduler->onScreenReleased(mAppConnectionHandle);
4347 } else {
4348 mEventThread->onScreenReleased();
4349 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004350 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004352 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004353 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004354 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004355 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004356
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004357 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004358 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004359 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004360 // Update refresh rate stats.
4361 mRefreshRateStats->setPowerMode(mode);
4362 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004363 }
4364
Dominik Laskowski34157762018-10-31 13:07:19 -07004365 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004366}
4367
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004368void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004369 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004370 const auto display = getDisplayDevice(displayToken);
4371 if (!display) {
4372 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4373 displayToken.get());
4374 } else if (display->isVirtual()) {
4375 ALOGW("Attempt to set power mode %d for virtual display", mode);
4376 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004377 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004378 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004380}
4381
4382// ---------------------------------------------------------------------------
4383
Dominik Laskowskic2867142019-01-21 11:33:38 -08004384status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4385 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004387
Mathias Agopianbd115332013-04-18 16:41:04 -07004388 IPCThreadState* ipc = IPCThreadState::self();
4389 const int pid = ipc->getCallingPid();
4390 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004391
Mathias Agopianbd115332013-04-18 16:41:04 -07004392 if ((uid != AID_SHELL) &&
4393 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4395 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004396 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004397 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004398 // (this would indicate SF is stuck, but we want to be able to
4399 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004400 status_t err = mStateLock.timedLock(s2ns(1));
4401 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004402 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403 StringAppendF(&result,
4404 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4405 "(no locks held)\n",
4406 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004407 }
4408
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004410
Dominik Laskowskic2867142019-01-21 11:33:38 -08004411 static const std::unordered_map<std::string, Dumper> dumpers = {
4412 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4413 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4414 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4415 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4416 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4417 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4418 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4419 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4420 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4421 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4422 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4423 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4424 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004425 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4427 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004430
Dominik Laskowskic2867142019-01-21 11:33:38 -08004431 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4432 (it->second)(args, asProto, result);
4433 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004434 if (asProto) {
4435 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4436 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4437 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004439 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004440 }
4441
Mathias Agopian9795c422009-08-26 16:36:26 -07004442 if (locked) {
4443 mStateLock.unlock();
4444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
4448}
4449
Dominik Laskowskic2867142019-01-21 11:33:38 -08004450void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451 mCurrentState.traverseInZOrder(
4452 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453}
4454
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004456 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458 if (args.size() > 1) {
4459 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004460 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004461 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004462 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463 }
Robert Carr2047fae2016-11-28 14:09:09 -08004464 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004465 } else {
4466 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 }
4468}
4469
Dominik Laskowskic2867142019-01-21 11:33:38 -08004470void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004471 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004472 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004473 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004474 }
Robert Carr2047fae2016-11-28 14:09:09 -08004475 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004476
Svetoslavd85084b2014-03-20 10:28:31 -07004477 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478}
4479
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4481 mTimeStats->parseArgs(asProto, args, result);
4482}
4483
Jamie Gennis6547ff42013-07-16 20:12:42 -07004484// This should only be called from the main thread. Otherwise it would need
4485// the lock and should use mCurrentState rather than mDrawingState.
4486void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004488 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490
4491 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004496
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 if (isLayerTripleBufferingDisabled())
4498 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4501 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4502 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4503 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4504 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4505 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004507}
4508
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004509void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004510 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004511 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004512 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004513 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004514
4515 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4516
4517 if (mUseScheduler) {
4518 mScheduler->dump(mAppConnectionHandle, result);
4519 } else {
4520 mEventThread->dump(result);
4521 }
4522}
4523
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4525 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004526 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4527 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004528 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004529 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004531 }
David Sodman4a36e932017-11-07 14:29:47 -08004532 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004533 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004534 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004535 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4536 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004537}
4538
Dan Stozae77c7662016-05-13 11:37:28 -07004539void SurfaceFlinger::recordBufferingStats(const char* layerName,
4540 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004541 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4542 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004543 for (const auto& segment : history) {
4544 if (!segment.usedThirdBuffer) {
4545 stats.twoBufferTime += segment.totalTime;
4546 }
4547 if (segment.occupancyAverage < 1.0f) {
4548 stats.doubleBufferedTime += segment.totalTime;
4549 } else if (segment.occupancyAverage < 2.0f) {
4550 stats.tripleBufferedTime += segment.totalTime;
4551 }
4552 ++stats.numSegments;
4553 stats.totalTime += segment.totalTime;
4554 }
4555}
4556
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4558 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004559
4560 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4561 const size_t count = currentLayers.size();
4562 for (size_t i=0 ; i<count ; i++) {
4563 currentLayers[i]->dumpFrameEvents(result);
4564 }
4565}
4566
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004568 result.append("Buffering stats:\n");
4569 result.append(" [Layer name] <Active time> <Two buffer> "
4570 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004571 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004572 typedef std::tuple<std::string, float, float, float> BufferTuple;
4573 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004574 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004575 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004576 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004577 if (stats.numSegments == 0) {
4578 continue;
4579 }
4580 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4581 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4582 stats.totalTime;
4583 float doubleBufferRatio = static_cast<float>(
4584 stats.doubleBufferedTime) / stats.totalTime;
4585 float tripleBufferRatio = static_cast<float>(
4586 stats.tripleBufferedTime) / stats.totalTime;
4587 sorted.insert({activeTime, {name, twoBufferRatio,
4588 doubleBufferRatio, tripleBufferRatio}});
4589 }
4590 for (const auto& sortedPair : sorted) {
4591 float activeTime = sortedPair.first;
4592 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4594 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004595 }
4596 result.append("\n");
4597}
4598
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004600 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004601 const auto displayId = display->getId();
4602 if (!displayId) {
4603 continue;
4604 }
4605 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004606 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004607 continue;
4608 }
4609
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result,
4611 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4612 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004613 uint8_t port;
4614 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004615 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004616 result.append("no identification data\n");
4617 continue;
4618 }
4619
4620 if (!isEdid(data)) {
4621 result.append("unknown identification data: ");
4622 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004624 }
4625 result.append("\n");
4626 continue;
4627 }
4628
4629 const auto edid = parseEdid(data);
4630 if (!edid) {
4631 result.append("invalid EDID: ");
4632 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004634 }
4635 result.append("\n");
4636 continue;
4637 }
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 result.append(edid->displayName.data(), edid->displayName.length());
4641 result.append("\"\n");
4642 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004643}
4644
Yiwei Zhang5434a782018-12-05 18:06:32 -08004645void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4646 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4647 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4648 StringAppendF(&result, "DisplayColorSetting: %s\n",
4649 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004650
4651 // TODO: print out if wide-color mode is active or not
4652
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004653 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 const auto displayId = display->getId();
4655 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004656 continue;
4657 }
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004660 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004661 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004663 }
4664
Lloyd Pique32cbe282018-10-19 13:09:22 -07004665 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666 StringAppendF(&result, " Current color mode: %s (%d)\n",
4667 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004668 }
4669 result.append("\n");
4670}
4671
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004673 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004674 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4675 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004676 continue;
4677 }
4678
Dominik Laskowski05275f12018-11-01 15:03:24 -07004679 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4681 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004682 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 compositionInfo.dump(result, nullptr);
4684 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004685 }
4686 }
David Sodman7e4ae112018-02-09 15:02:28 -08004687}
4688
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004689LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004690 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004691 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4692 const State& state = useDrawing ? mDrawingState : mCurrentState;
4693 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004694 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004695 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004696 });
4697
4698 return layersProto;
4699}
4700
Lloyd Pique32cbe282018-10-19 13:09:22 -07004701LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004702 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004703
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004704 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004705 resolution->set_w(displayDevice.getWidth());
4706 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004707
Lloyd Pique32cbe282018-10-19 13:09:22 -07004708 auto display = displayDevice.getCompositionDisplay();
4709 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004710
Lloyd Pique32cbe282018-10-19 13:09:22 -07004711 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4712 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4713 layersProto.set_global_transform(displayState.orientation);
4714
4715 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004716 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004717 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004718 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004719 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004720 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004721 }
4722 });
4723
4724 return layersProto;
4725}
4726
Dominik Laskowskic2867142019-01-21 11:33:38 -08004727void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4728 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 Colorizer colorizer(colorize);
4730
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 // figure out if we're stuck somewhere
4732 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004733 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4735
4736 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004737 * Dump library configuration.
4738 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739
4740 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004741 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004742 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004743 appendSfConfigString(result);
4744 appendUiConfigString(result);
4745 appendGuiConfigString(result);
4746 result.append("\n");
4747
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004748 result.append("\nDisplay identification data:\n");
4749 dumpDisplayIdentificationData(result);
4750
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004751 result.append("\nWide-Color information:\n");
4752 dumpWideColorInfo(result);
4753
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004755 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004757 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004758 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004759
Andy McFadden41d67d72014-04-25 16:58:34 -07004760 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004761 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004762 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004763 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004764 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004765
Dan Stozab90cf072015-03-05 11:05:59 -08004766 dumpStaticScreenStats(result);
4767 result.append("\n");
4768
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004770
Dan Stozae77c7662016-05-13 11:37:28 -07004771 dumpBufferingStats(result);
4772
Andy McFadden4803b742012-09-24 19:07:20 -07004773 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774 * Dump the visible layer list
4775 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4778 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4779 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004780 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004781
Chia-I Wu2f884132018-09-13 15:17:58 -07004782 {
4783 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4784 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004786 result.append("\n");
4787 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004788
David Sodman7e4ae112018-02-09 15:02:28 -08004789 result.append("\nFrame-Composition information:\n");
4790 dumpFrameCompositionInfo(result);
4791 result.append("\n");
4792
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004794 * Dump Display state
4795 */
4796
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004797 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004799 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004800 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004801 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004802 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004803 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004804
4805 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806 * Dump SurfaceFlinger global state
4807 */
4808
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004810 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004811 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004812
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004813 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004816 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4817 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4819 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004820 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004821 StringAppendF(&result,
4822 " transaction-flags : %08x\n"
4823 " gpu_to_cpu_unsupported : %d\n",
4824 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004825
Dominik Laskowski075d3172018-05-24 15:50:06 -07004826 if (const auto displayId = getInternalDisplayId();
4827 displayId && getHwComposer().isConnected(*displayId)) {
4828 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004829 StringAppendF(&result,
4830 " refresh-rate : %f fps\n"
4831 " x-dpi : %f\n"
4832 " y-dpi : %f\n",
4833 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4834 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004835 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004836
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004838
Dan Stozae22aec72016-08-01 13:20:59 -07004839 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004840 * Tracing state
4841 */
4842 mTracing.dump(result);
4843 result.append("\n");
4844
4845 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004846 * HWC layer minidump
4847 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004848 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004849 const auto displayId = display->getId();
4850 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004851 continue;
4852 }
4853
Yiwei Zhang5434a782018-12-05 18:06:32 -08004854 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004855 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004856 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004857 result.append("\n");
4858 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004859
4860 /*
4861 * Dump HWComposer state
4862 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004863 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004864 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004865 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004866 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004867 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004868 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004869
4870 /*
4871 * Dump gralloc state
4872 */
4873 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4874 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004875
4876 /*
4877 * Dump VrFlinger state if in use.
4878 */
4879 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4880 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004881 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004882 result.append("\n");
4883 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004884
4885 /**
4886 * Scheduler dump state.
4887 */
4888 if (mUseScheduler) {
4889 result.append("\nScheduler state:\n");
4890 result.append(mScheduler->doDump() + "\n");
4891 result.append(mRefreshRateStats->doDump() + "\n");
4892 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004893}
4894
Dominik Laskowski075d3172018-05-24 15:50:06 -07004895const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004896 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004897 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004898 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004899 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004900 }
4901 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004902
Dominik Laskowski34157762018-10-31 13:07:19 -07004903 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004904 static const Vector<sp<Layer>> empty;
4905 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004906}
4907
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908void SurfaceFlinger::updateColorMatrixLocked() {
4909 mat4 colorMatrix;
4910 if (mGlobalSaturationFactor != 1.0f) {
4911 // Rec.709 luma coefficients
4912 float3 luminance{0.213f, 0.715f, 0.072f};
4913 luminance *= 1.0f - mGlobalSaturationFactor;
4914 mat4 saturationMatrix = mat4(
4915 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4916 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4917 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4918 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4919 );
4920 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4921 } else {
4922 colorMatrix = mClientColorMatrix * mDaltonizer();
4923 }
4924
4925 if (mCurrentState.colorMatrix != colorMatrix) {
4926 mCurrentState.colorMatrix = colorMatrix;
4927 mCurrentState.colorMatrixChanged = true;
4928 setTransactionFlags(eTransactionNeeded);
4929 }
4930}
4931
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004932status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004933#pragma clang diagnostic push
4934#pragma clang diagnostic error "-Wswitch-enum"
4935 switch (static_cast<ISurfaceComposerTag>(code)) {
4936 // These methods should at minimum make sure that the client requested
4937 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004938 case BOOT_FINISHED:
4939 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 case CREATE_DISPLAY:
4941 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004942 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004943 case GET_ACTIVE_COLOR_MODE:
4944 case GET_ANIMATION_FRAME_STATS:
4945 case GET_HDR_CAPABILITIES:
4946 case SET_ACTIVE_CONFIG:
4947 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004948 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004949 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004950 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004951 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4952 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004953 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4954 IPCThreadState* ipc = IPCThreadState::self();
4955 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4956 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004957 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 }
Robert Carr1db73f62016-12-21 12:58:51 -08004959 return OK;
4960 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004961 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004962 IPCThreadState* ipc = IPCThreadState::self();
4963 const int pid = ipc->getCallingPid();
4964 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004965 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4966 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004967 return PERMISSION_DENIED;
4968 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971 // Used by apps to hook Choreographer to SurfaceFlinger.
4972 case CREATE_DISPLAY_EVENT_CONNECTION:
4973 // The following calls are currently used by clients that do not
4974 // request necessary permissions. However, they do not expose any secret
4975 // information, so it is OK to pass them.
4976 case AUTHENTICATE_SURFACE:
4977 case GET_ACTIVE_CONFIG:
4978 case GET_BUILT_IN_DISPLAY:
4979 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004980 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981 case GET_DISPLAY_CONFIGS:
4982 case GET_DISPLAY_STATS:
4983 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4984 // Calling setTransactionState is safe, because you need to have been
4985 // granted a reference to Client* and Handle* to do anything with it.
4986 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004987 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004988 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004989 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004990 case GET_PROTECTED_CONTENT_SUPPORT:
4991 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08004992 case UNCACHE_BUFFER:
4993 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 return OK;
4995 }
4996 case CAPTURE_LAYERS:
4997 case CAPTURE_SCREEN: {
4998 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004999 IPCThreadState* ipc = IPCThreadState::self();
5000 const int pid = ipc->getCallingPid();
5001 const int uid = ipc->getCallingUid();
5002 if ((uid != AID_GRAPHICS) &&
5003 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5004 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5005 return PERMISSION_DENIED;
5006 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 return OK;
5008 }
5009 // The following codes are deprecated and should never be allowed to access SF.
5010 case CONNECT_DISPLAY_UNUSED:
5011 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5012 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5013 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005016
5017 // These codes are used for the IBinder protocol to either interrogate the recipient
5018 // side of the transaction for its canonical interface descriptor or to dump its state.
5019 // We let them pass by default.
5020 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5021 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5022 code == IBinder::SYSPROPS_TRANSACTION) {
5023 return OK;
5024 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005025 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005026 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005027 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005028 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5029 return OK;
5030 }
5031 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5032 return PERMISSION_DENIED;
5033#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005034}
5035
Ana Krulec13be8ad2018-08-21 02:43:56 +00005036status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5037 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005038 status_t credentialCheck = CheckTransactCodeCredentials(code);
5039 if (credentialCheck != OK) {
5040 return credentialCheck;
5041 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5044 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005045 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005046 IPCThreadState* ipc = IPCThreadState::self();
5047 const int uid = ipc->getCallingUid();
5048 if (CC_UNLIKELY(uid != AID_SYSTEM
5049 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005050 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005051 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005052 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 return PERMISSION_DENIED;
5054 }
5055 int n;
5056 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005057 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005058 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 return NO_ERROR;
5060 case 1002: // SHOW_UPDATES
5061 n = data.readInt32();
5062 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005063 invalidateHwcGeometry();
5064 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005067 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005068 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005069 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005070 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005071 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005072 setTransactionFlags(
5073 eTransactionNeeded|
5074 eDisplayTransactionNeeded|
5075 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005076 return NO_ERROR;
5077 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005078 case 1006:{ // send empty update
5079 signalRefresh();
5080 return NO_ERROR;
5081 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005082 case 1008: // toggle use of hw composer
5083 n = data.readInt32();
5084 mDebugDisableHWC = n ? 1 : 0;
5085 invalidateHwcGeometry();
5086 repaintEverything();
5087 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005088 case 1009: // toggle use of transform hint
5089 n = data.readInt32();
5090 mDebugDisableTransformHint = n ? 1 : 0;
5091 invalidateHwcGeometry();
5092 repaintEverything();
5093 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005095 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005096 reply->writeInt32(0);
5097 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005098 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005099 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 return NO_ERROR;
5101 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005102 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005103 if (!display) {
5104 return NAME_NOT_FOUND;
5105 }
5106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005107 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005108 return NO_ERROR;
5109 }
5110 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005111 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005112 // daltonize
5113 n = data.readInt32();
5114 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005115 case 1:
5116 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5117 break;
5118 case 2:
5119 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5120 break;
5121 case 3:
5122 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5123 break;
5124 default:
5125 mDaltonizer.setType(ColorBlindnessType::None);
5126 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005127 }
5128 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005129 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005130 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005131 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005132 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005133
5134 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005135 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005136 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005137 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005138 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005139 // apply a color matrix
5140 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005141 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005142 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005143 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005144 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005145 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005146 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005147 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005148 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005149 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005150 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005151
5152 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5153 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005154 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005155 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5156 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5157 }
5158
Chia-I Wu28f320b2018-05-03 11:02:56 -07005159 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005160 return NO_ERROR;
5161 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005162 // This is an experimental interface
5163 // Needs to be shifted to proper binder interface when we productize
5164 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005165 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005166 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005167 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005168 return NO_ERROR;
5169 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005170 case 1017: {
5171 n = data.readInt32();
5172 mForceFullDamage = static_cast<bool>(n);
5173 return NO_ERROR;
5174 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005175 case 1018: { // Modify Choreographer's phase offset
5176 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005177 if (mUseScheduler) {
5178 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5179 } else {
5180 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5181 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005182 return NO_ERROR;
5183 }
5184 case 1019: { // Modify SurfaceFlinger's phase offset
5185 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005186 if (mUseScheduler) {
5187 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5188 } else {
5189 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5190 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005191 return NO_ERROR;
5192 }
Irvel468051e2016-06-13 16:44:44 -07005193 case 1020: { // Layer updates interceptor
5194 n = data.readInt32();
5195 if (n) {
5196 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005197 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005198 }
5199 else{
5200 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005201 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005202 }
5203 return NO_ERROR;
5204 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005205 case 1021: { // Disable HWC virtual displays
5206 n = data.readInt32();
5207 mUseHwcVirtualDisplays = !n;
5208 return NO_ERROR;
5209 }
Romain Guy0147a172017-06-01 13:53:56 -07005210 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005211 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005212 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005213
Chia-I Wu28f320b2018-05-03 11:02:56 -07005214 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005215 return NO_ERROR;
5216 }
Romain Guy54f154a2017-10-24 21:40:32 +01005217 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005218 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005219 invalidateHwcGeometry();
5220 repaintEverything();
5221 return NO_ERROR;
5222 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005223 // Deprecate, use 1030 to check whether the device is color managed.
5224 case 1024: {
5225 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005226 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005227 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005228 n = data.readInt32();
5229 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005230 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005231 mTracing.enable();
5232 doTracing("tracing.enable");
5233 reply->writeInt32(NO_ERROR);
5234 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005235 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005236 status_t err = mTracing.disable();
5237 reply->writeInt32(err);
5238 }
5239 return NO_ERROR;
5240 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005241 case 1026: { // Get layer tracing status
5242 reply->writeBool(mTracing.isEnabled());
5243 return NO_ERROR;
5244 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005245 // Is a DisplayColorSetting supported?
5246 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005247 const auto display = getDefaultDisplayDevice();
5248 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005249 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005250 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005251
5252 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5253 switch (setting) {
5254 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005255 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005256 break;
5257 case DisplayColorSetting::UNMANAGED:
5258 reply->writeBool(true);
5259 break;
5260 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005262 break;
5263 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005264 reply->writeBool(
5265 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005266 break;
5267 }
5268 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005269 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005270 // Is VrFlinger active?
5271 case 1028: {
5272 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005273 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005274 return NO_ERROR;
5275 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005276 // Is device color managed?
5277 case 1030: {
5278 reply->writeBool(useColorManagement);
5279 return NO_ERROR;
5280 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005281 // Override default composition data space
5282 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5283 // && adb shell stop zygote && adb shell start zygote
5284 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5285 // adb shell stop zygote && adb shell start zygote
5286 case 1031: {
5287 Mutex::Autolock _l(mStateLock);
5288 n = data.readInt32();
5289 if (n) {
5290 n = data.readInt32();
5291 if (n) {
5292 Dataspace dataspace = static_cast<Dataspace>(n);
5293 if (!validateCompositionDataspace(dataspace)) {
5294 return BAD_VALUE;
5295 }
5296 mDefaultCompositionDataspace = dataspace;
5297 }
5298 n = data.readInt32();
5299 if (n) {
5300 Dataspace dataspace = static_cast<Dataspace>(n);
5301 if (!validateCompositionDataspace(dataspace)) {
5302 return BAD_VALUE;
5303 }
5304 mWideColorGamutCompositionDataspace = dataspace;
5305 }
5306 } else {
5307 // restore composition data space.
5308 mDefaultCompositionDataspace = defaultCompositionDataspace;
5309 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5310 }
5311 return NO_ERROR;
5312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005313 }
5314 }
5315 return err;
5316}
5317
Steven Thomas6d8110b2017-08-31 18:24:21 -07005318void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005319 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005320 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005321}
5322
Ana Krulec7d1d6832018-12-27 11:10:09 -08005323void SurfaceFlinger::repaintEverythingForHWC() {
5324 mRepaintEverything = true;
5325 mEventQueue->invalidateForHWC();
5326}
5327
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5329class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005330public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005331 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5332 ~WindowDisconnector() {
5333 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005334 }
5335
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005336private:
5337 ANativeWindow* mWindow;
5338 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005339};
5340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005341status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005342 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5343 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005344 uint32_t reqWidth, uint32_t reqHeight,
5345 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005346 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005347 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005348
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005349 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005350
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005351 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5352
Chia-I Wu20261cb2018-08-23 12:55:44 -07005353 sp<DisplayDevice> display;
5354 {
5355 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005356
Chia-I Wu20261cb2018-08-23 12:55:44 -07005357 display = getDisplayDeviceLocked(displayToken);
5358 if (!display) return BAD_VALUE;
5359
Chia-I Wucb023152018-08-28 12:57:23 -07005360 // set the requested width/height to the logical display viewport size
5361 // by default
5362 if (reqWidth == 0 || reqHeight == 0) {
5363 reqWidth = uint32_t(display->getViewport().width());
5364 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005365 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005366 }
5367
Peiyong Lin0e003c92018-09-17 11:09:51 -07005368 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5369 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005370
5371 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005372 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005373 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5374 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005375}
5376
5377status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005378 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5379 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005380 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005381 ATRACE_CALL();
5382
5383 class LayerRenderArea : public RenderArea {
5384 public:
Robert Carr578038f2018-03-09 12:25:24 -08005385 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005386 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5387 bool childrenOnly)
5388 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005389 mLayer(layer),
5390 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005391 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005392 mFlinger(flinger),
5393 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005394 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005395 Rect getBounds() const override {
5396 const Layer::State& layerState(mLayer->getDrawingState());
5397 return mLayer->getBufferSize(layerState);
5398 }
Marissa Wall61c58622018-07-18 10:12:20 -07005399 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005400 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005401 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005402 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005403 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005404 }
chaviwa76b2712017-09-20 12:02:26 -07005405 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005406 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005407 Rect getSourceCrop() const override {
5408 if (mCrop.isEmpty()) {
5409 return getBounds();
5410 } else {
5411 return mCrop;
5412 }
5413 }
Robert Carr578038f2018-03-09 12:25:24 -08005414 class ReparentForDrawing {
5415 public:
5416 const sp<Layer>& oldParent;
5417 const sp<Layer>& newParent;
5418
5419 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5420 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005421 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005422 }
Robert Carr15eae092018-03-23 13:43:53 -07005423 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005424 };
5425
5426 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005427 const Rect sourceCrop = getSourceCrop();
5428 // no need to check rotation because there is none
5429 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5430 sourceCrop.height() != getReqHeight();
5431
Robert Carr578038f2018-03-09 12:25:24 -08005432 if (!mChildrenOnly) {
5433 mTransform = mLayer->getTransform().inverse();
5434 drawLayers();
5435 } else {
5436 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005437 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005438 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5439 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005440
5441 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5442 drawLayers();
5443 }
5444 }
chaviwa76b2712017-09-20 12:02:26 -07005445
chaviwa76b2712017-09-20 12:02:26 -07005446 private:
chaviw7206d492017-11-10 16:16:12 -08005447 const sp<Layer> mLayer;
5448 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005449
5450 // In the "childrenOnly" case we reparent the children to a screenshot
5451 // layer which has no properties set and which does not draw.
5452 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005453 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005454 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005455
5456 SurfaceFlinger* mFlinger;
5457 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005458 };
5459
5460 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5461 auto parent = layerHandle->owner.promote();
5462
Robert Carr2e102c92018-10-23 12:11:15 -07005463 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005464 ALOGE("captureLayers called with a removed parent");
5465 return NAME_NOT_FOUND;
5466 }
5467
Robert Carr578038f2018-03-09 12:25:24 -08005468 const int uid = IPCThreadState::self()->getCallingUid();
5469 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005470 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005471 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5472 return PERMISSION_DENIED;
5473 }
5474
chaviw7206d492017-11-10 16:16:12 -08005475 Rect crop(sourceCrop);
5476 if (sourceCrop.width() <= 0) {
5477 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005479 }
5480
5481 if (sourceCrop.height() <= 0) {
5482 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005483 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005484 }
5485
5486 int32_t reqWidth = crop.width() * frameScale;
5487 int32_t reqHeight = crop.height() * frameScale;
5488
Chia-I Wu20261cb2018-08-23 12:55:44 -07005489 // really small crop or frameScale
5490 if (reqWidth <= 0) {
5491 reqWidth = 1;
5492 }
5493 if (reqHeight <= 0) {
5494 reqHeight = 1;
5495 }
5496
Peiyong Lin0e003c92018-09-17 11:09:51 -07005497 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005498
Robert Carr578038f2018-03-09 12:25:24 -08005499 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005500 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5501 if (!layer->isVisible()) {
5502 return;
Robert Carr578038f2018-03-09 12:25:24 -08005503 } else if (childrenOnly && layer == parent.get()) {
5504 return;
chaviwa76b2712017-09-20 12:02:26 -07005505 }
5506 visitor(layer);
5507 });
5508 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005509 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005510}
5511
5512status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5513 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005514 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005515 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005516 bool useIdentityTransform) {
5517 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005518
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005520 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5521 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005522 *outBuffer =
5523 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5524 static_cast<android_pixel_format>(reqPixelFormat), 1,
5525 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526
5527 // This mutex protects syncFd and captureResult for communication of the return values from the
5528 // main thread back to this Binder thread
5529 std::mutex captureMutex;
5530 std::condition_variable captureCondition;
5531 std::unique_lock<std::mutex> captureLock(captureMutex);
5532 int syncFd = -1;
5533 std::optional<status_t> captureResult;
5534
Robert Carr03480e22018-01-04 16:02:06 -08005535 const int uid = IPCThreadState::self()->getCallingUid();
5536 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5537
Dominik Laskowski8c001672018-05-30 16:52:06 -07005538 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005539 // If there is a refresh pending, bug out early and tell the binder thread to try again
5540 // after the refresh.
5541 if (mRefreshPending) {
5542 ATRACE_NAME("Skipping screenshot for now");
5543 std::unique_lock<std::mutex> captureLock(captureMutex);
5544 captureResult = std::make_optional<status_t>(EAGAIN);
5545 captureCondition.notify_one();
5546 return;
5547 }
5548
5549 status_t result = NO_ERROR;
5550 int fd = -1;
5551 {
5552 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005553 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005554 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5555 useIdentityTransform, forSystem, &fd);
5556 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005557 }
5558
5559 {
5560 std::unique_lock<std::mutex> captureLock(captureMutex);
5561 syncFd = fd;
5562 captureResult = std::make_optional<status_t>(result);
5563 captureCondition.notify_one();
5564 }
5565 });
5566
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005567 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005568 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005569 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005570 while (*captureResult == EAGAIN) {
5571 captureResult.reset();
5572 result = postMessageAsync(message);
5573 if (result != NO_ERROR) {
5574 return result;
5575 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005576 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005577 }
5578 result = *captureResult;
5579 }
5580
5581 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005582 sync_wait(syncFd, -1);
5583 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005585
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005586 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005587}
5588
chaviwa76b2712017-09-20 12:02:26 -07005589void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005590 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005591 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5592 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005593 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005594
chaviwa76b2712017-09-20 12:02:26 -07005595 const auto reqWidth = renderArea.getReqWidth();
5596 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005597 const auto sourceCrop = renderArea.getSourceCrop();
5598 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005599
Alec Mouri0f714832018-11-12 15:31:06 -08005600 renderengine::DisplaySettings clientCompositionDisplay;
5601 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005602
Alec Mouri0f714832018-11-12 15:31:06 -08005603 // assume that bounds are never offset, and that they are the same as the
5604 // buffer bounds.
5605 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5606 ui::Transform transform = renderArea.getTransform();
5607 mat4 m;
5608 m[0][0] = transform[0][0];
5609 m[0][1] = transform[0][1];
5610 m[0][3] = transform[0][2];
5611 m[1][0] = transform[1][0];
5612 m[1][1] = transform[1][1];
5613 m[1][3] = transform[1][2];
5614 m[3][0] = transform[2][0];
5615 m[3][1] = transform[2][1];
5616 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617
Alec Mouri0f714832018-11-12 15:31:06 -08005618 clientCompositionDisplay.globalTransform = m;
5619 mat4 rotMatrix;
5620 // Displacement for repositioning the clipping rectangle after rotating it
5621 // with the rotation hint.
5622 int displacementX = 0;
5623 int displacementY = 0;
5624 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5625 switch (rotation) {
5626 case ui::Transform::ROT_90:
5627 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5628 displacementX = reqWidth;
5629 break;
5630 case ui::Transform::ROT_180:
5631 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5632 displacementX = reqWidth;
5633 displacementY = reqHeight;
5634 break;
5635 case ui::Transform::ROT_270:
5636 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5637 displacementY = reqHeight;
5638 break;
5639 default:
5640 break;
5641 }
5642 // We need to transform the clipping window into the right spot.
5643 // First, rotate the clipping rectangle by the rotation hint to get the
5644 // right orientation
5645 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5646 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5647 const vec4 rotClipTL = rotMatrix * clipTL;
5648 const vec4 rotClipBR = rotMatrix * clipBR;
5649 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5650 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5651 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5652 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5653
5654 // Now reposition the clipping rectangle with the displacement vector
5655 // computed above.
5656 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5657
5658 clientCompositionDisplay.clip =
5659 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5660 newClipRight + displacementX, newClipBottom + displacementY);
5661
5662 // We need to perform the same transformation in layer space, so propagate
5663 // it to the global transform.
5664 mat4 clipTransform = displacementMat * rotMatrix;
5665 clientCompositionDisplay.globalTransform *= clipTransform;
5666 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5667 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005668
chaviw50da5042018-04-09 13:49:37 -07005669 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005670
Alec Mouri0f714832018-11-12 15:31:06 -08005671 renderengine::LayerSettings fillLayer;
5672 fillLayer.source.buffer.buffer = nullptr;
5673 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5674 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5675 fillLayer.alpha = half(alpha);
5676 clientCompositionLayers.push_back(fillLayer);
5677
5678 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005679 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005680 renderengine::LayerSettings layerSettings;
5681 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5682 layerSettings);
5683 if (prepared) {
5684 clientCompositionLayers.push_back(layerSettings);
5685 }
chaviwa76b2712017-09-20 12:02:26 -07005686 });
Alec Mouri0f714832018-11-12 15:31:06 -08005687
5688 clientCompositionDisplay.clearRegion = clearRegion;
5689 base::unique_fd drawFence;
5690 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5691 &drawFence);
5692
5693 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005694}
5695
chaviwa76b2712017-09-20 12:02:26 -07005696status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5697 TraverseLayersFunction traverseLayers,
5698 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005699 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005700 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005701 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005702 ATRACE_CALL();
5703
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005704 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005705
5706 traverseLayers([&](Layer* layer) {
5707 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5708 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005709
Robert Carr03480e22018-01-04 16:02:06 -08005710 // We allow the system server to take screenshots of secure layers for
5711 // use in situations like the Screen-rotation animation and place
5712 // the impetus on WindowManager to not persist them.
5713 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005714 ALOGW("FB is protected: PERMISSION_DENIED");
5715 return PERMISSION_DENIED;
5716 }
Alec Mouri0f714832018-11-12 15:31:06 -08005717 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005718 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005719}
5720
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005721// ---------------------------------------------------------------------------
5722
Dan Stoza412903f2017-04-27 13:42:17 -07005723void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5724 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005725}
5726
Dan Stoza412903f2017-04-27 13:42:17 -07005727void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5728 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005729}
5730
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005731void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005732 const LayerVector::Visitor& visitor) {
5733 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005734 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005735 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005736 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005737 continue;
5738 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005739 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005740 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005741 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005742 return;
5743 }
chaviwa76b2712017-09-20 12:02:26 -07005744 if (!layer->isVisible()) {
5745 return;
5746 }
5747 visitor(layer);
5748 });
5749 }
5750}
5751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005752}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005753
Lloyd Pique074e8122018-07-26 12:57:23 -07005754
Mathias Agopian3f844832013-08-07 21:24:32 -07005755#if defined(__gl_h_)
5756#error "don't include gl/gl.h in this file"
5757#endif
5758
5759#if defined(__gl2_h_)
5760#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005761#endif