blob: c98220ddcb324a9c7d6bfa71e3da0a7403b8f7b2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700160ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
161 switch (rotation) {
162 case ISurfaceComposer::eRotateNone:
163 return ui::Transform::ROT_0;
164 case ISurfaceComposer::eRotate90:
165 return ui::Transform::ROT_90;
166 case ISurfaceComposer::eRotate180:
167 return ui::Transform::ROT_180;
168 case ISurfaceComposer::eRotate270:
169 return ui::Transform::ROT_270;
170 }
171 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
172 return ui::Transform::ROT_0;
173}
174
Peiyong Linfca547f2018-07-09 13:03:33 -0700175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Peiyong Lin9d846a52018-11-05 13:18:20 -0800190// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
191bool validateCompositionDataspace(Dataspace dataspace) {
192 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
193}
194
Steven Thomasb02664d2017-07-26 18:48:28 -0700195} // namespace anonymous
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Mathias Agopian99b49842011-06-27 16:05:52 -0700199const String16 sHardwareTest("android.permission.HARDWARE_TEST");
200const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
201const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
202const String16 sDump("android.permission.DUMP");
203
Daniel Solomon42d04562019-01-20 21:03:19 -0800204constexpr float kSrgbRedX = 0.4123f;
205constexpr float kSrgbRedY = 0.2126f;
206constexpr float kSrgbRedZ = 0.0193f;
207constexpr float kSrgbGreenX = 0.3576f;
208constexpr float kSrgbGreenY = 0.7152f;
209constexpr float kSrgbGreenZ = 0.1192f;
210constexpr float kSrgbBlueX = 0.1805f;
211constexpr float kSrgbBlueY = 0.0722f;
212constexpr float kSrgbBlueZ = 0.9506f;
213constexpr float kSrgbWhiteX = 0.9505f;
214constexpr float kSrgbWhiteY = 1.0000f;
215constexpr float kSrgbWhiteZ = 1.0891f;
216
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800217constexpr float kDefaultRefreshRate = 60.f;
218constexpr float kPerformanceRefreshRate = 90.f;
219
Mathias Agopian99b49842011-06-27 16:05:52 -0700220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700228int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700235
Kalle Raitaa099a242017-01-11 11:17:29 -0800236std::string getHwcServiceName() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.hwc_service_name", value, "default");
239 ALOGI("Using HWComposer service: '%s'", value);
240 return std::string(value);
241}
242
243bool useTrebleTestingOverride() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.treble_testing_override", value, "false");
246 ALOGI("Treble testing override: '%s'", value);
247 return std::string(value) == "true";
248}
249
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
251 switch(displayColorSetting) {
252 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Enhanced");
258 default:
259 return std::string("Unknown ") +
260 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262}
263
David Sodmanbc815282017-11-05 18:57:52 -0800264SurfaceFlingerBE::SurfaceFlingerBE()
265 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800266 mFrameBuckets(),
267 mTotalTime(0),
268 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800269 mComposerSequenceId(0) {
270}
271
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
273 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700276 mTransactionPending(false),
277 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700278 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700279 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800281 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800283 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800284 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800285 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700287 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700288 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700289 mDebugInTransaction(0),
290 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700291 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800292 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700293 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700294 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Ady Abrahamc3e21312019-02-07 14:30:23 -0800399 if (!mUseScheduler) {
400 mPrimaryDispSync =
401 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
402 SurfaceFlinger::dispSyncPresentTimeOffset);
403 }
404
Ana Krulec757f63a2019-01-25 10:46:18 -0800405 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
406 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700455sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
456 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457{
458 class DisplayToken : public BBinder {
459 sp<SurfaceFlinger> flinger;
460 virtual ~DisplayToken() {
461 // no more references, this display must be terminated
462 Mutex::Autolock _l(flinger->mStateLock);
463 flinger->mCurrentState.displays.removeItem(this);
464 flinger->setTransactionFlags(eDisplayTransactionNeeded);
465 }
466 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700467 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 : flinger(flinger) {
469 }
470 };
471
472 sp<BBinder> token = new DisplayToken(this);
473
474 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 // Display ID is assigned when virtual display is allocated by HWC.
476 DisplayDeviceState state;
477 state.isSecure = secure;
478 state.displayName = displayName;
479 mCurrentState.displays.add(token, state);
480 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 return token;
482}
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 Mutex::Autolock _l(mStateLock);
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
488 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 return;
491 }
492
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
494 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 ALOGE("destroyDisplay called for non-virtual display");
496 return;
497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 mInterceptor->saveDisplayDeletion(state.sequenceId);
499 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 setTransactionFlags(eDisplayTransactionNeeded);
501}
502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
504 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800506 const auto internalDisplayId = getInternalDisplayIdLocked();
507 if (!internalDisplayId) {
508 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 }
510
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800511 std::vector<PhysicalDisplayId> displayIds;
512 displayIds.reserve(mPhysicalDisplayTokens.size());
513 displayIds.push_back(internalDisplayId->value);
514
515 for (const auto& [id, token] : mPhysicalDisplayTokens) {
516 if (id != *internalDisplayId) {
517 displayIds.push_back(id.value);
518 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800521 return displayIds;
522}
523
524sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
525 Mutex::Autolock lock(mStateLock);
526 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527}
528
Ady Abraham37965d42018-11-01 13:43:32 -0700529status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
530 if (!outGetColorManagement) {
531 return BAD_VALUE;
532 }
533 *outGetColorManagement = useColorManagement;
534 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700535}
536
Lloyd Pique441d5042018-10-18 16:49:51 -0700537HWComposer& SurfaceFlinger::getHwComposer() const {
538 return mCompositionEngine->getHwComposer();
539}
540
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700541renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
542 return mCompositionEngine->getRenderEngine();
543}
544
Lloyd Pique70d91362018-10-18 16:02:55 -0700545compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
546 return *mCompositionEngine.get();
547}
548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549void SurfaceFlinger::bootFinished()
550{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551 if (mStartPropertySetThread->join() != NO_ERROR) {
552 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554 const nsecs_t now = systemTime();
555 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000556 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
558 // wait patiently for the window manager death
559 const String16 name("window");
560 sp<IBinder> window(defaultServiceManager()->getService(name));
561 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700562 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 postMessageAsync(new LambdaMessage([this] {
586 readPersistentProperties();
587 mBootStage = BootStage::FINISHED;
588 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589}
590
Dan Stoza436ccf32018-06-21 12:10:12 -0700591uint32_t SurfaceFlinger::getNewTexture() {
592 {
593 std::lock_guard lock(mTexturePoolMutex);
594 if (!mTexturePool.empty()) {
595 uint32_t name = mTexturePool.back();
596 mTexturePool.pop_back();
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
598 return name;
599 }
600
601 // The pool was too small, so increase it for the future
602 ++mTexturePoolSize;
603 }
604
605 // The pool was empty, so we need to get a new texture name directly using a
606 // blocking call to the main thread
607 uint32_t name = 0;
608 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
609 return name;
610}
611
Mathias Agopian3f844832013-08-07 21:24:32 -0700612void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Dominik Laskowski83b88212018-12-11 13:34:06 -0800626 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800630 mScheduler = getFactory().createScheduler(
631 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
632
Ana Krulec757f63a2019-01-25 10:46:18 -0800633 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
634 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
635 mPhaseOffsets->setRefreshRateType(
636 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mAppConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800639 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800640 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 impl::EventThread::InterceptVSyncsCallback());
642 mSfConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800643 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800644 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 mInterceptor->saveVSyncEvent(timestamp);
646 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700649 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
650 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 } else {
652 mEventThreadSource =
653 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800654 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700655 mEventThread =
656 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 impl::EventThread::InterceptVSyncsCallback(),
658 "appEventThread");
659 mSfEventThreadSource =
660 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800661 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700662
663 mSFEventThread =
664 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700665 [this](nsecs_t timestamp) {
666 mInterceptor->saveVSyncEvent(timestamp);
667 },
668 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800669 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700670 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700674 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700675 renderEngineFeature |= (useColorManagement ?
676 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700677 renderEngineFeature |= (useContextPriority ?
678 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700679
680 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700681 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700682 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700684
685 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
686 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700687 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
688 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800689 // Process any initial hotplug and resulting display changes.
690 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 const auto display = getDefaultDisplayDeviceLocked();
692 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800695
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700698 // This callback is called from the vr flinger dispatch thread. We
699 // need to call signalTransaction(), which requires holding
700 // mStateLock when we're not on the main thread. Acquiring
701 // mStateLock from the vr flinger dispatch thread might trigger a
702 // deadlock in surface flinger (see b/66916578), so post a message
703 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700705 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
706 mVrFlingerRequestsDisplay = requestDisplay;
707 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700708 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700710 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
711 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700713 .value_or(0),
714 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800715 if (!mVrFlinger) {
716 ALOGE("Failed to start vrflinger");
717 }
718 }
719
Ady Abrahamc3e21312019-02-07 14:30:23 -0800720 if (!mUseScheduler) {
721 mEventControlThread = getFactory().createEventControlThread(
722 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
723 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700724
Mathias Agopian92a979a2012-08-02 18:32:23 -0700725 // initialize our drawing state
726 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700727
Andy McFadden13a082e2012-08-24 10:16:42 -0700728 // set initial conditions (e.g. unblank default device)
729 initializeDisplays();
730
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700731 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700732
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700734
735 const bool presentFenceReliable =
736 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
737 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738
739 if (mStartPropertySetThread->Start() != NO_ERROR) {
740 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800744 mScheduler->setExpiredIdleTimerCallback([this] {
745 Mutex::Autolock lock(mStateLock);
746 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800747 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800748 mScheduler->setResetIdleTimerCallback([this] {
749 Mutex::Autolock lock(mStateLock);
750 setRefreshRateTo(RefreshRateType::PERFORMANCE);
751 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800752
Alec Mourifb571ea2019-01-24 18:42:10 -0800753 mRefreshRateStats =
754 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
755 *display->getId()),
756 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800757 }
758
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700760}
761
Romain Guy11d63f42017-07-20 12:47:14 -0700762void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700763 Mutex::Autolock _l(mStateLock);
764
Romain Guy11d63f42017-07-20 12:47:14 -0700765 char value[PROPERTY_VALUE_MAX];
766
767 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800768 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700769 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800770 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100771
772 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700773 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800774
775 property_get("persist.sys.sf.color_mode", value, "0");
776 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700777}
778
Mathias Agopiana67e4182012-06-19 17:26:12 -0700779void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800780 // Start boot animation service by setting a property mailbox
781 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700782 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800783 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 if (mStartPropertySetThread->join() != NO_ERROR) {
785 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800786 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700787}
788
Mathias Agopian875d8e12013-06-07 15:35:48 -0700789size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700790 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700791}
792
Mathias Agopian875d8e12013-06-07 15:35:48 -0700793size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700794 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700795}
796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800797// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800798
Jamie Gennis582270d2011-08-17 18:19:00 -0700799bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800801 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800802 return authenticateSurfaceTextureLocked(bufferProducer);
803}
804
805bool SurfaceFlinger::authenticateSurfaceTextureLocked(
806 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800807 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800808 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800809}
810
Brian Anderson6b376712017-04-04 10:51:39 -0700811status_t SurfaceFlinger::getSupportedFrameTimestamps(
812 std::vector<FrameEvent>* outSupported) const {
813 *outSupported = {
814 FrameEvent::REQUESTED_PRESENT,
815 FrameEvent::ACQUIRE,
816 FrameEvent::LATCH,
817 FrameEvent::FIRST_REFRESH_START,
818 FrameEvent::LAST_REFRESH_START,
819 FrameEvent::GPU_COMPOSITION_DONE,
820 FrameEvent::DEQUEUE_READY,
821 FrameEvent::RELEASE,
822 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700823 ConditionalLock _l(mStateLock,
824 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700825 if (!getHwComposer().hasCapability(
826 HWC2::Capability::PresentFenceIsNotReliable)) {
827 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
828 }
829 return NO_ERROR;
830}
831
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800832status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
833 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700834 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 return BAD_VALUE;
836 }
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 if (!displayId) {
840 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 // TODO: Not sure if display density should handled by SF any longer
844 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700847 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700849 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851 return density;
852 }
853 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700856 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 return getDensityFromProperty("ro.sf.lcd_density"); }
858 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Dominik Laskowski075d3172018-05-24 15:50:06 -0700862 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 DisplayInfo info = DisplayInfo();
864
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 float xdpi = hwConfig->getDpiX();
866 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700868 info.w = hwConfig->getWidth();
869 info.h = hwConfig->getHeight();
870 // Default display viewport to display width and height
871 info.viewportW = info.w;
872 info.viewportH = info.h;
873
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800874 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 // The density of the device is provided by a build property
876 float density = Density::getBuildDensity() / 160.0f;
877 if (density == 0) {
878 // the build doesn't provide a density -- this is wrong!
879 // use xdpi instead
880 ALOGE("ro.sf.lcd_density must be defined as a build property");
881 density = xdpi / 160.0f;
882 }
883 if (Density::getEmuDensity()) {
884 // if "qemu.sf.lcd_density" is specified, it overrides everything
885 xdpi = ydpi = density = Density::getEmuDensity();
886 density /= 160.0f;
887 }
888 info.density = density;
889
890 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891 const auto display = getDefaultDisplayDeviceLocked();
892 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700893
894 // This is for screenrecord
895 const Rect viewport = display->getViewport();
896 if (viewport.isValid()) {
897 info.viewportW = uint32_t(viewport.getWidth());
898 info.viewportH = uint32_t(viewport.getHeight());
899 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 } else {
901 // TODO: where should this value come from?
902 static const int TV_DENSITY = 213;
903 info.density = TV_DENSITY / 160.0f;
904 info.orientation = 0;
905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 info.xdpi = xdpi;
908 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800910 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911
Andy McFadden91b2ca82014-06-13 14:04:23 -0700912 // This is how far in advance a buffer must be queued for
913 // presentation at a given time. If you want a buffer to appear
914 // on the screen at time N, you must submit the buffer before
915 // (N - presentationDeadline).
916 //
917 // Normally it's one full refresh period (to give SF a chance to
918 // latch the buffer), but this can be reduced by configuring a
919 // DispSync offset. Any additional delays introduced by the hardware
920 // composer or panel must be accounted for here.
921 //
922 // We add an additional 1ms to allow for processing time and
923 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800924 info.presentationDeadline =
925 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700926
927 // All non-virtual displays are currently considered secure.
928 info.secure = true;
929
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800930 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700931 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800932 std::swap(info.w, info.h);
933 }
934
Michael Wright28f24d02016-07-12 13:30:53 -0700935 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700936 }
937
Dan Stoza7f7da322014-05-02 15:26:25 -0700938 return NO_ERROR;
939}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
942 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700943 return BAD_VALUE;
944 }
945
Ana Krulece588e312018-09-18 12:32:24 -0700946 if (mUseScheduler) {
947 mScheduler->getDisplayStatInfo(stats);
948 } else {
949 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
950 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
951 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
966 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967
Ana Krulec7d1d6832018-12-27 11:10:09 -0800968 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 // Lock is acquired by setRefreshRateTo.
970 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800971 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
972 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
973 return;
974 }
975
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976 // Lock is acquired by setRefreshRateTo.
977 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800978 if (!display) {
979 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
980 displayToken.get());
981 return;
982 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700983 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800984 ALOGW("Attempt to set active config %d for virtual display", mode);
985 return;
986 }
987 int currentDisplayPowerMode = display->getPowerMode();
988 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
989 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700990 return;
991 }
992
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993 // Don't check against the current mode yet. Worst case we set the desired
994 // config twice.
995 {
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
998 }
999 // This will trigger HWC refresh without resetting the idle timer.
1000 repaintEverythingForHWC();
1001}
1002
1003status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1004 ATRACE_CALL();
1005 postMessageSync(new LambdaMessage(
1006 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1007 return NO_ERROR;
1008}
1009
1010void SurfaceFlinger::setActiveConfigInHWC() {
1011 ATRACE_CALL();
1012
1013 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1014 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 return;
1016 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 const auto displayId = display->getId();
1018 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1021 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1022 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1023 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1024}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026void SurfaceFlinger::setActiveConfigInternal() {
1027 ATRACE_CALL();
1028
1029 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1030 if (mUseScheduler) {
1031 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1032 }
1033
1034 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1035 display->setActiveConfig(mUpcomingActiveConfig.configId);
1036
1037 mSetActiveConfigState = SetActiveConfigState::NONE;
1038 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1039
Dominik Laskowski83b88212018-12-11 13:34:06 -08001040 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1042}
1043
1044bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1045 // Store the local variable to release the lock.
1046 ActiveConfigInfo desiredActiveConfig;
1047 {
1048 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1049 desiredActiveConfig = mDesiredActiveConfig;
1050 }
1051
1052 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1053 if (display) {
1054 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1055 display->getActiveConfig() != desiredActiveConfig.configId) {
1056 // Step 1) Desired active config was set, it is different than the
1057 // config currently in use. Notify HWC.
1058 mUpcomingActiveConfig = desiredActiveConfig;
1059 setActiveConfigInHWC();
1060 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1061 // Step 2) HWC was notified and we received refresh from it.
1062 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1063 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1064 repaintEverythingForHWC();
1065 // We do not want to give another frame to HWC while we are transitioning.
1066 return false;
1067 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1068 !(mPreviousPresentFence != Fence::NO_FENCE &&
1069 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1070 // Step 3) We received the present fence from the HWC, so we assume it
1071 // successfully updated the config, hence we update SF.
1072 setActiveConfigInternal();
1073 // If the config changed again while we were transitioning, restart the
1074 // process.
1075 if (desiredActiveConfig != mUpcomingActiveConfig) {
1076 mUpcomingActiveConfig = desiredActiveConfig;
1077 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1078 }
1079 }
1080 }
1081 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001082}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1085 Vector<ColorMode>* outColorModes) {
1086 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001087 return BAD_VALUE;
1088 }
1089
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001091 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001092 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1093
1094 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1095 if (!displayId) {
1096 return NAME_NOT_FOUND;
1097 }
1098
Dominik Laskowski075d3172018-05-24 15:50:06 -07001099 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001100 }
Michael Wright28f24d02016-07-12 13:30:53 -07001101 outColorModes->clear();
1102 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1103
1104 return NO_ERROR;
1105}
1106
Daniel Solomon42d04562019-01-20 21:03:19 -08001107status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1108 ui::DisplayPrimaries &primaries) {
1109 if (!displayToken) {
1110 return BAD_VALUE;
1111 }
1112
1113 // Currently we only support this API for a single internal display.
1114 if (getInternalDisplayToken() != displayToken) {
1115 return BAD_VALUE;
1116 }
1117
1118 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1123 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001124 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001125 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001126 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001130 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131 Vector<ColorMode> modes;
1132 getDisplayColorModes(displayToken, &modes);
1133 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1134 if (mode < ColorMode::NATIVE || !exists) {
1135 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1136 decodeColorMode(mode).c_str(), mode, displayToken.get());
1137 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001138 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 const auto display = getDisplayDevice(displayToken);
1140 if (!display) {
1141 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1142 decodeColorMode(mode).c_str(), mode, displayToken.get());
1143 } else if (display->isVirtual()) {
1144 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1145 decodeColorMode(mode).c_str(), mode);
1146 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001147 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1148 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 }
1150 }));
1151
Michael Wright28f24d02016-07-12 13:30:53 -07001152 return NO_ERROR;
1153}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001154
Svetoslavd85084b2014-03-20 10:28:31 -07001155status_t SurfaceFlinger::clearAnimationFrameStats() {
1156 Mutex::Autolock _l(mStateLock);
1157 mAnimFrameTracker.clearStats();
1158 return NO_ERROR;
1159}
1160
1161status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1162 Mutex::Autolock _l(mStateLock);
1163 mAnimFrameTracker.getStats(outStats);
1164 return NO_ERROR;
1165}
1166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001167status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1168 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001169 Mutex::Autolock _l(mStateLock);
1170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171 const auto display = getDisplayDeviceLocked(displayToken);
1172 if (!display) {
1173 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001174 return BAD_VALUE;
1175 }
1176
Peiyong Linfb069302018-04-25 14:34:31 -07001177 // At this point the DisplayDeivce should already be set up,
1178 // meaning the luminance information is already queried from
1179 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001180 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001181 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1182 capabilities.getDesiredMaxLuminance(),
1183 capabilities.getDesiredMaxAverageLuminance(),
1184 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001185
1186 return NO_ERROR;
1187}
1188
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001189status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1190 ui::PixelFormat* outFormat,
1191 ui::Dataspace* outDataspace,
1192 uint8_t* outComponentMask) const {
1193 if (!outFormat || !outDataspace || !outComponentMask) {
1194 return BAD_VALUE;
1195 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001196 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001197 if (!display || !display->getId()) {
1198 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1199 return BAD_VALUE;
1200 }
1201 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1202 outDataspace, outComponentMask);
1203}
1204
Kevin DuBois74e53772018-11-19 10:52:38 -08001205status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1206 bool enable, uint8_t componentMask,
1207 uint64_t maxFrames) const {
1208 const auto display = getDisplayDevice(displayToken);
1209 if (!display || !display->getId()) {
1210 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1211 return BAD_VALUE;
1212 }
1213
1214 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1215 componentMask, maxFrames);
1216}
1217
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001218status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1219 uint64_t maxFrames, uint64_t timestamp,
1220 DisplayedFrameStats* outStats) const {
1221 const auto display = getDisplayDevice(displayToken);
1222 if (!display || !display->getId()) {
1223 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1224 return BAD_VALUE;
1225 }
1226
1227 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1228 outStats);
1229}
1230
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001231status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1232 if (!outSupported) {
1233 return BAD_VALUE;
1234 }
1235 *outSupported = getRenderEngine().supportsProtectedContent();
1236 return NO_ERROR;
1237}
1238
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001239status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1240 bool* outIsWideColorDisplay) const {
1241 if (!displayToken || !outIsWideColorDisplay) {
1242 return BAD_VALUE;
1243 }
1244 Mutex::Autolock _l(mStateLock);
1245 const auto display = getDisplayDeviceLocked(displayToken);
1246 if (!display) {
1247 return BAD_VALUE;
1248 }
1249 *outIsWideColorDisplay = display->hasWideColorGamut();
1250 return NO_ERROR;
1251}
1252
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001254 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001256
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257 if (mInjectVSyncs == enable) {
1258 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001259 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260
Dominik Laskowski83b88212018-12-11 13:34:06 -08001261 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262
Ana Krulec98b5b242018-08-10 15:03:23 -07001263 // TODO(akrulec): Part of the Injector should be refactored, so that it
1264 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 if (enable) {
1266 ALOGV("VSync Injections enabled");
1267 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001268 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001269 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001271 impl::EventThread::InterceptVSyncsCallback(),
1272 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 } else {
1276 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001277 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001278 }
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001281 }));
1282
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001283 return NO_ERROR;
1284}
1285
1286status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001287 Mutex::Autolock _l(mStateLock);
1288
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001289 if (!mInjectVSyncs) {
1290 ALOGE("VSync Injections not enabled");
1291 return BAD_VALUE;
1292 }
1293 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1294 ALOGV("Injecting VSync inside SurfaceFlinger");
1295 mVSyncInjector->onInjectSyncEvent(when);
1296 }
1297 return NO_ERROR;
1298}
1299
Lloyd Pique755e3192018-01-31 16:46:15 -08001300status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1301 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001302 // Try to acquire a lock for 1s, fail gracefully
1303 const status_t err = mStateLock.timedLock(s2ns(1));
1304 const bool locked = (err == NO_ERROR);
1305 if (!locked) {
1306 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1307 return TIMED_OUT;
1308 }
1309
1310 outLayers->clear();
1311 mCurrentState.traverseInZOrder([&](Layer* layer) {
1312 outLayers->push_back(layer->getLayerDebugInfo());
1313 });
1314
1315 mStateLock.unlock();
1316 return NO_ERROR;
1317}
1318
Peiyong Linc6780972018-10-28 15:24:08 -07001319status_t SurfaceFlinger::getCompositionPreference(
1320 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1321 Dataspace* outWideColorGamutDataspace,
1322 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001325 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001326 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001327 return NO_ERROR;
1328}
1329
Dan Stoza84ab9372018-12-17 15:27:57 -08001330status_t SurfaceFlinger::addRegionSamplingListener(
1331 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1332 const sp<IRegionSamplingListener>& /*listener*/) {
1333 return NO_ERROR;
1334}
1335
1336status_t SurfaceFlinger::removeRegionSamplingListener(
1337 const sp<IRegionSamplingListener>& /*listener*/) {
1338 return NO_ERROR;
1339}
1340
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001341// ----------------------------------------------------------------------------
1342
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001343sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1344 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001345 auto resyncCallback = makeResyncCallback([this] {
1346 Mutex::Autolock lock(mStateLock);
1347 return getVsyncPeriod();
1348 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001349
Ana Krulec98b5b242018-08-10 15:03:23 -07001350 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001351 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1352 : mAppConnectionHandle;
1353
Ady Abrahama1a49af2019-02-07 14:36:55 -08001354 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001355 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001356 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001357 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001358 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001359 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001360 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001361 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001362}
1363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001364// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365
1366void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001367 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001368}
1369
1370void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001375 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376}
1377
1378void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001379 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381}
1382
1383status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001384 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001385 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386}
1387
1388status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001389 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001390 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 if (res == NO_ERROR) {
1392 msg->wait();
1393 }
1394 return res;
1395}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001397void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001398 do {
1399 waitForEvent();
1400 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401}
1402
Dominik Laskowski83b88212018-12-11 13:34:06 -08001403nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001404 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001405 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1406 return 0;
1407 }
1408
1409 const auto config = getHwComposer().getActiveConfig(*displayId);
1410 return config ? config->getVsyncPeriod() : 0;
1411}
1412
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001413void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001414 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001415 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001416 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001417 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001418 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001419 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001420 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001421}
1422
Dominik Laskowski83b88212018-12-11 13:34:06 -08001423void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001424 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001425 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1426 if (mUseScheduler) {
1427 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001428 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001429 } else if (!mScheduler->getHWSyncAvailable()) {
1430 // Hardware vsync is not currently available, so abort the resync
1431 // attempt for now
1432 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001433 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001434 } else {
1435 if (makeAvailable) {
1436 mHWVsyncAvailable = true;
1437 } else if (!mHWVsyncAvailable) {
1438 // Hardware vsync is not currently available, so abort the resync
1439 // attempt for now
1440 return;
1441 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001442 }
1443
Dominik Laskowski83b88212018-12-11 13:34:06 -08001444 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001445 return;
1446 }
1447
Ana Krulece588e312018-09-18 12:32:24 -07001448 if (mUseScheduler) {
1449 mScheduler->setVsyncPeriod(period);
1450 } else {
1451 mPrimaryDispSync->reset();
1452 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001453
Ana Krulece588e312018-09-18 12:32:24 -07001454 if (!mPrimaryHWVsyncEnabled) {
1455 mPrimaryDispSync->beginResync();
1456 mEventControlThread->setVsyncEnabled(true);
1457 mPrimaryHWVsyncEnabled = true;
1458 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001459 }
1460}
1461
Jesse Hall948fe0c2013-10-14 12:56:09 -07001462void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001463 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001464 Mutex::Autolock _l(mHWVsyncLock);
1465 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001466 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001467 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001468 mPrimaryHWVsyncEnabled = false;
1469 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001470 if (makeUnavailable) {
1471 mHWVsyncAvailable = false;
1472 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001473}
1474
Dominik Laskowski83b88212018-12-11 13:34:06 -08001475void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001476 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001477
Dan Stoza57164302017-05-08 14:03:54 -07001478 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001479 const nsecs_t last = lastResyncTime.exchange(now);
1480
1481 if (now - last > kIgnoreDelay) {
1482 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001483 }
1484}
1485
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001486void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1487 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001488 ATRACE_NAME("SF onVsync");
1489
Steven Thomas3cfac282017-02-06 12:29:30 -08001490 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001492 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 return;
1494 }
1495
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001497 return;
1498 }
1499
Dominik Laskowski075d3172018-05-24 15:50:06 -07001500 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001501 // For now, we don't do anything with external display vsyncs.
1502 return;
1503 }
1504
Ana Krulece588e312018-09-18 12:32:24 -07001505 if (mUseScheduler) {
1506 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001507 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001508 bool needsHwVsync = false;
1509 { // Scope for the lock
1510 Mutex::Autolock _l(mHWVsyncLock);
1511 if (mPrimaryHWVsyncEnabled) {
1512 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1513 }
1514 }
1515
1516 if (needsHwVsync) {
1517 enableHardwareVsync();
1518 } else {
1519 disableHardwareVsync(false);
1520 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001521 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001522}
1523
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001525 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1526 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527}
1528
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001529void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1530 mPhaseOffsets->setRefreshRateType(refreshRate);
1531
1532 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1533 mVsyncModulator.setPhaseOffsets(early, gl, late);
1534
1535 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001536 return;
1537 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001538
Ana Krulec7d1d6832018-12-27 11:10:09 -08001539 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1540 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1541 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1542 // refresh cycle.
1543
1544 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001545 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001546 if (currentVsyncPeriod == 0) {
1547 return;
1548 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001549
Ana Krulec7d1d6832018-12-27 11:10:09 -08001550 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1551 // floating numbers.
1552 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001553 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1554 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001555 if (std::abs(currentFps - newFps) <= 1) {
1556 return;
1557 }
1558
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001559 const auto displayId = getInternalDisplayIdLocked();
1560 LOG_ALWAYS_FATAL_IF(!displayId);
1561
1562 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001563 for (int i = 0; i < configs.size(); i++) {
1564 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1565 if (vsyncPeriod == 0) {
1566 continue;
1567 }
1568 const float fps = 1e9 / vsyncPeriod;
1569 // TODO(b/113612090): There should be a better way at determining which config
1570 // has the right refresh rate.
1571 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001572 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001573 }
1574 }
1575}
1576
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001577void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001578 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001579 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001580 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581
Lloyd Piqueba04e622017-12-14 17:11:26 -08001582 // Ignore events that do not have the right sequenceId.
1583 if (sequenceId != getBE().mComposerSequenceId) {
1584 return;
1585 }
1586
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 // Only lock if we're not on the main thread. This function is normally
1588 // called on a hwbinder thread, but for the primary display it's called on
1589 // the main thread with the state lock already held, so don't attempt to
1590 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001591 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001592
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001593 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001594
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001595 if (std::this_thread::get_id() == mMainThreadId) {
1596 // Process all pending hot plug events immediately if we are on the main thread.
1597 processDisplayHotplugEventsLocked();
1598 }
1599
Lloyd Piqueba04e622017-12-14 17:11:26 -08001600 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001601}
1602
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001603void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001604 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001605 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001607 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001608 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001609}
1610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001611void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001612 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001613 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001614 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001615 getHwComposer().setVsyncEnabled(*displayId,
1616 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1617 }
Mathias Agopian86303202012-07-24 22:46:10 -07001618}
1619
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001620// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001621void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001622 if (mUseScheduler) {
1623 mScheduler->disableHardwareVsync(true);
1624 } else {
1625 disableHardwareVsync(true);
1626 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001627 // Clear the drawing state so that the logic inside of
1628 // handleTransactionLocked will fire. It will determine the delta between
1629 // mCurrentState and mDrawingState and re-apply all changes when we make the
1630 // transition.
1631 mDrawingState.displays.clear();
1632 mDisplays.clear();
1633}
1634
Steven Thomas050b2c82017-03-06 11:45:16 -08001635void SurfaceFlinger::updateVrFlinger() {
1636 if (!mVrFlinger)
1637 return;
1638 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001639 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001640 return;
1641 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642
Lloyd Pique441d5042018-10-18 16:49:51 -07001643 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001644 ALOGE("Vr flinger is only supported for remote hardware composer"
1645 " service connections. Ignoring request to transition to vr"
1646 " flinger.");
1647 mVrFlingerRequestsDisplay = false;
1648 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001649 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001652
Steven Thomas0123ac62018-07-12 11:32:34 -07001653 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001654 LOG_ALWAYS_FATAL_IF(!display);
1655 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001656 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1657 // called below. Clear the reference now so we don't accidentally use it
1658 // later.
1659 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001660
Steven Thomasb02664d2017-07-26 18:48:28 -07001661 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001663 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001664
Steven Thomasb02664d2017-07-26 18:48:28 -07001665 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001666 // Delete the current instance before creating the new one
1667 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1668 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1669 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1670 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001671
Lloyd Pique441d5042018-10-18 16:49:51 -07001672 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001673 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001674
1675 if (vrFlingerRequestsDisplay) {
1676 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001677 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001678
1679 mVisibleRegionsDirty = true;
1680 invalidateHwcGeometry();
1681
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001682 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001683 display = getDefaultDisplayDeviceLocked();
1684 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001685 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001686
Steven Thomasb02664d2017-07-26 18:48:28 -07001687 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001688 const nsecs_t vsyncPeriod = getVsyncPeriod();
1689 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001690
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001691 // The present fences returned from vr_hwc are not an accurate
1692 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001693 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001694 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1695 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001696 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001698 !hasSyncFramework);
1699 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001700
Steven Thomasb02664d2017-07-26 18:48:28 -07001701 // Use phase of 0 since phase is not known.
1702 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001703 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001704 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001705
Dominik Laskowski83b88212018-12-11 13:34:06 -08001706 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001707
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001708 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710}
1711
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001713 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001714 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001715 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001716 if (!updateSetActiveConfigStateMachine()) {
1717 break;
1718 }
1719
Ana Krulec3084c052018-11-21 20:27:17 +01001720 if (mUseScheduler) {
1721 // This call is made each time SF wakes up and creates a new frame.
1722 mScheduler->incrementFrameCounter();
1723 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001724 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1725 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001726 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001727 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001728 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001729 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001730 if (mPropagateBackpressure) {
1731 signalLayerUpdate();
1732 break;
1733 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001734 }
Dan Stoza50182882016-07-08 12:02:20 -07001735
Steven Thomas050b2c82017-03-06 11:45:16 -08001736 // Now that we're going to make it to the handleMessageTransaction()
1737 // call below it's safe to call updateVrFlinger(), which will
1738 // potentially trigger a display handoff.
1739 updateVrFlinger();
1740
Dan Stoza6b9454d2014-11-07 16:00:59 -08001741 bool refreshNeeded = handleMessageTransaction();
1742 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001743
1744 updateCursorAsync();
1745 updateInputFlinger();
1746
Dan Stoza58784442014-12-02 16:58:17 -08001747 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001748 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001749 // Signal a refresh if a transaction modified the window state,
1750 // a new buffer was latched, or if HWC has requested a full
1751 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001752 signalRefresh();
1753 }
1754 break;
1755 }
1756 case MessageQueue::REFRESH: {
1757 handleMessageRefresh();
1758 break;
1759 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001760 }
1761}
1762
Dan Stoza6b9454d2014-11-07 16:00:59 -08001763bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001764 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001765
1766 // Apply any ready transactions in the queues if there are still transactions that have not been
1767 // applied, wake up during the next vsync period and check again
1768 bool transactionNeeded = false;
1769 if (!flushTransactionQueues()) {
1770 transactionNeeded = true;
1771 }
1772
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001774 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001776
1777 if (transactionNeeded) {
1778 setTransactionFlags(eTransactionNeeded);
1779 }
1780
1781 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001782}
1783
Mathias Agopian4fec8732012-06-29 14:12:52 -07001784void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001786
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001787 mRefreshPending = false;
1788
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001789 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001790 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001791 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001792 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793 for (const auto& [token, display] : mDisplays) {
1794 beginFrame(display);
1795 prepareFrame(display);
1796 doDebugFlashRegions(display, repaintEverything);
1797 doComposition(display, repaintEverything);
1798 }
1799
Adrian Roos1e1a1282017-11-01 19:05:31 +01001800 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001801 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001802
1803 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001804 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001805
Dan Stozabfbffeb2016-07-21 14:49:33 -07001806 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807 for (const auto& [token, displayDevice] : mDisplays) {
1808 auto display = displayDevice->getCompositionDisplay();
1809 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001810 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001812 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001813
Alec Mouri86770e52018-09-24 22:40:58 +00001814 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001815 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001816 if (mHadClientComposition) {
1817 base::unique_fd flushFence(getRenderEngine().flush());
1818 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1819 getBE().flushFence = new Fence(std::move(flushFence));
1820 } else {
1821 // Cleanup for hygiene.
1822 getBE().flushFence = Fence::NO_FENCE;
1823 }
1824 }
1825
Jorim Jaggi90535212018-05-23 23:44:06 +02001826 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001827
David Sodman7e4ae112018-02-09 15:02:28 -08001828 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001829 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001830 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001831 compositionInfo.hwc.hwcLayer = nullptr;
1832 }
David Sodmanba340492018-08-05 21:51:33 -07001833 }
David Sodman7e4ae112018-02-09 15:02:28 -08001834
1835 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001837
David Sodmanfa9b2af2017-12-24 13:28:59 -08001838
1839bool SurfaceFlinger::handleMessageInvalidate() {
1840 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001841 bool refreshNeeded = handlePageFlip();
1842
Vishnu Nair4351ad52019-02-11 14:13:02 -08001843 if (mVisibleRegionsDirty) {
1844 computeLayerBounds();
1845 }
1846
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001847 for (auto& layer : mLayersPendingRefresh) {
1848 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001849 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001850 invalidateLayerStack(layer, visibleReg);
1851 }
1852 mLayersPendingRefresh.clear();
1853 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001854}
1855
David Sodman79bba0e2018-08-05 18:07:49 -07001856void SurfaceFlinger::calculateWorkingSet() {
1857 ATRACE_CALL();
1858 ALOGV(__FUNCTION__);
1859
David Sodman79bba0e2018-08-05 18:07:49 -07001860 // build the h/w work list
1861 if (CC_UNLIKELY(mGeometryInvalid)) {
1862 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 for (const auto& [token, displayDevice] : mDisplays) {
1864 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001865 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001866 if (!displayId) {
1867 continue;
1868 }
David Sodman79bba0e2018-08-05 18:07:49 -07001869
Lloyd Pique32cbe282018-10-19 13:09:22 -07001870 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 for (size_t i = 0; i < currentLayers.size(); i++) {
1872 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001873
Dominik Laskowski075d3172018-05-24 15:50:06 -07001874 if (!layer->hasHwcLayer(*displayId)) {
1875 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1876 layer->forceClientComposition(*displayId);
1877 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001878 }
1879 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001880
Lloyd Pique32cbe282018-10-19 13:09:22 -07001881 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001882 if (mDebugDisableHWC || mDebugRegion) {
1883 layer->forceClientComposition(*displayId);
1884 }
David Sodman79bba0e2018-08-05 18:07:49 -07001885 }
1886 }
1887 }
1888
1889 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 for (const auto& [token, displayDevice] : mDisplays) {
1891 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001892 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001893 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001894 continue;
1895 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001896 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001897
1898 if (mDrawingState.colorMatrixChanged) {
1899 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001900 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001901 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001902 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001903 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001904 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1905 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001906 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001907 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001908 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1909 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001910 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001911 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001912 }
1913
Peiyong Lind3788632018-09-18 16:01:31 -07001914 // TODO(b/111562338) remove when composer 2.3 is shipped.
1915 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001916 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001917 }
1918
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001919 if (layer->getRoundedCornerState().radius > 0.0f) {
1920 layer->forceClientComposition(*displayId);
1921 }
1922
Dominik Laskowski075d3172018-05-24 15:50:06 -07001923 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001924 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001925 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001926 continue;
1927 }
1928
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 const auto& displayState = display->getState();
1930 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1931 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001932 }
1933
Peiyong Lin13effd12018-07-24 17:01:47 -07001934 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001935 ColorMode colorMode;
1936 Dataspace dataSpace;
1937 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001938 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001940 }
1941 }
1942
1943 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001944
1945 for (const auto& [token, display] : mDisplays) {
1946 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001947 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001948 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001949
1950 if (displayId) {
1951 if (!layer->setHwcLayer(*displayId)) {
1952 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1953 }
1954 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001955 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001956
Dominik Laskowski05275f12018-11-01 15:03:24 -07001957 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001958 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1959 }
1960 }
David Sodman79bba0e2018-08-05 18:07:49 -07001961}
1962
Lloyd Pique32cbe282018-10-19 13:09:22 -07001963void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1964 bool repaintEverything) {
1965 auto display = displayDevice->getCompositionDisplay();
1966 const auto& displayState = display->getState();
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 // is debugging enabled
1969 if (CC_LIKELY(!mDebugRegion))
1970 return;
1971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001973 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001974 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001975 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001976 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001977 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001978 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001980 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001981 }
1982 }
1983
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001985
1986 if (mDebugRegion > 1) {
1987 usleep(mDebugRegion * 1000);
1988 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001989
Lloyd Pique32cbe282018-10-19 13:09:22 -07001990 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991}
1992
Adrian Roos1e1a1282017-11-01 19:05:31 +01001993void SurfaceFlinger::doTracing(const char* where) {
1994 ATRACE_CALL();
1995 ATRACE_NAME(where);
1996 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001997 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001998 }
1999}
2000
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002001void SurfaceFlinger::logLayerStats() {
2002 ATRACE_CALL();
2003 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002004 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 if (display->isPrimary()) {
2006 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002007 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002008 }
2009 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002010
2011 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002012 }
2013}
2014
David Sodman2b406362017-12-15 13:33:47 -08002015void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ATRACE_CALL();
2018 ALOGV("preComposition");
2019
David Sodman2b406362017-12-15 13:33:47 -08002020 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2021
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002023 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002024 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 needExtraInvalidate = true;
2026 }
Robert Carr2047fae2016-11-28 14:09:09 -08002027 });
2028
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029 if (needExtraInvalidate) {
2030 signalLayerUpdate();
2031 }
2032}
2033
Ana Krulece588e312018-09-18 12:32:24 -07002034void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2035 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036 // Update queue of past composite+present times and determine the
2037 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002038 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002039 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002040 while (!getBE().mCompositePresentTimes.empty()) {
2041 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 // Cached values should have been updated before calling this method,
2043 // which helps avoid duplicate syscalls.
2044 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2045 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2046 break;
2047 }
2048 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002049 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 }
2051
2052 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002053 while (getBE().mCompositePresentTimes.size() > 16) {
2054 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 }
2056
Ana Krulece588e312018-09-18 12:32:24 -07002057 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002058}
2059
Ana Krulece588e312018-09-18 12:32:24 -07002060void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2061 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 // Integer division and modulo round toward 0 not -inf, so we need to
2063 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002064 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2065 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2066 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067
Ana Krulec757f63a2019-01-25 10:46:18 -08002068 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002069 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002070 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002071 }
2072
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // Snap the latency to a value that removes scheduling jitter from the
2074 // composition and present times, which often have >1ms of jitter.
2075 // Reducing jitter is important if an app attempts to extrapolate
2076 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002077 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002078 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002079 nsecs_t bias = stats.vsyncPeriod / 2;
2080 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2081 nsecs_t snappedCompositeToPresentLatency =
2082 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083
David Sodman99974d22017-11-28 12:04:33 -08002084 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002085 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2086 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002087 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088}
2089
Ady Abraham8164d482019-01-11 14:47:59 -08002090// debug patch for b/119477596 - add stack guards to catch stack
2091// corruptions and disable clang optimizations.
2092// The code below is temporary and planned to be removed once stack
2093// corruptions are found.
2094#pragma clang optimize off
2095class StackGuard {
2096public:
2097 StackGuard(const char* name, const char* func, int line) {
2098 guarders.reserve(MIN_CAPACITY);
2099 guarders.push_back({this, name, func, line});
2100 validate();
2101 }
2102 ~StackGuard() {
2103 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2104 if (i->guard == this) {
2105 guarders.erase(i);
2106 break;
2107 }
2108 }
2109 }
2110
2111 static void validate() {
2112 for (const auto& guard : guarders) {
2113 if (guard.guard->cookie != COOKIE_VALUE) {
2114 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2115 CallStack stack(LOG_TAG);
2116 abort();
2117 }
2118 }
2119 }
2120
2121private:
2122 uint64_t cookie = COOKIE_VALUE;
2123 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2124 static constexpr size_t MIN_CAPACITY = 16;
2125
2126 struct GuarderElement {
2127 StackGuard* guard;
2128 const char* name;
2129 const char* func;
2130 int line;
2131 };
2132
2133 static std::vector<GuarderElement> guarders;
2134};
2135std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2136
2137#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2138
2139#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002140void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002141{
Ady Abraham8164d482019-01-11 14:47:59 -08002142 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 ATRACE_CALL();
2144 ALOGV("postComposition");
2145
Brian Anderson3546a3f2016-07-14 11:51:14 -07002146 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002147 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002148 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002149 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002150 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002151 }
Ady Abraham8164d482019-01-11 14:47:59 -08002152 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002153
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002154 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 const auto displayDevice = getDefaultDisplayDeviceLocked();
2156 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002157
David Sodman73beded2017-11-15 11:56:06 -08002158 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2161
Lloyd Pique32cbe282018-10-19 13:09:22 -07002162 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002163 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002164 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2165 ->getRenderSurface()
2166 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002167 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002168 } else {
2169 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2170 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002171
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
2173
David Sodman73beded2017-11-15 11:56:06 -08002174 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002175 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2176 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002177 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002179 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002180
Ana Krulece588e312018-09-18 12:32:24 -07002181 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002182 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002183 if (mUseScheduler) {
2184 mScheduler->getDisplayStatInfo(&stats);
2185 } else {
2186 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2187 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2188 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189
Ady Abraham8164d482019-01-11 14:47:59 -08002190 ASSERT_ON_STACK_GUARD();
2191
David Sodman2b406362017-12-15 13:33:47 -08002192 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002193 // when we started doing work for this frame, but that should be okay
2194 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002195 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002196 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 DEFINE_STACK_GUARD(compositorTiming);
2198
Brian Andersond0010582017-03-07 13:20:31 -08002199 {
David Sodman99974d22017-11-28 12:04:33 -08002200 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002201 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002202 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002203
2204 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002205 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002206
Robert Carr2047fae2016-11-28 14:09:09 -08002207 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002208 bool frameLatched =
2209 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2210 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002211 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002212 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002213 recordBufferingStats(layer->getName().string(),
2214 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002215 }
Ady Abraham8164d482019-01-11 14:47:59 -08002216 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002217 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002218
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002219 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002220 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002221 if (mUseScheduler) {
2222 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002224 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002225 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2226 enableHardwareVsync();
2227 } else {
2228 disableHardwareVsync(false);
2229 }
Ady Abraham8164d482019-01-11 14:47:59 -08002230 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002231 }
2232 }
2233
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002234 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002235 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2236 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002237 if (mUseScheduler) {
2238 mScheduler->enableHardwareVsync();
2239 } else {
2240 enableHardwareVsync();
2241 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002242 }
2243 }
2244
Ady Abraham8164d482019-01-11 14:47:59 -08002245 ASSERT_ON_STACK_GUARD();
2246
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002247 if (mAnimCompositionPending) {
2248 mAnimCompositionPending = false;
2249
Brian Anderson4e606e32017-03-16 15:34:57 -07002250 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002251 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002252 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002253
2254 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002256 // The HWC doesn't support present fences, so use the refresh
2257 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const nsecs_t presentTime =
2259 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002260 DEFINE_STACK_GUARD(presentTime);
2261
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002262 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002263 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264 }
2265 mAnimFrameTracker.advanceFrame();
2266 }
Dan Stozab90cf072015-03-05 11:05:59 -08002267
Ady Abraham8164d482019-01-11 14:47:59 -08002268 ASSERT_ON_STACK_GUARD();
2269
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002270 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002271 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002272 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002273 }
2274
Ady Abraham8164d482019-01-11 14:47:59 -08002275 ASSERT_ON_STACK_GUARD();
2276
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002277 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002278
Ady Abraham8164d482019-01-11 14:47:59 -08002279 ASSERT_ON_STACK_GUARD();
2280
Lloyd Pique32cbe282018-10-19 13:09:22 -07002281 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2282 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002283 return;
2284 }
2285
2286 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002287 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002288 if (mHasPoweredOff) {
2289 mHasPoweredOff = false;
2290 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002291 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002292 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002293 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002294 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002295 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2296 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002297 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002298 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002299 }
David Sodman4a36e932017-11-07 14:29:47 -08002300 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002301
2302 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002303 }
David Sodman4a36e932017-11-07 14:29:47 -08002304 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002305 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002306
2307 {
2308 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002309 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002310 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002311 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002312 if (refillCount > 0) {
2313 const size_t offset = mTexturePool.size();
2314 mTexturePool.resize(mTexturePoolSize);
2315 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2316 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2317 }
Ady Abraham8164d482019-01-11 14:47:59 -08002318 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002319 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002320
Marissa Wallfda30bb2018-10-12 11:34:28 -07002321 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002322 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002323
2324 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325}
Ady Abraham8164d482019-01-11 14:47:59 -08002326#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002327
Vishnu Nair4351ad52019-02-11 14:13:02 -08002328void SurfaceFlinger::computeLayerBounds() {
2329 for (const auto& pair : mDisplays) {
2330 const auto& displayDevice = pair.second;
2331 const auto display = displayDevice->getCompositionDisplay();
2332 for (const auto& layer : mDrawingState.layersSortedByZ) {
2333 // only consider the layers on the given layer stack
2334 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002335 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002336 }
2337
2338 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2339 }
2340 }
2341}
2342
Mathias Agopiancd60f992012-08-16 16:28:27 -07002343void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 ATRACE_CALL();
2345 ALOGV("rebuildLayerStacks");
2346
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002347 // We need to clear these out now as these may be holding on to a
2348 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2349 // also holds a reference. When the set of visible layers is recomputed,
2350 // some layers may be destroyed if the only thing keeping them alive was
2351 // that list of visible layers associated with each display. The layer
2352 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2353 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2354 for (const auto& [token, display] : mDisplays) {
2355 getBE().mCompositionInfo[token].clear();
2356 }
2357
Mathias Agopiancd60f992012-08-16 16:28:27 -07002358 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002359 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002360 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002361 mVisibleRegionsDirty = false;
2362 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002363
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002364 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002365 const auto& displayDevice = pair.second;
2366 auto display = displayDevice->getCompositionDisplay();
2367 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002368 Region opaqueRegion;
2369 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002370 compositionengine::Output::OutputLayers layersSortedByZ;
2371 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002372 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002373 const ui::Transform& tr = displayState.transform;
2374 const Rect bounds = displayState.bounds;
2375 if (displayState.isEnabled) {
2376 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002377
Jeff Sharkey76488112017-02-27 14:15:18 -07002378 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002379 auto compositionLayer = layer->getCompositionLayer();
2380 if (compositionLayer == nullptr) {
2381 return;
2382 }
2383
Chia-I Wu83806892017-11-16 10:50:20 -08002384 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002386 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2387 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2388
Lloyd Piqueef36b002019-01-23 17:52:04 -08002389 if (display->belongsInOutput(layer->getLayerStack(),
2390 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002391 Region drawRegion(tr.transform(
2392 layer->visibleNonTransparentRegion));
2393 drawRegion.andSelf(bounds);
2394 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002395 layersSortedByZ.emplace_back(
2396 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2397 layerFE));
2398
2399 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002400 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002401 // Clear out the HWC layer if this layer was
2402 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002404 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002405 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002406 // WM changes display->layerStack upon sleep/awake.
2407 // Here we make sure we delete the HWC layers even if
2408 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002410 }
2411
2412 // If a layer is not going to get a release fence because
2413 // it is invisible, but it is also going to release its
2414 // old buffer, add it to the list of layers needing
2415 // fences.
2416 if (hwcLayerDestroyed) {
2417 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2418 mLayersWithQueuedFrames.cend(), layer);
2419 if (found != mLayersWithQueuedFrames.cend()) {
2420 layersNeedingFences.add(layer);
2421 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002422 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002423 });
2424 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002425
2426 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2427
2428 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 displayDevice->setLayersNeedingFences(layersNeedingFences);
2430
2431 Region undefinedRegion{bounds};
2432 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2433
2434 display->editState().undefinedRegion = undefinedRegion;
2435 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002436 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002437 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002438}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002439
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002440// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002441// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002442// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002443// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002444// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002445// The returned HDR data space is one of
2446// - Dataspace::UNKNOWN
2447// - Dataspace::BT2020_HLG
2448// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2450 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002451 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002452 *outHdrDataSpace = Dataspace::UNKNOWN;
2453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002455 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002456 case Dataspace::V0_SCRGB:
2457 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002458 case Dataspace::BT2020:
2459 case Dataspace::BT2020_ITU:
2460 case Dataspace::BT2020_LINEAR:
2461 case Dataspace::DISPLAY_BT2020:
2462 bestDataSpace = Dataspace::DISPLAY_BT2020;
2463 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002464 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002465 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002466 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002467 case Dataspace::BT2020_PQ:
2468 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002469 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002470 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002471 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002472 case Dataspace::BT2020_HLG:
2473 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002474 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002475 // When there's mixed PQ content and HLG content, we set the HDR
2476 // data space to be BT2020_PQ and convert HLG to PQ.
2477 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2478 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002479 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002480 break;
2481 default:
2482 break;
2483 }
Romain Guy54f154a2017-10-24 21:40:32 +01002484 }
2485
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002486 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002487}
2488
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002489// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2491 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002492 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2493 *outMode = ColorMode::NATIVE;
2494 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002495 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002496 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002497 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002498
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002499 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002501
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002502 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2503
Peiyong Lina3ea5592019-02-10 14:45:00 -08002504 switch (mForceColorMode) {
2505 case ColorMode::SRGB:
2506 bestDataSpace = Dataspace::V0_SRGB;
2507 break;
2508 case ColorMode::DISPLAY_P3:
2509 bestDataSpace = Dataspace::DISPLAY_P3;
2510 break;
2511 default:
2512 break;
2513 }
2514
Peiyong Lindfde5112018-06-05 10:58:41 -07002515 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002516 const bool isHdr =
2517 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002518 if (isHdr) {
2519 bestDataSpace = hdrDataSpace;
2520 }
2521
Chia-I Wu0d711262018-05-21 15:19:35 -07002522 RenderIntent intent;
2523 switch (mDisplayColorSetting) {
2524 case DisplayColorSetting::MANAGED:
2525 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002526 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002527 break;
2528 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002529 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002530 break;
2531 default: // vendor display color setting
2532 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2533 break;
2534 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002535
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002536 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002537}
2538
Lloyd Pique32cbe282018-10-19 13:09:22 -07002539void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2540 auto display = displayDevice->getCompositionDisplay();
2541 const auto& displayState = display->getState();
2542
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002543 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2545 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002546
David Sodmanfa9b2af2017-12-24 13:28:59 -08002547 // If nothing has changed (!dirty), don't recompose.
2548 // If something changed, but we don't currently have any visible layers,
2549 // and didn't when we last did a composition, then skip it this time.
2550 // The second rule does two things:
2551 // - When all layers are removed from a display, we'll emit one black
2552 // frame, then nothing more until we get new layers.
2553 // - When a display is created with a private layer stack, we won't
2554 // emit any black frames until a layer is added to the layer stack.
2555 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002556
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 const char flagPrefix[] = {'-', '+'};
2558 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002559 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2560 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2561 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2562 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002563
Lloyd Pique31cb2942018-10-19 17:23:03 -07002564 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002565
David Sodmanfa9b2af2017-12-24 13:28:59 -08002566 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002567 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002568 }
2569}
2570
Lloyd Pique32cbe282018-10-19 13:09:22 -07002571void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2572 auto display = displayDevice->getCompositionDisplay();
2573 const auto& displayState = display->getState();
2574
2575 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002576 return;
David Sodman2b406362017-12-15 13:33:47 -08002577 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002578
Lloyd Pique31cb2942018-10-19 17:23:03 -07002579 status_t result = display->getRenderSurface()->prepareFrame(
2580 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002582 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002583}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002584
Lloyd Pique32cbe282018-10-19 13:09:22 -07002585void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002586 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("doComposition");
2588
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 auto display = displayDevice->getCompositionDisplay();
2590 const auto& displayState = display->getState();
2591
2592 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002593 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002594 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002595
David Sodmanfa9b2af2017-12-24 13:28:59 -08002596 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002597 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002598
Lloyd Pique32cbe282018-10-19 13:09:22 -07002599 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002600 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002601 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002602 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603}
2604
David Sodmanfa9b2af2017-12-24 13:28:59 -08002605void SurfaceFlinger::postFrame()
2606{
2607 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 const auto display = getDefaultDisplayDeviceLocked();
2609 if (display && getHwComposer().isConnected(*display->getId())) {
2610 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002611 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2612 logFrameStats();
2613 }
2614 }
2615}
2616
Lloyd Pique32cbe282018-10-19 13:09:22 -07002617void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002618 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002620
Lloyd Pique32cbe282018-10-19 13:09:22 -07002621 auto display = displayDevice->getCompositionDisplay();
2622 const auto& displayState = display->getState();
2623 const auto displayId = display->getId();
2624
David Sodmanfa9b2af2017-12-24 13:28:59 -08002625 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002626
Lloyd Pique32cbe282018-10-19 13:09:22 -07002627 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 if (displayId) {
2629 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002630 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002631 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002632 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002633 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002634
Chia-I Wu7b549592017-11-15 09:14:57 -08002635 // The layer buffer from the previous frame (if any) is released
2636 // by HWC only when the release fence from this frame (if any) is
2637 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 if (displayId && layer->hasHwcLayer(*displayId)) {
2639 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2640 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002641 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002642
2643 // If the layer was client composited in the previous frame, we
2644 // need to merge with the previous client target acquire fence.
2645 // Since we do not track that, always merge with the current
2646 // client target acquire fence when it is available, even though
2647 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002648 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002649 releaseFence =
2650 Fence::merge("LayerRelease", releaseFence,
2651 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002652 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002653
David Sodman15094112018-10-11 09:39:37 -07002654 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 }
Chia-I Wu83806892017-11-16 10:50:20 -08002656
2657 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002659 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002660 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002662 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002663 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002664 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002665 }
2666 }
2667
Dominik Laskowski075d3172018-05-24 15:50:06 -07002668 if (displayId) {
2669 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002670 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672}
2673
Mathias Agopian87baae12012-07-31 12:38:26 -07002674void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675{
Mathias Agopian841cde52012-03-01 15:44:37 -08002676 ATRACE_CALL();
2677
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002678 // here we keep a copy of the drawing state (that is the state that's
2679 // going to be overwritten by handleTransactionLocked()) outside of
2680 // mStateLock so that the side-effects of the State assignment
2681 // don't happen with mStateLock held (which can cause deadlocks).
2682 State drawingState(mDrawingState);
2683
Mathias Agopianca4d3602011-05-19 15:38:14 -07002684 Mutex::Autolock _l(mStateLock);
2685 const nsecs_t now = systemTime();
2686 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687
Mathias Agopianca4d3602011-05-19 15:38:14 -07002688 // Here we're guaranteed that some transaction flags are set
2689 // so we can call handleTransactionLocked() unconditionally.
2690 // We call getTransactionFlags(), which will also clear the flags,
2691 // with mStateLock held to guarantee that mCurrentState won't change
2692 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002693
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002694 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002695 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002696 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002697
Mathias Agopianca4d3602011-05-19 15:38:14 -07002698 mLastTransactionTime = systemTime() - now;
2699 mDebugInTransaction = 0;
2700 invalidateHwcGeometry();
2701 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002702}
2703
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2705 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002706 const std::optional<DisplayIdentificationInfo> info =
2707 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002708
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002710 continue;
2711 }
2712
Lloyd Piqueba04e622017-12-14 17:11:26 -08002713 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002715 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002716 mPhysicalDisplayTokens[info->id] = new BBinder();
2717 DisplayDeviceState state;
2718 state.displayId = info->id;
2719 state.isSecure = true; // All physical displays are currently considered secure.
2720 state.displayName = info->name;
2721 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2722 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002723 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002724 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002725 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002726
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2728 if (index >= 0) {
2729 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2730 mInterceptor->saveDisplayDeletion(state.sequenceId);
2731 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002732 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002734 }
2735
2736 processDisplayChangesLocked();
2737 }
2738
2739 mPendingHotplugEvents.clear();
2740}
2741
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002742void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002743 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002744 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2745 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002746 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002747 mEventThread->onHotplugReceived(displayId, connected);
2748 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002749 }
2750}
2751
Lloyd Pique99d3da52018-01-22 17:48:03 -08002752sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002754 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 const sp<IGraphicBufferProducer>& producer) {
2756 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002757 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002758 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002759 creationArgs.isSecure = state.isSecure;
2760 creationArgs.displaySurface = dispSurface;
2761 creationArgs.hasWideColorGamut = false;
2762 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002763
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002764 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 creationArgs.isPrimary = isInternalDisplay;
2766
2767 if (useColorManagement && displayId) {
2768 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002769 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002770 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002771 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002772 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002773
Dominik Laskowski7e045462018-05-30 13:02:02 -07002774 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002776 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002777 }
tangrobin6753a022018-08-10 10:58:54 +08002778 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002779
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 if (displayId) {
2781 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002782 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002784 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002785
Lloyd Pique90c115d2018-09-18 21:39:42 -07002786 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002787 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002788 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002789
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790 // Make sure that composition can never be stalled by a virtual display
2791 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002792 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002793 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2795 }
2796
Dominik Laskowski075d3172018-05-24 15:50:06 -07002797 creationArgs.displayInstallOrientation =
2798 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002799
Lloyd Pique99d3da52018-01-22 17:48:03 -08002800 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002801 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002802
Lloyd Pique90c115d2018-09-18 21:39:42 -07002803 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002804
2805 if (maxFrameBufferAcquiredBuffers >= 3) {
2806 nativeWindowSurface->preallocateBuffers();
2807 }
2808
2809 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002810 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002811 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002812 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002813 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002814 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002815 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2816 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817 if (!state.isVirtual()) {
2818 LOG_ALWAYS_FATAL_IF(!displayId);
2819 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002820 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 display->setLayerStack(state.layerStack);
2823 display->setProjection(state.orientation, state.viewport, state.frame);
2824 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002827}
2828
Lloyd Pique347200f2017-12-14 17:00:15 -08002829void SurfaceFlinger::processDisplayChangesLocked() {
2830 // here we take advantage of Vector's copy-on-write semantics to
2831 // improve performance by skipping the transaction entirely when
2832 // know that the lists are identical
2833 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2834 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2835 if (!curr.isIdenticalTo(draw)) {
2836 mVisibleRegionsDirty = true;
2837 const size_t cc = curr.size();
2838 size_t dc = draw.size();
2839
2840 // find the displays that were removed
2841 // (ie: in drawing state but not in current state)
2842 // also handle displays that changed
2843 // (ie: displays that are in both lists)
2844 for (size_t i = 0; i < dc;) {
2845 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2846 if (j < 0) {
2847 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002848 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002849 // Save display ID before disconnecting.
2850 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002851 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002852
2853 if (!display->isVirtual()) {
2854 LOG_ALWAYS_FATAL_IF(!displayId);
2855 dispatchDisplayHotplugEvent(displayId->value, false);
2856 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002858
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002860 } else {
2861 // this display is in both lists. see if something changed.
2862 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002864 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2865 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2866 if (state_binder != draw_binder) {
2867 // changing the surface is like destroying and
2868 // recreating the DisplayDevice, so we just remove it
2869 // from the drawing state, so that it get re-added
2870 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002872 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002875 mDrawingState.displays.removeItemsAt(i);
2876 dc--;
2877 // at this point we must loop to the next item
2878 continue;
2879 }
2880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002882 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002884 }
2885 if ((state.orientation != draw[i].orientation) ||
2886 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002888 }
2889 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002891 }
2892 }
2893 }
2894 ++i;
2895 }
2896
2897 // find displays that were added
2898 // (ie: in current state but not in drawing state)
2899 for (size_t i = 0; i < cc; i++) {
2900 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2901 const DisplayDeviceState& state(curr[i]);
2902
Lloyd Pique542307f2018-10-19 13:24:08 -07002903 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002904 sp<IGraphicBufferProducer> producer;
2905 sp<IGraphicBufferProducer> bqProducer;
2906 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002907 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002908
Dominik Laskowski075d3172018-05-24 15:50:06 -07002909 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002910 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002911 // Virtual displays without a surface are dormant:
2912 // they have external state (layer stack, projection,
2913 // etc.) but no internal state (i.e. a DisplayDevice).
2914 if (state.surface != nullptr) {
2915 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002916 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002917 int width = 0;
2918 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2919 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2920 int height = 0;
2921 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2922 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2923 int intFormat = 0;
2924 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2925 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002926 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002927
Dominik Laskowski075d3172018-05-24 15:50:06 -07002928 displayId =
2929 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002930 }
2931
2932 // TODO: Plumb requested format back up to consumer
2933
2934 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002935 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002936 bqProducer, bqConsumer,
2937 state.displayName);
2938
2939 dispSurface = vds;
2940 producer = vds;
2941 }
2942 } else {
2943 ALOGE_IF(state.surface != nullptr,
2944 "adding a supported display, but rendering "
2945 "surface is provided (%p), ignoring it",
2946 state.surface.get());
2947
Dominik Laskowski075d3172018-05-24 15:50:06 -07002948 displayId = state.displayId;
2949 LOG_ALWAYS_FATAL_IF(!displayId);
2950 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002951 producer = bqProducer;
2952 }
2953
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002954 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002955 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002957 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002958 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002959 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002960 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002961 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002962 }
2963 }
2964 }
2965 }
2966 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002967
2968 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002969}
2970
Mathias Agopian87baae12012-07-31 12:38:26 -07002971void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002972{
Dan Stoza7dde5992015-05-22 09:51:44 -07002973 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002974 mCurrentState.traverseInZOrder([](Layer* layer) {
2975 layer->notifyAvailableFrames();
2976 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002977
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 /*
2979 * Traversal of the children
2980 * (perform the transaction for each of them if needed)
2981 */
2982
Mathias Agopian3559b072012-08-15 13:46:03 -07002983 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002984 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002986 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987
2988 const uint32_t flags = layer->doTransaction(0);
2989 if (flags & Layer::eVisibleRegion)
2990 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002991
2992 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002993 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002994 }
Robert Carr2047fae2016-11-28 14:09:09 -08002995 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 }
2997
2998 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002999 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 */
3001
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08003003 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08003004 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07003005 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003007 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08003008 // The transform hint might have changed for some layers
3009 // (either because a display has changed, or because a layer
3010 // as changed).
3011 //
3012 // Walk through all the layers in currentLayers,
3013 // and update their transform hint.
3014 //
3015 // If a layer is visible only on a single display, then that
3016 // display is used to calculate the hint, otherwise we use the
3017 // default display.
3018 //
3019 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
3020 // the hint is set before we acquire a buffer from the surface texture.
3021 //
3022 // NOTE: layer transactions have taken place already, so we use their
3023 // drawing state. However, SurfaceFlinger's own transaction has not
3024 // happened yet, so we must use the current state layer list
3025 // (soon to become the drawing state list).
3026 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003027 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003028 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003029 bool first = true;
3030 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003031 // NOTE: we rely on the fact that layers are sorted by
3032 // layerStack first (so we don't have to traverse the list
3033 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003035 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003036 currentlayerStack = layerStack;
3037 // figure out if this layerstack is mirrored
3038 // (more than one display) if so, pick the default display,
3039 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003040 hintDisplay = nullptr;
3041 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003042 if (display->getCompositionDisplay()
3043 ->belongsInOutput(layer->getLayerStack(),
3044 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003045 if (hintDisplay) {
3046 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003047 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003049 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003050 }
3051 }
3052 }
3053 }
Chet Haase91d25932013-04-11 15:24:55 -07003054
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003055 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003056 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3057 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003058
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003059 // could be null when this layer is using a layerStack
3060 // that is not visible on any display. Also can occur at
3061 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003062 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003063 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003064
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003065 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003066 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003067 if (hintDisplay) {
3068 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003069 }
Robert Carr2047fae2016-11-28 14:09:09 -08003070
3071 first = false;
3072 });
Mathias Agopian84300952012-11-21 16:02:13 -08003073 }
3074
3075
Mathias Agopian3559b072012-08-15 13:46:03 -07003076 /*
3077 * Perform our own transaction if needed
3078 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079
3080 if (mLayersAdded) {
3081 mLayersAdded = false;
3082 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003083 mVisibleRegionsDirty = true;
3084 }
3085
3086 // some layers might have been removed, so
3087 // we need to update the regions they're exposing.
3088 if (mLayersRemoved) {
3089 mLayersRemoved = false;
3090 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003091 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003093 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003095 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003096 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003097 }
Robert Carr2047fae2016-11-28 14:09:09 -08003098 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 }
3100
3101 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003102}
3103
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003104void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003105 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003106 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003107 return;
3108 }
3109
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003110 if (mVisibleRegionsDirty || mInputInfoChanged) {
3111 mInputInfoChanged = false;
3112 updateInputWindowInfo();
3113 }
3114
3115 executeInputWindowCommands();
3116}
3117
3118void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003119 Vector<InputWindowInfo> inputHandles;
3120
3121 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3122 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003123 // When calculating the screen bounds we ignore the transparent region since it may
3124 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003125 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003126 }
3127 });
3128 mInputFlinger->setInputWindows(inputHandles);
3129}
3130
chaviwfbe5d9c2018-12-26 12:23:37 -08003131void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003132 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3133 if (transferTouchFocusCommand.fromToken != nullptr &&
3134 transferTouchFocusCommand.toToken != nullptr &&
3135 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3136 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3137 transferTouchFocusCommand.toToken);
3138 }
3139 }
3140
3141 mInputWindowCommands.clear();
3142}
3143
Riley Andrews03414a12014-07-01 14:22:59 -07003144void SurfaceFlinger::updateCursorAsync()
3145{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003146 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003147 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003148 continue;
3149 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003151 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3152 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003153 }
3154 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003155}
3156
chaviw61626f22018-11-15 16:26:27 -08003157void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3158 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003159 nsecs_t expectedPresentTime;
3160 if (mUseScheduler) {
3161 expectedPresentTime = mScheduler->expectedPresentTime();
3162 } else {
3163 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3164 }
chaviw61626f22018-11-15 16:26:27 -08003165 if (layer->shouldPresentNow(expectedPresentTime)) {
3166 bool ignored = false;
3167 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3168 }
3169 }
3170 layer->releasePendingBuffer(systemTime());
3171}
3172
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173void SurfaceFlinger::commitTransaction()
3174{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003175 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003176 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 for (const auto& l : mLayersPendingRemoval) {
3178 recordBufferingStats(l->getName().string(),
3179 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003180
3181 // We need to release the HWC layers when the Layer is removed
3182 // from the current state otherwise the HWC layer just continues
3183 // showing at its last configured state until we eventually
3184 // abandon the buffer queue.
3185 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003186 l->destroyHwcLayersForAllDisplays();
3187 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003188 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003189 }
3190 mLayersPendingRemoval.clear();
3191 }
3192
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003193 // If this transaction is part of a window animation then the next frame
3194 // we composite should be considered an animation as well.
3195 mAnimCompositionPending = mAnimTransactionPending;
3196
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003198 // clear the "changed" flags in current state
3199 mCurrentState.colorMatrixChanged = false;
3200
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 mDrawingState.traverseInZOrder([](Layer* layer) {
3202 layer->commitChildList();
3203 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003204 mTransactionPending = false;
3205 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003206 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Lloyd Pique32cbe282018-10-19 13:09:22 -07003209void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003210 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003211 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003212 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003213
Lloyd Pique32cbe282018-10-19 13:09:22 -07003214 auto display = displayDevice->getCompositionDisplay();
3215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 Region aboveOpaqueLayers;
3217 Region aboveCoveredLayers;
3218 Region dirty;
3219
Mathias Agopian87baae12012-07-31 12:38:26 -07003220 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003223 // start with the whole surface at its current location
3224 const Layer::State& s(layer->getDrawingState());
3225
Jesse Hall01e29052013-02-19 16:13:35 -08003226 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003227 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003228 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003229 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003230
Mathias Agopianab028732010-03-16 16:41:46 -07003231 /*
3232 * opaqueRegion: area of a surface that is fully opaque.
3233 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003235
3236 /*
3237 * visibleRegion: area of a surface that is visible on screen
3238 * and not fully transparent. This is essentially the layer's
3239 * footprint minus the opaque regions above it.
3240 * Areas covered by a translucent surface are considered visible.
3241 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003243
3244 /*
3245 * coveredRegion: area of a surface that is covered by all
3246 * visible regions above it (which includes the translucent areas).
3247 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003249
Jesse Halla8026d22012-09-25 13:25:04 -07003250 /*
3251 * transparentRegion: area of a surface that is hinted to be completely
3252 * transparent. This is only used to tell when the layer has no visible
3253 * non-transparent regions and can be removed from the layer list. It
3254 * does not affect the visibleRegion of this layer or any layers
3255 * beneath it. The hint may not be correct if apps don't respect the
3256 * SurfaceView restrictions (which, sadly, some don't).
3257 */
3258 Region transparentRegion;
3259
Mathias Agopianab028732010-03-16 16:41:46 -07003260
3261 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003262 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003263 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003264 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003267 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003268 if (!visibleRegion.isEmpty()) {
3269 // Remove the transparent area from the visible region
3270 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003271 if (tr.preserveRects()) {
3272 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003273 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003274 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003275 // transformation too complex, can't do the
3276 // transparent region optimization.
3277 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003278 }
Mathias Agopianab028732010-03-16 16:41:46 -07003279 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280
Mathias Agopianab028732010-03-16 16:41:46 -07003281 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003282 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003283 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003284 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003285 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003286 // the opaque region is the layer's footprint
3287 opaqueRegion = visibleRegion;
3288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 }
3290 }
3291
Robert Carre5f4f692018-01-12 13:12:28 -08003292 if (visibleRegion.isEmpty()) {
3293 layer->clearVisibilityRegions();
3294 return;
3295 }
3296
Mathias Agopianab028732010-03-16 16:41:46 -07003297 // Clip the covered region to the visible region
3298 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3299
3300 // Update aboveCoveredLayers for next (lower) layer
3301 aboveCoveredLayers.orSelf(visibleRegion);
3302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303 // subtract the opaque region covered by the layers above us
3304 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305
3306 // compute this layer's dirty region
3307 if (layer->contentDirty) {
3308 // we need to invalidate the whole region
3309 dirty = visibleRegion;
3310 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003311 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003312 layer->contentDirty = false;
3313 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003314 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003315 * the exposed region consists of two components:
3316 * 1) what's VISIBLE now and was COVERED before
3317 * 2) what's EXPOSED now less what was EXPOSED before
3318 *
3319 * note that (1) is conservative, we start with the whole
3320 * visible region but only keep what used to be covered by
3321 * something -- which mean it may have been exposed.
3322 *
3323 * (2) handles areas that were not covered by anything but got
3324 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003325 */
Mathias Agopianab028732010-03-16 16:41:46 -07003326 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003327 const Region oldVisibleRegion = layer->visibleRegion;
3328 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003329 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3330 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 }
3332 dirty.subtractSelf(aboveOpaqueLayers);
3333
3334 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003335 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336
Mathias Agopianab028732010-03-16 16:41:46 -07003337 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003339
Jesse Halla8026d22012-09-25 13:25:04 -07003340 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341 layer->setVisibleRegion(visibleRegion);
3342 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003343 layer->setVisibleNonTransparentRegion(
3344 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003345 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346
Mathias Agopian87baae12012-07-31 12:38:26 -07003347 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348}
3349
Chia-I Wuab0c3192017-08-01 11:29:00 -07003350void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003351 for (const auto& [token, displayDevice] : mDisplays) {
3352 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003353 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003354 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003355 }
3356 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003357}
3358
Daniel Solomon42d04562019-01-20 21:03:19 -08003359void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3360 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3361 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3362 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3363 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3364 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3365 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3366 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3367 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3368 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3369 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3370 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3371 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3372}
3373
Dan Stoza6b9454d2014-11-07 16:00:59 -08003374bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003376 ALOGV("handlePageFlip");
3377
Brian Andersond6927fb2016-07-23 23:37:30 -07003378 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379
Mathias Agopian4fec8732012-06-29 14:12:52 -07003380 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003381 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003382 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003383
3384 // Store the set of layers that need updates. This set must not change as
3385 // buffers are being latched, as this could result in a deadlock.
3386 // Example: Two producers share the same command stream and:
3387 // 1.) Layer 0 is latched
3388 // 2.) Layer 0 gets a new frame
3389 // 2.) Layer 1 gets a new frame
3390 // 3.) Layer 1 is latched.
3391 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3392 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003393 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003394 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003395 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003396 nsecs_t expectedPresentTime;
3397 if (mUseScheduler) {
3398 expectedPresentTime = mScheduler->expectedPresentTime();
3399 } else {
3400 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3401 }
Ana Krulec010d2192018-10-08 06:29:54 -07003402 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003403 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003404 } else {
3405 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003406 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003407 } else {
3408 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003409 }
Robert Carr2047fae2016-11-28 14:09:09 -08003410 });
3411
Lloyd Piquef2c79392018-12-20 16:23:33 -08003412 if (!mLayersWithQueuedFrames.empty()) {
3413 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3414 // writes to Layer current state. See also b/119481871
3415 Mutex::Autolock lock(mStateLock);
3416
3417 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003418 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3419 mLayersPendingRefresh.push_back(layer);
3420 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003421 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003422 if (layer->isBufferLatched()) {
3423 newDataLatched = true;
3424 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003425 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003426 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003427
Alec Mouri86770e52018-09-24 22:40:58 +00003428 // Clear the renderengine fence here...
3429 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3430 // clear instead of sp::clear.
3431 getBE().flushFence = Fence::NO_FENCE;
3432
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003433 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003434
3435 // If we will need to wake up at some time in the future to deal with a
3436 // queued frame that shouldn't be displayed during this vsync period, wake
3437 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003438 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003439 signalLayerUpdate();
3440 }
3441
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003442 // enter boot animation on first buffer latch
3443 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3444 ALOGI("Enter boot animation");
3445 mBootStage = BootStage::BOOTANIMATION;
3446 }
3447
Dan Stoza6b9454d2014-11-07 16:00:59 -08003448 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003449 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450}
3451
Mathias Agopianad456f92011-01-13 17:53:01 -08003452void SurfaceFlinger::invalidateHwcGeometry()
3453{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003454 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003455}
3456
Lloyd Pique32cbe282018-10-19 13:09:22 -07003457void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003458 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003459 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003460 // We only need to actually compose the display if:
3461 // 1) It is being handled by hardware composer, which may need this to
3462 // keep its virtual display state machine in sync, or
3463 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003464 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003465 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003466 return;
3467 }
3468
Dan Stoza9e56aa02015-11-02 13:00:03 -08003469 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003470 base::unique_fd readyFence;
3471 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003472
3473 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003474 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475}
3476
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003477bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3478 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003479 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003480 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003481
Lloyd Pique32cbe282018-10-19 13:09:22 -07003482 auto display = displayDevice->getCompositionDisplay();
3483 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003484 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003485
3486 const Region bounds(displayState.bounds);
3487 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003488 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003489 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003490
Peiyong Lind3788632018-09-18 16:01:31 -07003491 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003492 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003493
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003494 renderengine::DisplaySettings clientCompositionDisplay;
3495 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3496 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003497
Dan Stoza9e56aa02015-11-02 13:00:03 -08003498 if (hasClientComposition) {
3499 ALOGV("hasClientComposition");
3500
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003501 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003502
3503 if (buf == nullptr) {
3504 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3505 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003506 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003507 return false;
3508 }
3509
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003510 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3511 clientCompositionDisplay.clip = displayState.scissor;
3512 const ui::Transform& displayTransform = displayState.transform;
3513 mat4 m;
3514 m[0][0] = displayTransform[0][0];
3515 m[0][1] = displayTransform[0][1];
3516 m[0][3] = displayTransform[0][2];
3517 m[1][0] = displayTransform[1][0];
3518 m[1][1] = displayTransform[1][1];
3519 m[1][3] = displayTransform[1][2];
3520 m[3][0] = displayTransform[2][0];
3521 m[3][1] = displayTransform[2][1];
3522 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003523
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003524 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003525
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003526 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003527 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003528 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003529 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003530 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003531 clientCompositionDisplay.outputDataspace = outputDataspace;
3532 clientCompositionDisplay.maxLuminance =
3533 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003534
Lloyd Pique441d5042018-10-18 16:49:51 -07003535 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003536 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003537 getHwComposer()
3538 .hasDisplayCapability(displayId,
3539 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003540
Peiyong Lind3788632018-09-18 16:01:31 -07003541 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003542 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3543 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003544 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003545 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003546 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003547
Mathias Agopian85d751c2012-08-29 16:59:24 -07003548 /*
3549 * and then, render the layers targeted at the framebuffer
3550 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003551
Dan Stoza9e56aa02015-11-02 13:00:03 -08003552 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003553 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003554 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003555 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003556 const Region viewportRegion(displayState.viewport);
3557 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003558 ALOGV("Layer: %s", layer->getName().string());
3559 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003560 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003561 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003562 case HWC2::Composition::Cursor:
3563 case HWC2::Composition::Device:
3564 case HWC2::Composition::Sideband:
3565 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003566 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003567 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003568 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003569 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003570 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003571 // never clear the very first layer since we're
3572 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003573 renderengine::LayerSettings layerSettings;
3574 Region dummyRegion;
3575 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3576 layerSettings);
3577
3578 if (prepared) {
3579 layerSettings.source.buffer.buffer = nullptr;
3580 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3581 layerSettings.alpha = half(0.0);
3582 layerSettings.disableBlending = true;
3583 clientCompositionLayers.push_back(layerSettings);
3584 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003585 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003586 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003587 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003588 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003589 renderengine::LayerSettings layerSettings;
3590 bool prepared =
3591 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3592 if (prepared) {
3593 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003594 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003595 break;
3596 }
3597 default:
3598 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003599 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003600 } else {
3601 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003602 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003603 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003604 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003605
Alec Mouri820c7402019-01-23 13:02:39 -08003606 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003607 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003608 clientCompositionDisplay.clearRegion = clearRegion;
3609 if (!debugRegion.isEmpty()) {
3610 Region::const_iterator it = debugRegion.begin();
3611 Region::const_iterator end = debugRegion.end();
3612 while (it != end) {
3613 const Rect& rect = *it++;
3614 renderengine::LayerSettings layerSettings;
3615 layerSettings.source.buffer.buffer = nullptr;
3616 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3617 layerSettings.geometry.boundaries = rect.toFloatRect();
3618 layerSettings.alpha = half(1.0);
3619 clientCompositionLayers.push_back(layerSettings);
3620 }
3621 }
3622 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3623 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003624 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003625 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626}
3627
Chia-I Wu28e3a252018-09-07 12:05:02 -07003628void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003629 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003630 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Dan Stoza7d89d062015-04-30 13:29:25 -07003633status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003634 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003635 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003636 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003637 const sp<Layer>& parent,
3638 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003639{
Dan Stoza7d89d062015-04-30 13:29:25 -07003640 // add this layer to the current state list
3641 {
3642 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003643 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003644 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3645 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003646 return NO_MEMORY;
3647 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003648 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003649 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003650 } else if (parent == nullptr) {
3651 lbc->onRemovedFromCurrentState();
3652 } else if (parent->isRemovedFromCurrentState()) {
3653 parent->addChild(lbc);
3654 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003655 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003656 parent->addChild(lbc);
3657 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003658
Yiwei Zhang243b3782018-05-15 17:40:04 -07003659 if (gbc != nullptr) {
3660 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3661 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3662 mMaxGraphicBufferProducerListSize,
3663 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3664 mGraphicBufferProducerList.size(),
3665 mMaxGraphicBufferProducerListSize, mNumLayers);
3666 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003667 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003668 }
3669
Mathias Agopian96f08192010-06-02 23:28:45 -07003670 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003671 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003672
Dan Stoza7d89d062015-04-30 13:29:25 -07003673 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003674}
3675
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003676uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003677 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003678}
3679
Mathias Agopian3f844832013-08-07 21:24:32 -07003680uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003681 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682}
3683
Mathias Agopian3f844832013-08-07 21:24:32 -07003684uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003685 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003686}
3687
3688uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003689 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003690 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003691 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003693 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 }
3695 return old;
3696}
3697
Marissa Wall713b63f2018-10-17 15:42:43 -07003698bool SurfaceFlinger::flushTransactionQueues() {
3699 Mutex::Autolock _l(mStateLock);
3700 auto it = mTransactionQueues.begin();
3701 while (it != mTransactionQueues.end()) {
3702 auto& [applyToken, transactionQueue] = *it;
3703
3704 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003705 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3706 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003707 break;
3708 }
chaviw273171b2018-12-26 11:46:30 -08003709 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003710 transactionQueue.pop();
3711 }
3712
3713 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3714 }
3715 return mTransactionQueues.empty();
3716}
3717
chaviwca27f252018-02-06 16:46:39 -08003718bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3719 for (const ComposerState& state : states) {
3720 // Here we need to check that the interface we're given is indeed
3721 // one of our own. A malicious client could give us a nullptr
3722 // IInterface, or one of its own or even one of our own but a
3723 // different type. All these situations would cause us to crash.
3724 if (state.client == nullptr) {
3725 return true;
3726 }
3727
3728 sp<IBinder> binder = IInterface::asBinder(state.client);
3729 if (binder == nullptr) {
3730 return true;
3731 }
3732
3733 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3734 return true;
3735 }
3736 }
3737 return false;
3738}
3739
Marissa Wall17b4e452018-12-26 16:32:34 -08003740bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3741 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003742 nsecs_t expectedPresentTime;
3743 if (mUseScheduler) {
3744 expectedPresentTime = mScheduler->expectedPresentTime();
3745 } else {
3746 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3747 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003748 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3749 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3750 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3751 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3752 return false;
3753 }
3754
Marissa Wall713b63f2018-10-17 15:42:43 -07003755 for (const ComposerState& state : states) {
3756 const layer_state_t& s = state.state;
3757 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3758 continue;
3759 }
3760 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003761 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003762 }
3763 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003764 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003765}
3766
3767void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3768 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003769 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003770 const InputWindowCommands& inputWindowCommands,
3771 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003772 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003773 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003774
chaviwca27f252018-02-06 16:46:39 -08003775 if (containsAnyInvalidClientState(states)) {
3776 return;
3777 }
3778
Marissa Wall713b63f2018-10-17 15:42:43 -07003779 // If its TransactionQueue already has a pending TransactionState or if it is pending
3780 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003781 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3782 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003783 setTransactionFlags(eTransactionNeeded);
3784 return;
3785 }
3786
chaviw273171b2018-12-26 11:46:30 -08003787 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003788}
3789
3790void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003791 const Vector<DisplayState>& displays, uint32_t flags,
3792 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003793 uint32_t transactionFlags = 0;
3794
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003795 if (flags & eAnimation) {
3796 // For window updates that are part of an animation we must wait for
3797 // previous animation "frames" to be handled.
3798 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003799 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003800 if (CC_UNLIKELY(err != NO_ERROR)) {
3801 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003802 // caller after a few seconds.
3803 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3804 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003805 mAnimTransactionPending = false;
3806 break;
3807 }
3808 }
3809 }
3810
chaviwca27f252018-02-06 16:46:39 -08003811 for (const DisplayState& display : displays) {
3812 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003813 }
3814
Marissa Walle2ffb422018-10-12 11:33:52 -07003815 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003816 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003817 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003818 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003819 // If the state doesn't require a traversal and there are callbacks, send them now
3820 if (!(clientStateFlags & eTraversalNeeded)) {
3821 mTransactionCompletedThread.sendCallbacks();
3822 }
3823 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003824
chaviw273171b2018-12-26 11:46:30 -08003825 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3826
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003827 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3828 // anyway. This can be used as a flush mechanism for previous async transactions.
3829 // Empty animation transaction can be used to simulate back-pressure, so also force a
3830 // transaction for empty animation transactions.
3831 if (transactionFlags == 0 &&
3832 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003833 transactionFlags = eTransactionNeeded;
3834 }
3835
Mathias Agopian386aa982011-11-07 21:58:03 -08003836 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003837 if (mInterceptor->isEnabled()) {
3838 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003839 }
Irvel468051e2016-06-13 16:44:44 -07003840
Mathias Agopian386aa982011-11-07 21:58:03 -08003841 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003842 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3843 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003844 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003845
3846 // if this is a synchronous transaction, wait for it to take effect
3847 // before returning.
3848 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003849 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003850 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003851 if (flags & eAnimation) {
3852 mAnimTransactionPending = true;
3853 }
3854 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003855 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3856 if (CC_UNLIKELY(err != NO_ERROR)) {
3857 // just in case something goes wrong in SF, return to the
3858 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003859 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3860 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003861 break;
3862 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003863 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864 }
3865}
3866
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003867uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3868 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3869 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003870
Mathias Agopiane57f2922012-08-09 16:29:12 -07003871 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003872 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3873
3874 const uint32_t what = s.what;
3875 if (what & DisplayState::eSurfaceChanged) {
3876 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3877 state.surface = s.surface;
3878 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003879 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003880 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003881 if (what & DisplayState::eLayerStackChanged) {
3882 if (state.layerStack != s.layerStack) {
3883 state.layerStack = s.layerStack;
3884 flags |= eDisplayTransactionNeeded;
3885 }
3886 }
3887 if (what & DisplayState::eDisplayProjectionChanged) {
3888 if (state.orientation != s.orientation) {
3889 state.orientation = s.orientation;
3890 flags |= eDisplayTransactionNeeded;
3891 }
3892 if (state.frame != s.frame) {
3893 state.frame = s.frame;
3894 flags |= eDisplayTransactionNeeded;
3895 }
3896 if (state.viewport != s.viewport) {
3897 state.viewport = s.viewport;
3898 flags |= eDisplayTransactionNeeded;
3899 }
3900 }
3901 if (what & DisplayState::eDisplaySizeChanged) {
3902 if (state.width != s.width) {
3903 state.width = s.width;
3904 flags |= eDisplayTransactionNeeded;
3905 }
3906 if (state.height != s.height) {
3907 state.height = s.height;
3908 flags |= eDisplayTransactionNeeded;
3909 }
3910 }
3911
Mathias Agopiane57f2922012-08-09 16:29:12 -07003912 return flags;
3913}
3914
Robert Carrd4ae7f32018-06-07 16:10:57 -07003915bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3916 IPCThreadState* ipc = IPCThreadState::self();
3917 const int pid = ipc->getCallingPid();
3918 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003919 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003920 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003921 return false;
3922 }
3923 return true;
3924}
3925
chaviwca27f252018-02-06 16:46:39 -08003926uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3927 const layer_state_t& s = composerState.state;
3928 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3929
Mathias Agopian13127d82013-03-05 17:47:11 -08003930 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003931 if (layer == nullptr) {
3932 return 0;
3933 }
3934
chaviw8b3871a2017-11-01 17:41:01 -07003935 uint32_t flags = 0;
3936
Garfield Tan8a3083e2018-12-03 13:21:07 -08003937 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003938 bool geometryAppliesWithResize =
3939 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003940
3941 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3942 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003943 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003944 layer->pushPendingState();
3945 }
3946
chaviw8b3871a2017-11-01 17:41:01 -07003947 if (what & layer_state_t::ePositionChanged) {
3948 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3949 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003950 }
chaviw8b3871a2017-11-01 17:41:01 -07003951 }
3952 if (what & layer_state_t::eLayerChanged) {
3953 // NOTE: index needs to be calculated before we update the state
3954 const auto& p = layer->getParent();
3955 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003956 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003957 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003958 mCurrentState.layersSortedByZ.removeAt(idx);
3959 mCurrentState.layersSortedByZ.add(layer);
3960 // we need traversal (state changed)
3961 // AND transaction (list changed)
3962 flags |= eTransactionNeeded|eTraversalNeeded;
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 } else {
3965 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003966 flags |= eTransactionNeeded|eTraversalNeeded;
3967 }
3968 }
chaviw8b3871a2017-11-01 17:41:01 -07003969 }
3970 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003971 // NOTE: index needs to be calculated before we update the state
3972 const auto& p = layer->getParent();
3973 if (p == nullptr) {
3974 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3975 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3976 mCurrentState.layersSortedByZ.removeAt(idx);
3977 mCurrentState.layersSortedByZ.add(layer);
3978 // we need traversal (state changed)
3979 // AND transaction (list changed)
3980 flags |= eTransactionNeeded|eTraversalNeeded;
3981 }
3982 } else {
3983 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3984 flags |= eTransactionNeeded|eTraversalNeeded;
3985 }
chaviw8b3871a2017-11-01 17:41:01 -07003986 }
3987 }
3988 if (what & layer_state_t::eSizeChanged) {
3989 if (layer->setSize(s.w, s.h)) {
3990 flags |= eTraversalNeeded;
3991 }
3992 }
3993 if (what & layer_state_t::eAlphaChanged) {
3994 if (layer->setAlpha(s.alpha))
3995 flags |= eTraversalNeeded;
3996 }
3997 if (what & layer_state_t::eColorChanged) {
3998 if (layer->setColor(s.color))
3999 flags |= eTraversalNeeded;
4000 }
Peiyong Lind3788632018-09-18 16:01:31 -07004001 if (what & layer_state_t::eColorTransformChanged) {
4002 if (layer->setColorTransform(s.colorTransform)) {
4003 flags |= eTraversalNeeded;
4004 }
4005 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004006 if (what & layer_state_t::eBackgroundColorChanged) {
4007 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4008 flags |= eTraversalNeeded;
4009 }
4010 }
chaviw8b3871a2017-11-01 17:41:01 -07004011 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004012 // TODO: b/109894387
4013 //
4014 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4015 // rotation. To see the problem observe that if we have a square parent, and a child
4016 // of the same size, then we rotate the child 45 degrees around it's center, the child
4017 // must now be cropped to a non rectangular 8 sided region.
4018 //
4019 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4020 // private API, and the WindowManager only uses rotation in one case, which is on a top
4021 // level layer in which cropping is not an issue.
4022 //
4023 // However given that abuse of rotation matrices could lead to surfaces extending outside
4024 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4025 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4026 // transformations.
4027 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07004028 flags |= eTraversalNeeded;
4029 }
4030 if (what & layer_state_t::eTransparentRegionChanged) {
4031 if (layer->setTransparentRegionHint(s.transparentRegion))
4032 flags |= eTraversalNeeded;
4033 }
4034 if (what & layer_state_t::eFlagsChanged) {
4035 if (layer->setFlags(s.flags, s.mask))
4036 flags |= eTraversalNeeded;
4037 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004038 if (what & layer_state_t::eCropChanged_legacy) {
4039 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004040 flags |= eTraversalNeeded;
4041 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004042 if (what & layer_state_t::eCornerRadiusChanged) {
4043 if (layer->setCornerRadius(s.cornerRadius))
4044 flags |= eTraversalNeeded;
4045 }
chaviw8b3871a2017-11-01 17:41:01 -07004046 if (what & layer_state_t::eLayerStackChanged) {
4047 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4048 // We only allow setting layer stacks for top level layers,
4049 // everything else inherits layer stack from its parent.
4050 if (layer->hasParent()) {
4051 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4052 layer->getName().string());
4053 } else if (idx < 0) {
4054 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4055 "that also does not appear in the top level layer list. Something"
4056 " has gone wrong.", layer->getName().string());
4057 } else if (layer->setLayerStack(s.layerStack)) {
4058 mCurrentState.layersSortedByZ.removeAt(idx);
4059 mCurrentState.layersSortedByZ.add(layer);
4060 // we need traversal (state changed)
4061 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004062 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004063 }
4064 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004065 if (what & layer_state_t::eDeferTransaction_legacy) {
4066 if (s.barrierHandle_legacy != nullptr) {
4067 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4068 } else if (s.barrierGbp_legacy != nullptr) {
4069 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004070 if (authenticateSurfaceTextureLocked(gbp)) {
4071 const auto& otherLayer =
4072 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004073 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004074 } else {
4075 ALOGE("Attempt to defer transaction to to an"
4076 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004077 }
4078 }
chaviw8b3871a2017-11-01 17:41:01 -07004079 // We don't trigger a traversal here because if no other state is
4080 // changed, we don't want this to cause any more work
4081 }
4082 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004083 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004084 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004085 if (!hadParent) {
4086 mCurrentState.layersSortedByZ.remove(layer);
4087 }
chaviw8b3871a2017-11-01 17:41:01 -07004088 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004089 }
chaviw8b3871a2017-11-01 17:41:01 -07004090 }
4091 if (what & layer_state_t::eReparentChildren) {
4092 if (layer->reparentChildren(s.reparentHandle)) {
4093 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004094 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004095 }
chaviw8b3871a2017-11-01 17:41:01 -07004096 if (what & layer_state_t::eDetachChildren) {
4097 layer->detachChildren();
4098 }
4099 if (what & layer_state_t::eOverrideScalingModeChanged) {
4100 layer->setOverrideScalingMode(s.overrideScalingMode);
4101 // We don't trigger a traversal here because if no other state is
4102 // changed, we don't want this to cause any more work
4103 }
Marissa Wall61c58622018-07-18 10:12:20 -07004104 if (what & layer_state_t::eTransformChanged) {
4105 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4106 }
4107 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4108 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4109 flags |= eTraversalNeeded;
4110 }
4111 if (what & layer_state_t::eCropChanged) {
4112 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4113 }
Marissa Wall861616d2018-10-22 12:52:23 -07004114 if (what & layer_state_t::eFrameChanged) {
4115 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4116 }
Marissa Wall61c58622018-07-18 10:12:20 -07004117 if (what & layer_state_t::eAcquireFenceChanged) {
4118 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4119 }
4120 if (what & layer_state_t::eDataspaceChanged) {
4121 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4122 }
4123 if (what & layer_state_t::eHdrMetadataChanged) {
4124 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4125 }
4126 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4127 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4128 }
4129 if (what & layer_state_t::eApiChanged) {
4130 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4131 }
4132 if (what & layer_state_t::eSidebandStreamChanged) {
4133 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4134 }
Robert Carr720e5062018-07-30 17:45:14 -07004135 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004136 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4137 layer->setInputInfo(s.inputInfo);
4138 flags |= eTraversalNeeded;
4139 } else {
4140 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4141 }
Robert Carr720e5062018-07-30 17:45:14 -07004142 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004143 if (what & layer_state_t::eMetadataChanged) {
4144 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4145 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004146 std::vector<sp<CallbackHandle>> callbackHandles;
4147 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4148 mTransactionCompletedThread.run();
4149 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4150 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4151 }
4152 }
Marissa Wall73411622019-01-25 10:45:41 -08004153
4154 if (what & layer_state_t::eBufferChanged) {
4155 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4156 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4157 s.buffer);
4158 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004159 if (what & layer_state_t::eCachedBufferChanged) {
4160 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004161 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4162 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004163 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4164 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004165 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4166 // Do not put anything that updates layer state or modifies flags after
4167 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004168 return flags;
4169}
4170
chaviw273171b2018-12-26 11:46:30 -08004171uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4172 uint32_t flags = 0;
4173 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4174 flags |= eTraversalNeeded;
4175 }
4176
4177 mInputWindowCommands.merge(inputWindowCommands);
4178 return flags;
4179}
4180
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004181status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4182 uint32_t h, PixelFormat format, uint32_t flags,
4183 LayerMetadata metadata, sp<IBinder>* handle,
4184 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004185 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004186 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004187 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004189 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004190
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004191 status_t result = NO_ERROR;
4192
4193 sp<Layer> layer;
4194
Cody Northropbc755282017-03-31 12:00:08 -06004195 String8 uniqueName = getUniqueLayerName(name);
4196
Mathias Agopian3165cc22012-08-08 19:42:09 -07004197 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004198 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004199 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4200 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004203 case ISurfaceComposerClient::eFXSurfaceBufferState:
4204 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4205 break;
chaviw13fdc492017-06-27 12:40:18 -07004206 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004207 // check if buffer size is set for color layer.
4208 if (w > 0 || h > 0) {
4209 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4210 int(w), int(h));
4211 return BAD_VALUE;
4212 }
4213
chaviw13fdc492017-06-27 12:40:18 -07004214 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004215 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004216 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004217 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004218 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004219 // check if buffer size is set for container layer.
4220 if (w > 0 || h > 0) {
4221 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4222 int(w), int(h));
4223 return BAD_VALUE;
4224 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004225 result = createContainerLayer(client,
4226 uniqueName, w, h, flags,
4227 handle, &layer);
4228 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004229 default:
4230 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004231 break;
4232 }
4233
Dan Stoza7d89d062015-04-30 13:29:25 -07004234 if (result != NO_ERROR) {
4235 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004236 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004237
Chia-I Wuab0c3192017-08-01 11:29:00 -07004238 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4239 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004240 if (metadata.has(METADATA_WINDOW_TYPE)) {
4241 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4242 if (windowType == 441731) {
4243 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4244 layer->setPrimaryDisplayOnly();
4245 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004246 }
4247
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004248 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004249
Robert Carrb89ea9d2018-12-10 13:01:14 -08004250 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4251 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4252 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004253 if (result != NO_ERROR) {
4254 return result;
4255 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004256 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004257
4258 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004259 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260}
4261
Cody Northropbc755282017-03-31 12:00:08 -06004262String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4263{
4264 bool matchFound = true;
4265 uint32_t dupeCounter = 0;
4266
4267 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4268 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4269
Dan Stoza436ccf32018-06-21 12:10:12 -07004270 // Grab the state lock since we're accessing mCurrentState
4271 Mutex::Autolock lock(mStateLock);
4272
Cody Northropbc755282017-03-31 12:00:08 -06004273 // Loop over layers until we're sure there is no matching name
4274 while (matchFound) {
4275 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004276 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004277 if (layer->getName() == uniqueName) {
4278 matchFound = true;
4279 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4280 }
4281 });
4282 }
4283
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004284 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4285 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004286
4287 return uniqueName;
4288}
4289
Marissa Wallfd668622018-05-10 10:21:13 -07004290status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4291 uint32_t w, uint32_t h, uint32_t flags,
4292 PixelFormat& format, sp<IBinder>* handle,
4293 sp<IGraphicBufferProducer>* gbp,
4294 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004295 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004296 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004297 case PIXEL_FORMAT_TRANSPARENT:
4298 case PIXEL_FORMAT_TRANSLUCENT:
4299 format = PIXEL_FORMAT_RGBA_8888;
4300 break;
4301 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004302 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 break;
4304 }
4305
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004306 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004307 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004308 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004309 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004310 *handle = layer->getHandle();
4311 *gbp = layer->getProducer();
4312 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004314
Marissa Wallfd668622018-05-10 10:21:13 -07004315 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004316 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004317}
4318
Marissa Wall61c58622018-07-18 10:12:20 -07004319status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4320 uint32_t w, uint32_t h, uint32_t flags,
4321 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004322 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004323 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004324 *handle = layer->getHandle();
4325 *outLayer = layer;
4326
4327 return NO_ERROR;
4328}
4329
chaviw13fdc492017-06-27 12:40:18 -07004330status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004331 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004332 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004333{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004334 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004335 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004336 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004337}
4338
Robert Carr6b3f6c52018-08-13 13:05:17 -07004339status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4340 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4341 sp<IBinder>* handle, sp<Layer>* outLayer)
4342{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004343 *outLayer =
4344 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004345 *handle = (*outLayer)->getHandle();
4346 return NO_ERROR;
4347}
4348
4349
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004350void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004351 mLayersPendingRemoval.add(layer);
4352 mLayersRemoved = true;
4353 setTransactionFlags(eTransactionNeeded);
4354}
4355
Robert Carr695d5282018-12-18 15:27:58 -08004356void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004357{
Robert Carr2e102c92018-10-23 12:11:15 -07004358 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004359 // If a layer has a parent, we allow it to out-live it's handle
4360 // with the idea that the parent holds a reference and will eventually
4361 // be cleaned up. However no one cleans up the top-level so we do so
4362 // here.
4363 if (layer->getParent() == nullptr) {
4364 mCurrentState.layersSortedByZ.remove(layer);
4365 }
4366 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004367 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004368}
4369
Mathias Agopianb60314a2012-04-10 22:09:54 -07004370// ---------------------------------------------------------------------------
4371
Andy McFadden13a082e2012-08-24 10:16:42 -07004372void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004373 const auto display = getDefaultDisplayDeviceLocked();
4374 if (!display) return;
4375
4376 const sp<IBinder> token = display->getDisplayToken().promote();
4377 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004378
Jesse Hall01e29052013-02-19 16:13:35 -08004379 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004380 Vector<ComposerState> state;
4381 Vector<DisplayState> displays;
4382 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004383 d.what = DisplayState::eDisplayProjectionChanged |
4384 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004385 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004386 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004387 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004388 d.frame.makeInvalid();
4389 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004390 d.width = 0;
4391 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004392 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004393 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004394
Dominik Laskowskie9774092018-12-11 10:04:24 -08004395 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004396
Dominik Laskowski83b88212018-12-11 13:34:06 -08004397 const nsecs_t vsyncPeriod = getVsyncPeriod();
4398 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004399
Brian Andersond0010582017-03-07 13:20:31 -08004400 // Use phase of 0 since phase is not known.
4401 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004402 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004403 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004404}
4405
4406void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004407 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004408 postMessageAsync(
4409 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004410}
4411
Dominik Laskowskie9774092018-12-11 10:04:24 -08004412void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004413 if (display->isVirtual()) {
4414 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004415 return;
4416 }
4417
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 const auto displayId = display->getId();
4419 LOG_ALWAYS_FATAL_IF(!displayId);
4420
Dominik Laskowski34157762018-10-31 13:07:19 -07004421 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004422
4423 int currentMode = display->getPowerMode();
4424 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004425 return;
4426 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004427
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004428 display->setPowerMode(mode);
4429
Lloyd Pique4dccc412018-01-22 17:21:36 -08004430 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004431 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004432 }
4433
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004434 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004435 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004436 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004437 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004438 if (mUseScheduler) {
4439 mScheduler->onScreenAcquired(mAppConnectionHandle);
4440 } else {
4441 mEventThread->onScreenAcquired();
4442 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004443 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004446 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004447 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004448 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004449
4450 struct sched_param param = {0};
4451 param.sched_priority = 1;
4452 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4453 ALOGW("Couldn't set SCHED_FIFO on display on");
4454 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004455 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004456 // Turn off the display
4457 struct sched_param param = {0};
4458 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4459 ALOGW("Couldn't set SCHED_OTHER on display off");
4460 }
4461
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004462 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004463 if (mUseScheduler) {
4464 mScheduler->disableHardwareVsync(true);
4465 } else {
4466 disableHardwareVsync(true); // also cancels any in-progress resync
4467 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004468 if (mUseScheduler) {
4469 mScheduler->onScreenReleased(mAppConnectionHandle);
4470 } else {
4471 mEventThread->onScreenReleased();
4472 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004473 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004474
Dominik Laskowski075d3172018-05-24 15:50:06 -07004475 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004476 mVisibleRegionsDirty = true;
4477 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004478 } else if (mode == HWC_POWER_MODE_DOZE ||
4479 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004480 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004481 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004482 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004483 if (mUseScheduler) {
4484 mScheduler->onScreenAcquired(mAppConnectionHandle);
4485 } else {
4486 mEventThread->onScreenAcquired();
4487 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004488 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004489 }
4490 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4491 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004492 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004493 if (mUseScheduler) {
4494 mScheduler->disableHardwareVsync(true);
4495 } else {
4496 disableHardwareVsync(true); // also cancels any in-progress resync
4497 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004498 if (mUseScheduler) {
4499 mScheduler->onScreenReleased(mAppConnectionHandle);
4500 } else {
4501 mEventThread->onScreenReleased();
4502 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004503 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004504 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004505 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004506 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004507 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004508 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004509
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004510 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004511 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004512 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004513 // Update refresh rate stats.
4514 mRefreshRateStats->setPowerMode(mode);
4515 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004516 }
4517
Dominik Laskowski34157762018-10-31 13:07:19 -07004518 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004519}
4520
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004522 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004523 const auto display = getDisplayDevice(displayToken);
4524 if (!display) {
4525 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4526 displayToken.get());
4527 } else if (display->isVirtual()) {
4528 ALOGW("Attempt to set power mode %d for virtual display", mode);
4529 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004530 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004531 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004532 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004533}
4534
4535// ---------------------------------------------------------------------------
4536
Dominik Laskowskic2867142019-01-21 11:33:38 -08004537status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4538 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004540
Mathias Agopianbd115332013-04-18 16:41:04 -07004541 IPCThreadState* ipc = IPCThreadState::self();
4542 const int pid = ipc->getCallingPid();
4543 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004544
Mathias Agopianbd115332013-04-18 16:41:04 -07004545 if ((uid != AID_SHELL) &&
4546 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4548 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004550 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004551 // (this would indicate SF is stuck, but we want to be able to
4552 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004553 status_t err = mStateLock.timedLock(s2ns(1));
4554 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004555 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result,
4557 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4558 "(no locks held)\n",
4559 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004560 }
4561
Dominik Laskowskic2867142019-01-21 11:33:38 -08004562 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004563
Dominik Laskowskic2867142019-01-21 11:33:38 -08004564 static const std::unordered_map<std::string, Dumper> dumpers = {
4565 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4566 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4567 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004568 {"--dispsync"s, dumper([this](std::string& s) {
4569 if (mUseScheduler) {
4570 mScheduler->dumpPrimaryDispSync(s);
4571 } else {
4572 mPrimaryDispSync->dump(s);
4573 }
4574 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004575 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4576 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4577 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4578 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4579 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4580 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4581 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4582 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4583 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004584 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004585 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4586 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004587
Dominik Laskowskic2867142019-01-21 11:33:38 -08004588 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004589
Dominik Laskowskic2867142019-01-21 11:33:38 -08004590 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4591 (it->second)(args, asProto, result);
4592 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004593 if (asProto) {
4594 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4595 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4596 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004597 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004598 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004599 }
4600
Mathias Agopian9795c422009-08-26 16:36:26 -07004601 if (locked) {
4602 mStateLock.unlock();
4603 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004604 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004605 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 return NO_ERROR;
4607}
4608
Dominik Laskowskic2867142019-01-21 11:33:38 -08004609void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 mCurrentState.traverseInZOrder(
4611 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004612}
4613
Dominik Laskowskic2867142019-01-21 11:33:38 -08004614void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004615 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004616
Dominik Laskowskic2867142019-01-21 11:33:38 -08004617 if (args.size() > 1) {
4618 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004619 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004620 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004621 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004622 }
Robert Carr2047fae2016-11-28 14:09:09 -08004623 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004624 } else {
4625 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 }
4627}
4628
Dominik Laskowskic2867142019-01-21 11:33:38 -08004629void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004630 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004631 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004632 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004633 }
Robert Carr2047fae2016-11-28 14:09:09 -08004634 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004635
Svetoslavd85084b2014-03-20 10:28:31 -07004636 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004637}
4638
Dominik Laskowskic2867142019-01-21 11:33:38 -08004639void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4640 mTimeStats->parseArgs(asProto, args, result);
4641}
4642
Jamie Gennis6547ff42013-07-16 20:12:42 -07004643// This should only be called from the main thread. Otherwise it would need
4644// the lock and should use mCurrentState rather than mDrawingState.
4645void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004646 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004647 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004648 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004649
4650 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4651}
4652
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004654 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004655
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004656 if (isLayerTripleBufferingDisabled())
4657 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4660 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4661 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4662 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4663 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4664 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004665 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004666}
4667
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004668void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004669 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004670 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004671 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004672 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004673
4674 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4675
4676 if (mUseScheduler) {
4677 mScheduler->dump(mAppConnectionHandle, result);
4678 } else {
4679 mEventThread->dump(result);
4680 }
4681}
4682
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4684 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004685 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4686 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004687 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004688 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004690 }
David Sodman4a36e932017-11-07 14:29:47 -08004691 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004692 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004693 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4695 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004696}
4697
Dan Stozae77c7662016-05-13 11:37:28 -07004698void SurfaceFlinger::recordBufferingStats(const char* layerName,
4699 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004700 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4701 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004702 for (const auto& segment : history) {
4703 if (!segment.usedThirdBuffer) {
4704 stats.twoBufferTime += segment.totalTime;
4705 }
4706 if (segment.occupancyAverage < 1.0f) {
4707 stats.doubleBufferedTime += segment.totalTime;
4708 } else if (segment.occupancyAverage < 2.0f) {
4709 stats.tripleBufferedTime += segment.totalTime;
4710 }
4711 ++stats.numSegments;
4712 stats.totalTime += segment.totalTime;
4713 }
4714}
4715
Yiwei Zhang5434a782018-12-05 18:06:32 -08004716void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4717 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004718
4719 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4720 const size_t count = currentLayers.size();
4721 for (size_t i=0 ; i<count ; i++) {
4722 currentLayers[i]->dumpFrameEvents(result);
4723 }
4724}
4725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004727 result.append("Buffering stats:\n");
4728 result.append(" [Layer name] <Active time> <Two buffer> "
4729 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004730 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004731 typedef std::tuple<std::string, float, float, float> BufferTuple;
4732 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004733 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004734 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004735 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004736 if (stats.numSegments == 0) {
4737 continue;
4738 }
4739 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4740 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4741 stats.totalTime;
4742 float doubleBufferRatio = static_cast<float>(
4743 stats.doubleBufferedTime) / stats.totalTime;
4744 float tripleBufferRatio = static_cast<float>(
4745 stats.tripleBufferedTime) / stats.totalTime;
4746 sorted.insert({activeTime, {name, twoBufferRatio,
4747 doubleBufferRatio, tripleBufferRatio}});
4748 }
4749 for (const auto& sortedPair : sorted) {
4750 float activeTime = sortedPair.first;
4751 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004752 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4753 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004754 }
4755 result.append("\n");
4756}
4757
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004759 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 const auto displayId = display->getId();
4761 if (!displayId) {
4762 continue;
4763 }
4764 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004765 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004766 continue;
4767 }
4768
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 StringAppendF(&result,
4770 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4771 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004772 uint8_t port;
4773 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004774 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004775 result.append("no identification data\n");
4776 continue;
4777 }
4778
4779 if (!isEdid(data)) {
4780 result.append("unknown identification data: ");
4781 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004783 }
4784 result.append("\n");
4785 continue;
4786 }
4787
4788 const auto edid = parseEdid(data);
4789 if (!edid) {
4790 result.append("invalid EDID: ");
4791 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004793 }
4794 result.append("\n");
4795 continue;
4796 }
4797
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004799 result.append(edid->displayName.data(), edid->displayName.length());
4800 result.append("\"\n");
4801 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004802}
4803
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4805 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4806 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4807 StringAppendF(&result, "DisplayColorSetting: %s\n",
4808 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004809
4810 // TODO: print out if wide-color mode is active or not
4811
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004812 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004813 const auto displayId = display->getId();
4814 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004815 continue;
4816 }
4817
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004819 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004820 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004821 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004822 }
4823
Lloyd Pique32cbe282018-10-19 13:09:22 -07004824 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, " Current color mode: %s (%d)\n",
4826 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004827 }
4828 result.append("\n");
4829}
4830
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004832 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004833 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4834 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004835 continue;
4836 }
4837
Dominik Laskowski05275f12018-11-01 15:03:24 -07004838 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004839 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4840 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004841 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 compositionInfo.dump(result, nullptr);
4843 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004844 }
4845 }
David Sodman7e4ae112018-02-09 15:02:28 -08004846}
4847
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004848LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004849 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004850 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4851 const State& state = useDrawing ? mDrawingState : mCurrentState;
4852 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004853 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004854 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004855 });
4856
4857 return layersProto;
4858}
4859
Lloyd Pique32cbe282018-10-19 13:09:22 -07004860LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004861 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004862
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004863 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004864 resolution->set_w(displayDevice.getWidth());
4865 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004866
Lloyd Pique32cbe282018-10-19 13:09:22 -07004867 auto display = displayDevice.getCompositionDisplay();
4868 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004869
Lloyd Pique32cbe282018-10-19 13:09:22 -07004870 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4871 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4872 layersProto.set_global_transform(displayState.orientation);
4873
4874 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004875 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004876 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004877 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004878 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004879 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004880 }
4881 });
4882
4883 return layersProto;
4884}
4885
Dominik Laskowskic2867142019-01-21 11:33:38 -08004886void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4887 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004888 Colorizer colorizer(colorize);
4889
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004890 // figure out if we're stuck somewhere
4891 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004893 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4894
4895 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004896 * Dump library configuration.
4897 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004898
4899 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004900 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004901 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004902 appendSfConfigString(result);
4903 appendUiConfigString(result);
4904 appendGuiConfigString(result);
4905 result.append("\n");
4906
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004907 result.append("\nDisplay identification data:\n");
4908 dumpDisplayIdentificationData(result);
4909
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004910 result.append("\nWide-Color information:\n");
4911 dumpWideColorInfo(result);
4912
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004913 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004914 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004915 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004916 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004917 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004918
Andy McFadden41d67d72014-04-25 16:58:34 -07004919 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004920 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004921 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004922 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004923 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004924
Dan Stozab90cf072015-03-05 11:05:59 -08004925 dumpStaticScreenStats(result);
4926 result.append("\n");
4927
Yiwei Zhang5434a782018-12-05 18:06:32 -08004928 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004929
Dan Stozae77c7662016-05-13 11:37:28 -07004930 dumpBufferingStats(result);
4931
Andy McFadden4803b742012-09-24 19:07:20 -07004932 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933 * Dump the visible layer list
4934 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004935 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004936 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4937 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4938 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004939 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004940
Chia-I Wu2f884132018-09-13 15:17:58 -07004941 {
4942 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4943 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004944 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004945 result.append("\n");
4946 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004947
David Sodman7e4ae112018-02-09 15:02:28 -08004948 result.append("\nFrame-Composition information:\n");
4949 dumpFrameCompositionInfo(result);
4950 result.append("\n");
4951
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004952 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004953 * Dump Display state
4954 */
4955
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004956 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004957 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004958 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004959 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004960 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004961 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004962 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004963
4964 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004965 * Dump SurfaceFlinger global state
4966 */
4967
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004968 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004969 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004970 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004971
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004972 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004973
Dominik Laskowski075d3172018-05-24 15:50:06 -07004974 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004975 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4976 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004977 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4978 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004979 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004980 StringAppendF(&result,
4981 " transaction-flags : %08x\n"
4982 " gpu_to_cpu_unsupported : %d\n",
4983 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004984
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004985 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004986 displayId && getHwComposer().isConnected(*displayId)) {
4987 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004988 StringAppendF(&result,
4989 " refresh-rate : %f fps\n"
4990 " x-dpi : %f\n"
4991 " y-dpi : %f\n",
4992 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4993 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004994 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004995
Yiwei Zhang5434a782018-12-05 18:06:32 -08004996 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004997
Dan Stozae22aec72016-08-01 13:20:59 -07004998 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004999 * Tracing state
5000 */
5001 mTracing.dump(result);
5002 result.append("\n");
5003
5004 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005005 * HWC layer minidump
5006 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005007 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005008 const auto displayId = display->getId();
5009 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005010 continue;
5011 }
5012
Yiwei Zhang5434a782018-12-05 18:06:32 -08005013 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005014 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07005015 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07005016 result.append("\n");
5017 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005018
5019 /*
5020 * Dump HWComposer state
5021 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005022 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005023 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005024 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005025 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005026 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005027 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005028
5029 /*
5030 * Dump gralloc state
5031 */
5032 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5033 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005034
5035 /*
5036 * Dump VrFlinger state if in use.
5037 */
5038 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5039 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005040 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005041 result.append("\n");
5042 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005043
5044 /**
5045 * Scheduler dump state.
5046 */
5047 if (mUseScheduler) {
5048 result.append("\nScheduler state:\n");
5049 result.append(mScheduler->doDump() + "\n");
5050 result.append(mRefreshRateStats->doDump() + "\n");
5051 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005052}
5053
Dominik Laskowski075d3172018-05-24 15:50:06 -07005054const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005055 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005056 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005057 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005058 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005059 }
5060 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005061
Dominik Laskowski34157762018-10-31 13:07:19 -07005062 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005063 static const Vector<sp<Layer>> empty;
5064 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005065}
5066
Chia-I Wu28f320b2018-05-03 11:02:56 -07005067void SurfaceFlinger::updateColorMatrixLocked() {
5068 mat4 colorMatrix;
5069 if (mGlobalSaturationFactor != 1.0f) {
5070 // Rec.709 luma coefficients
5071 float3 luminance{0.213f, 0.715f, 0.072f};
5072 luminance *= 1.0f - mGlobalSaturationFactor;
5073 mat4 saturationMatrix = mat4(
5074 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5075 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5076 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5077 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5078 );
5079 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5080 } else {
5081 colorMatrix = mClientColorMatrix * mDaltonizer();
5082 }
5083
5084 if (mCurrentState.colorMatrix != colorMatrix) {
5085 mCurrentState.colorMatrix = colorMatrix;
5086 mCurrentState.colorMatrixChanged = true;
5087 setTransactionFlags(eTransactionNeeded);
5088 }
5089}
5090
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005091status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005092#pragma clang diagnostic push
5093#pragma clang diagnostic error "-Wswitch-enum"
5094 switch (static_cast<ISurfaceComposerTag>(code)) {
5095 // These methods should at minimum make sure that the client requested
5096 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005097 case BOOT_FINISHED:
5098 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005099 case CREATE_DISPLAY:
5100 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005101 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005102 case GET_ACTIVE_COLOR_MODE:
5103 case GET_ANIMATION_FRAME_STATS:
5104 case GET_HDR_CAPABILITIES:
5105 case SET_ACTIVE_CONFIG:
5106 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005107 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005108 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005109 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005110 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5111 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005112 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5113 IPCThreadState* ipc = IPCThreadState::self();
5114 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5115 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005116 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 }
Robert Carr1db73f62016-12-21 12:58:51 -08005118 return OK;
5119 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005120 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005121 IPCThreadState* ipc = IPCThreadState::self();
5122 const int pid = ipc->getCallingPid();
5123 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005124 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5125 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005126 return PERMISSION_DENIED;
5127 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005128 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005129 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005130 // Used by apps to hook Choreographer to SurfaceFlinger.
5131 case CREATE_DISPLAY_EVENT_CONNECTION:
5132 // The following calls are currently used by clients that do not
5133 // request necessary permissions. However, they do not expose any secret
5134 // information, so it is OK to pass them.
5135 case AUTHENTICATE_SURFACE:
5136 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005137 case GET_PHYSICAL_DISPLAY_IDS:
5138 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005139 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005140 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005141 case GET_DISPLAY_CONFIGS:
5142 case GET_DISPLAY_STATS:
5143 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5144 // Calling setTransactionState is safe, because you need to have been
5145 // granted a reference to Client* and Handle* to do anything with it.
5146 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005147 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005148 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005149 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005150 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005151 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005152 return OK;
5153 }
5154 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005155 case CAPTURE_SCREEN:
5156 case ADD_REGION_SAMPLING_LISTENER:
5157 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005158 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005159 IPCThreadState* ipc = IPCThreadState::self();
5160 const int pid = ipc->getCallingPid();
5161 const int uid = ipc->getCallingUid();
5162 if ((uid != AID_GRAPHICS) &&
5163 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5164 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5165 return PERMISSION_DENIED;
5166 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005167 return OK;
5168 }
5169 // The following codes are deprecated and should never be allowed to access SF.
5170 case CONNECT_DISPLAY_UNUSED:
5171 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5172 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5173 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005175 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005176
5177 // These codes are used for the IBinder protocol to either interrogate the recipient
5178 // side of the transaction for its canonical interface descriptor or to dump its state.
5179 // We let them pass by default.
5180 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5181 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5182 code == IBinder::SYSPROPS_TRANSACTION) {
5183 return OK;
5184 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005185 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005186 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005187 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005188 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5189 return OK;
5190 }
5191 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5192 return PERMISSION_DENIED;
5193#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005194}
5195
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5197 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005198 status_t credentialCheck = CheckTransactCodeCredentials(code);
5199 if (credentialCheck != OK) {
5200 return credentialCheck;
5201 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005203 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5204 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005205 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005206 IPCThreadState* ipc = IPCThreadState::self();
5207 const int uid = ipc->getCallingUid();
5208 if (CC_UNLIKELY(uid != AID_SYSTEM
5209 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005210 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005211 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005212 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005213 return PERMISSION_DENIED;
5214 }
5215 int n;
5216 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005217 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005218 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005219 return NO_ERROR;
5220 case 1002: // SHOW_UPDATES
5221 n = data.readInt32();
5222 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005223 invalidateHwcGeometry();
5224 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005225 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005226 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005227 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005228 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005230 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005231 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005232 setTransactionFlags(
5233 eTransactionNeeded|
5234 eDisplayTransactionNeeded|
5235 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005236 return NO_ERROR;
5237 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005238 case 1006:{ // send empty update
5239 signalRefresh();
5240 return NO_ERROR;
5241 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005242 case 1008: // toggle use of hw composer
5243 n = data.readInt32();
5244 mDebugDisableHWC = n ? 1 : 0;
5245 invalidateHwcGeometry();
5246 repaintEverything();
5247 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005248 case 1009: // toggle use of transform hint
5249 n = data.readInt32();
5250 mDebugDisableTransformHint = n ? 1 : 0;
5251 invalidateHwcGeometry();
5252 repaintEverything();
5253 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005254 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005255 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005256 reply->writeInt32(0);
5257 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005258 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005259 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005260 return NO_ERROR;
5261 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005262 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005263 if (!display) {
5264 return NAME_NOT_FOUND;
5265 }
5266
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005267 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005268 return NO_ERROR;
5269 }
5270 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005271 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005272 // daltonize
5273 n = data.readInt32();
5274 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005275 case 1:
5276 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5277 break;
5278 case 2:
5279 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5280 break;
5281 case 3:
5282 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5283 break;
5284 default:
5285 mDaltonizer.setType(ColorBlindnessType::None);
5286 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005287 }
5288 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005289 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005290 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005291 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005292 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005293
5294 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005295 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005296 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005297 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005298 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005299 // apply a color matrix
5300 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005301 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005302 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005303 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005304 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005305 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005306 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005307 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005308 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005309 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005310 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005311
5312 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5313 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005314 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005315 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5316 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5317 }
5318
Chia-I Wu28f320b2018-05-03 11:02:56 -07005319 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005320 return NO_ERROR;
5321 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005322 // This is an experimental interface
5323 // Needs to be shifted to proper binder interface when we productize
5324 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005325 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005326 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005327 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005328 return NO_ERROR;
5329 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005330 case 1017: {
5331 n = data.readInt32();
5332 mForceFullDamage = static_cast<bool>(n);
5333 return NO_ERROR;
5334 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005335 case 1018: { // Modify Choreographer's phase offset
5336 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005337 if (mUseScheduler) {
5338 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5339 } else {
5340 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5341 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005342 return NO_ERROR;
5343 }
5344 case 1019: { // Modify SurfaceFlinger's phase offset
5345 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005346 if (mUseScheduler) {
5347 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5348 } else {
5349 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5350 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005351 return NO_ERROR;
5352 }
Irvel468051e2016-06-13 16:44:44 -07005353 case 1020: { // Layer updates interceptor
5354 n = data.readInt32();
5355 if (n) {
5356 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005357 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005358 }
5359 else{
5360 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005361 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005362 }
5363 return NO_ERROR;
5364 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005365 case 1021: { // Disable HWC virtual displays
5366 n = data.readInt32();
5367 mUseHwcVirtualDisplays = !n;
5368 return NO_ERROR;
5369 }
Romain Guy0147a172017-06-01 13:53:56 -07005370 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005371 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005372 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005373
Chia-I Wu28f320b2018-05-03 11:02:56 -07005374 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005375 return NO_ERROR;
5376 }
Romain Guy54f154a2017-10-24 21:40:32 +01005377 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005378 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005379 invalidateHwcGeometry();
5380 repaintEverything();
5381 return NO_ERROR;
5382 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005383 // Deprecate, use 1030 to check whether the device is color managed.
5384 case 1024: {
5385 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005386 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005387 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005388 n = data.readInt32();
5389 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005390 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005391 mTracing.enable();
5392 doTracing("tracing.enable");
5393 reply->writeInt32(NO_ERROR);
5394 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005395 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005396 status_t err = mTracing.disable();
5397 reply->writeInt32(err);
5398 }
5399 return NO_ERROR;
5400 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005401 case 1026: { // Get layer tracing status
5402 reply->writeBool(mTracing.isEnabled());
5403 return NO_ERROR;
5404 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005405 // Is a DisplayColorSetting supported?
5406 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005407 const auto display = getDefaultDisplayDevice();
5408 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005409 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005410 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005411
5412 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5413 switch (setting) {
5414 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005415 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005416 break;
5417 case DisplayColorSetting::UNMANAGED:
5418 reply->writeBool(true);
5419 break;
5420 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005421 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005422 break;
5423 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005424 reply->writeBool(
5425 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005426 break;
5427 }
5428 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005429 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005430 // Is VrFlinger active?
5431 case 1028: {
5432 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005433 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005434 return NO_ERROR;
5435 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005436 // Is device color managed?
5437 case 1030: {
5438 reply->writeBool(useColorManagement);
5439 return NO_ERROR;
5440 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005441 // Override default composition data space
5442 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5443 // && adb shell stop zygote && adb shell start zygote
5444 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5445 // adb shell stop zygote && adb shell start zygote
5446 case 1031: {
5447 Mutex::Autolock _l(mStateLock);
5448 n = data.readInt32();
5449 if (n) {
5450 n = data.readInt32();
5451 if (n) {
5452 Dataspace dataspace = static_cast<Dataspace>(n);
5453 if (!validateCompositionDataspace(dataspace)) {
5454 return BAD_VALUE;
5455 }
5456 mDefaultCompositionDataspace = dataspace;
5457 }
5458 n = data.readInt32();
5459 if (n) {
5460 Dataspace dataspace = static_cast<Dataspace>(n);
5461 if (!validateCompositionDataspace(dataspace)) {
5462 return BAD_VALUE;
5463 }
5464 mWideColorGamutCompositionDataspace = dataspace;
5465 }
5466 } else {
5467 // restore composition data space.
5468 mDefaultCompositionDataspace = defaultCompositionDataspace;
5469 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5470 }
5471 return NO_ERROR;
5472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005473 }
5474 }
5475 return err;
5476}
5477
Steven Thomas6d8110b2017-08-31 18:24:21 -07005478void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005479 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005480 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005481}
5482
Ana Krulec7d1d6832018-12-27 11:10:09 -08005483void SurfaceFlinger::repaintEverythingForHWC() {
5484 mRepaintEverything = true;
5485 mEventQueue->invalidateForHWC();
5486}
5487
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5489class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005490public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005491 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5492 ~WindowDisconnector() {
5493 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005494 }
5495
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496private:
5497 ANativeWindow* mWindow;
5498 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005499};
5500
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005501status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005502 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5503 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005504 uint32_t reqWidth, uint32_t reqHeight,
5505 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005506 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005509 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005510
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005511 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5512
Chia-I Wu20261cb2018-08-23 12:55:44 -07005513 sp<DisplayDevice> display;
5514 {
5515 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005516
Chia-I Wu20261cb2018-08-23 12:55:44 -07005517 display = getDisplayDeviceLocked(displayToken);
5518 if (!display) return BAD_VALUE;
5519
Chia-I Wucb023152018-08-28 12:57:23 -07005520 // set the requested width/height to the logical display viewport size
5521 // by default
5522 if (reqWidth == 0 || reqHeight == 0) {
5523 reqWidth = uint32_t(display->getViewport().width());
5524 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005525 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005526 }
5527
Peiyong Lin0e003c92018-09-17 11:09:51 -07005528 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5529 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005530
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005531 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5532 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005533 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5534 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005535}
5536
5537status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005538 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5539 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005540 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005541 ATRACE_CALL();
5542
5543 class LayerRenderArea : public RenderArea {
5544 public:
Robert Carr578038f2018-03-09 12:25:24 -08005545 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005546 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5547 bool childrenOnly)
5548 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005549 mLayer(layer),
5550 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005551 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005552 mFlinger(flinger),
5553 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005554 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005555 Rect getBounds() const override {
5556 const Layer::State& layerState(mLayer->getDrawingState());
5557 return mLayer->getBufferSize(layerState);
5558 }
Marissa Wall61c58622018-07-18 10:12:20 -07005559 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005560 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005561 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005562 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005563 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005564 }
chaviwa76b2712017-09-20 12:02:26 -07005565 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005566 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005567 Rect getSourceCrop() const override {
5568 if (mCrop.isEmpty()) {
5569 return getBounds();
5570 } else {
5571 return mCrop;
5572 }
5573 }
Robert Carr578038f2018-03-09 12:25:24 -08005574 class ReparentForDrawing {
5575 public:
5576 const sp<Layer>& oldParent;
5577 const sp<Layer>& newParent;
5578
Vishnu Nair4351ad52019-02-11 14:13:02 -08005579 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5580 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005581 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005582 // Compute and cache the bounds for the new parent layer.
5583 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005584 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005585 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005586 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005587 };
5588
5589 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005590 const Rect sourceCrop = getSourceCrop();
5591 // no need to check rotation because there is none
5592 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5593 sourceCrop.height() != getReqHeight();
5594
Robert Carr578038f2018-03-09 12:25:24 -08005595 if (!mChildrenOnly) {
5596 mTransform = mLayer->getTransform().inverse();
5597 drawLayers();
5598 } else {
5599 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005600 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005601 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5602 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005603
Vishnu Nair4351ad52019-02-11 14:13:02 -08005604 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005605 drawLayers();
5606 }
5607 }
chaviwa76b2712017-09-20 12:02:26 -07005608
chaviwa76b2712017-09-20 12:02:26 -07005609 private:
chaviw7206d492017-11-10 16:16:12 -08005610 const sp<Layer> mLayer;
5611 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005612
5613 // In the "childrenOnly" case we reparent the children to a screenshot
5614 // layer which has no properties set and which does not draw.
5615 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005616 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005617 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005618
5619 SurfaceFlinger* mFlinger;
5620 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005621 };
5622
5623 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5624 auto parent = layerHandle->owner.promote();
5625
Robert Carr2e102c92018-10-23 12:11:15 -07005626 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005627 ALOGE("captureLayers called with a removed parent");
5628 return NAME_NOT_FOUND;
5629 }
5630
Robert Carr578038f2018-03-09 12:25:24 -08005631 const int uid = IPCThreadState::self()->getCallingUid();
5632 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005633 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005634 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5635 return PERMISSION_DENIED;
5636 }
5637
chaviw7206d492017-11-10 16:16:12 -08005638 Rect crop(sourceCrop);
5639 if (sourceCrop.width() <= 0) {
5640 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005641 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005642 }
5643
5644 if (sourceCrop.height() <= 0) {
5645 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005646 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005647 }
5648
5649 int32_t reqWidth = crop.width() * frameScale;
5650 int32_t reqHeight = crop.height() * frameScale;
5651
Chia-I Wu20261cb2018-08-23 12:55:44 -07005652 // really small crop or frameScale
5653 if (reqWidth <= 0) {
5654 reqWidth = 1;
5655 }
5656 if (reqHeight <= 0) {
5657 reqHeight = 1;
5658 }
5659
Peiyong Lin0e003c92018-09-17 11:09:51 -07005660 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005661
Robert Carr578038f2018-03-09 12:25:24 -08005662 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005663 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5664 if (!layer->isVisible()) {
5665 return;
Robert Carr578038f2018-03-09 12:25:24 -08005666 } else if (childrenOnly && layer == parent.get()) {
5667 return;
chaviwa76b2712017-09-20 12:02:26 -07005668 }
5669 visitor(layer);
5670 });
5671 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005672 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005673}
5674
5675status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5676 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005677 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005678 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005679 bool useIdentityTransform) {
5680 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005681
Peiyong Lin0e003c92018-09-17 11:09:51 -07005682 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005683 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5684 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005685 *outBuffer =
5686 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5687 static_cast<android_pixel_format>(reqPixelFormat), 1,
5688 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005689
5690 // This mutex protects syncFd and captureResult for communication of the return values from the
5691 // main thread back to this Binder thread
5692 std::mutex captureMutex;
5693 std::condition_variable captureCondition;
5694 std::unique_lock<std::mutex> captureLock(captureMutex);
5695 int syncFd = -1;
5696 std::optional<status_t> captureResult;
5697
Robert Carr03480e22018-01-04 16:02:06 -08005698 const int uid = IPCThreadState::self()->getCallingUid();
5699 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5700
Dominik Laskowski8c001672018-05-30 16:52:06 -07005701 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005702 // If there is a refresh pending, bug out early and tell the binder thread to try again
5703 // after the refresh.
5704 if (mRefreshPending) {
5705 ATRACE_NAME("Skipping screenshot for now");
5706 std::unique_lock<std::mutex> captureLock(captureMutex);
5707 captureResult = std::make_optional<status_t>(EAGAIN);
5708 captureCondition.notify_one();
5709 return;
5710 }
5711
5712 status_t result = NO_ERROR;
5713 int fd = -1;
5714 {
5715 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005716 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005717 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5718 useIdentityTransform, forSystem, &fd);
5719 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005720 }
5721
5722 {
5723 std::unique_lock<std::mutex> captureLock(captureMutex);
5724 syncFd = fd;
5725 captureResult = std::make_optional<status_t>(result);
5726 captureCondition.notify_one();
5727 }
5728 });
5729
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005730 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005732 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 while (*captureResult == EAGAIN) {
5734 captureResult.reset();
5735 result = postMessageAsync(message);
5736 if (result != NO_ERROR) {
5737 return result;
5738 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005739 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005740 }
5741 result = *captureResult;
5742 }
5743
5744 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005745 sync_wait(syncFd, -1);
5746 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005747 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005748
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005749 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005750}
5751
chaviwa76b2712017-09-20 12:02:26 -07005752void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005753 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005754 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5755 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005756 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005757
chaviwa76b2712017-09-20 12:02:26 -07005758 const auto reqWidth = renderArea.getReqWidth();
5759 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005760 const auto sourceCrop = renderArea.getSourceCrop();
5761 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005762
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005763 renderengine::DisplaySettings clientCompositionDisplay;
5764 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005765
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005766 // assume that bounds are never offset, and that they are the same as the
5767 // buffer bounds.
5768 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5769 ui::Transform transform = renderArea.getTransform();
5770 mat4 m;
5771 m[0][0] = transform[0][0];
5772 m[0][1] = transform[0][1];
5773 m[0][3] = transform[0][2];
5774 m[1][0] = transform[1][0];
5775 m[1][1] = transform[1][1];
5776 m[1][3] = transform[1][2];
5777 m[3][0] = transform[2][0];
5778 m[3][1] = transform[2][1];
5779 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005780
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005781 clientCompositionDisplay.globalTransform = m;
5782 mat4 rotMatrix;
5783 // Displacement for repositioning the clipping rectangle after rotating it
5784 // with the rotation hint.
5785 int displacementX = 0;
5786 int displacementY = 0;
5787 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5788 switch (rotation) {
5789 case ui::Transform::ROT_90:
5790 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5791 displacementX = reqWidth;
5792 break;
5793 case ui::Transform::ROT_180:
5794 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5795 displacementX = reqWidth;
5796 displacementY = reqHeight;
5797 break;
5798 case ui::Transform::ROT_270:
5799 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5800 displacementY = reqHeight;
5801 break;
5802 default:
5803 break;
5804 }
5805 // We need to transform the clipping window into the right spot.
5806 // First, rotate the clipping rectangle by the rotation hint to get the
5807 // right orientation
5808 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5809 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5810 const vec4 rotClipTL = rotMatrix * clipTL;
5811 const vec4 rotClipBR = rotMatrix * clipBR;
5812 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5813 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5814 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5815 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5816
5817 // Now reposition the clipping rectangle with the displacement vector
5818 // computed above.
5819 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5820
5821 clientCompositionDisplay.clip =
5822 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5823 newClipRight + displacementX, newClipBottom + displacementY);
5824
5825 // We need to perform the same transformation in layer space, so propagate
5826 // it to the global transform.
5827 mat4 clipTransform = displacementMat * rotMatrix;
5828 clientCompositionDisplay.globalTransform *= clipTransform;
5829 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5830 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005831
chaviw50da5042018-04-09 13:49:37 -07005832 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005833
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834 renderengine::LayerSettings fillLayer;
5835 fillLayer.source.buffer.buffer = nullptr;
5836 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5837 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5838 fillLayer.alpha = half(alpha);
5839 clientCompositionLayers.push_back(fillLayer);
5840
5841 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005842 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005843 renderengine::LayerSettings layerSettings;
5844 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5845 layerSettings);
5846 if (prepared) {
5847 clientCompositionLayers.push_back(layerSettings);
5848 }
chaviwa76b2712017-09-20 12:02:26 -07005849 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005850
5851 clientCompositionDisplay.clearRegion = clearRegion;
5852 base::unique_fd drawFence;
5853 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5854 &drawFence);
5855
5856 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005857}
5858
chaviwa76b2712017-09-20 12:02:26 -07005859status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5860 TraverseLayersFunction traverseLayers,
5861 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005862 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005863 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005864 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005865 ATRACE_CALL();
5866
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005867 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005868
5869 traverseLayers([&](Layer* layer) {
5870 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5871 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005872
Robert Carr03480e22018-01-04 16:02:06 -08005873 // We allow the system server to take screenshots of secure layers for
5874 // use in situations like the Screen-rotation animation and place
5875 // the impetus on WindowManager to not persist them.
5876 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005877 ALOGW("FB is protected: PERMISSION_DENIED");
5878 return PERMISSION_DENIED;
5879 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005880 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005881 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005882}
5883
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005884// ---------------------------------------------------------------------------
5885
Dan Stoza412903f2017-04-27 13:42:17 -07005886void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5887 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005888}
5889
Dan Stoza412903f2017-04-27 13:42:17 -07005890void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5891 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005892}
5893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005894void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005895 const LayerVector::Visitor& visitor) {
5896 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005897 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005898 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005899 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005900 continue;
5901 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005902 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005903 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005904 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005905 return;
5906 }
chaviwa76b2712017-09-20 12:02:26 -07005907 if (!layer->isVisible()) {
5908 return;
5909 }
5910 visitor(layer);
5911 });
5912 }
5913}
5914
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005915}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005916
Lloyd Pique074e8122018-07-26 12:57:23 -07005917
Mathias Agopian3f844832013-08-07 21:24:32 -07005918#if defined(__gl_h_)
5919#error "don't include gl/gl.h in this file"
5920#endif
5921
5922#if defined(__gl2_h_)
5923#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005924#endif