blob: 547f30f21098aa44ade4fd10e4eba8c7481d88c4 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
112#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
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700160bool isHdrColorMode(const ColorMode colorMode) {
161 switch (colorMode) {
162 case ColorMode::BT2100_PQ:
163 case ColorMode::BT2100_HLG:
164 return true;
165 case ColorMode::DISPLAY_P3:
166 case ColorMode::ADOBE_RGB:
167 case ColorMode::DCI_P3:
168 case ColorMode::BT2020:
169 case ColorMode::DISPLAY_BT2020:
170 case ColorMode::NATIVE:
171 case ColorMode::STANDARD_BT601_625:
172 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
173 case ColorMode::STANDARD_BT601_525:
174 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
175 case ColorMode::STANDARD_BT709:
176 case ColorMode::SRGB:
177 return false;
178 }
179 return false;
180}
181
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700182ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
183 switch (rotation) {
184 case ISurfaceComposer::eRotateNone:
185 return ui::Transform::ROT_0;
186 case ISurfaceComposer::eRotate90:
187 return ui::Transform::ROT_90;
188 case ISurfaceComposer::eRotate180:
189 return ui::Transform::ROT_180;
190 case ISurfaceComposer::eRotate270:
191 return ui::Transform::ROT_270;
192 }
193 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
194 return ui::Transform::ROT_0;
195}
196
Peiyong Linfca547f2018-07-09 13:03:33 -0700197#pragma clang diagnostic pop
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199class ConditionalLock {
200public:
201 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
202 if (lock) {
203 mMutex.lock();
204 }
205 }
206 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
207private:
208 Mutex& mMutex;
209 bool mLocked;
210};
Peiyong Linfca547f2018-07-09 13:03:33 -0700211
Peiyong Lin9d846a52018-11-05 13:18:20 -0800212// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
213bool validateCompositionDataspace(Dataspace dataspace) {
214 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
215}
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
225
226// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700227int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700228bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800229uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800230bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800231bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800232int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600233bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700234int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700235bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700236bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700237Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
238ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
239Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
240ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700241
Kalle Raitaa099a242017-01-11 11:17:29 -0800242std::string getHwcServiceName() {
243 char value[PROPERTY_VALUE_MAX] = {};
244 property_get("debug.sf.hwc_service_name", value, "default");
245 ALOGI("Using HWComposer service: '%s'", value);
246 return std::string(value);
247}
248
249bool useTrebleTestingOverride() {
250 char value[PROPERTY_VALUE_MAX] = {};
251 property_get("debug.sf.treble_testing_override", value, "false");
252 ALOGI("Treble testing override: '%s'", value);
253 return std::string(value) == "true";
254}
255
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
257 switch(displayColorSetting) {
258 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700261 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Enhanced");
264 default:
265 return std::string("Unknown ") +
266 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268}
269
David Sodmanbc815282017-11-05 18:57:52 -0800270SurfaceFlingerBE::SurfaceFlingerBE()
271 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800272 mFrameBuckets(),
273 mTotalTime(0),
274 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800275 mComposerSequenceId(0) {
276}
277
Lloyd Pique90c115d2018-09-18 21:39:42 -0700278SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
279 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800280 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700281 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700282 mTransactionPending(false),
283 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700284 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700285 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800287 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800289 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800290 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800291 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700293 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700294 mDebugDisableTransformHint(0),
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800295 mDebugEnableProtectedContent(false),
Mathias Agopian9795c422009-08-26 16:36:26 -0700296 mDebugInTransaction(0),
297 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700298 mForceFullDamage(false),
Nataniel Borges2b796da2019-02-15 13:32:18 -0800299 mTracing(*this),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800300 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800301 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800302 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800303 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700304 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700305 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800306 mCompositionEngine{getFactory().createCompositionEngine()} {
307 mSetInputWindowsListener = new SetInputWindowsListener(this);
308}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800309
Lloyd Pique90c115d2018-09-18 21:39:42 -0700310SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
311 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800312 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800321
Steven Thomas050b2c82017-03-06 11:45:16 -0800322 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 mDefaultCompositionDataspace =
332 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
333 mWideColorGamutCompositionDataspace =
334 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
335 defaultCompositionDataspace = mDefaultCompositionDataspace;
336 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
337 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
338 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
339 wideColorGamutCompositionPixelFormat =
340 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800343
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
345 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
346 switch (tmpPrimaryDisplayOrientation) {
347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800355 break;
356 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700357 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800358 break;
359 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700360 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800361
Sundong Ahn85131bd2019-02-18 15:51:53 +0900362 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800363
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 Krulece5a06e02019-03-06 17:09:03 -0800396 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800397 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800398
399 int int_value = atoi(value);
400 if (int_value) {
401 mUseSmart90ForVideo = true;
402 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800403
Dan Stozaec460082018-12-17 15:35:09 -0800404 property_get("debug.sf.luma_sampling", value, "1");
405 mLumaSampling = atoi(value);
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
Ady Abraham97d04232019-03-05 19:48:12 -0800591 // set the refresh rate according to the policy
592 const auto displayId = getInternalDisplayIdLocked();
593 LOG_ALWAYS_FATAL_IF(!displayId);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800594
Ady Abraham97d04232019-03-05 19:48:12 -0800595 const auto performanceRefreshRate =
596 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
597
598 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800599 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800600 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800601 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800602 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800603 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800604}
605
Dan Stoza436ccf32018-06-21 12:10:12 -0700606uint32_t SurfaceFlinger::getNewTexture() {
607 {
608 std::lock_guard lock(mTexturePoolMutex);
609 if (!mTexturePool.empty()) {
610 uint32_t name = mTexturePool.back();
611 mTexturePool.pop_back();
612 ATRACE_INT("TexturePoolSize", mTexturePool.size());
613 return name;
614 }
615
616 // The pool was too small, so increase it for the future
617 ++mTexturePoolSize;
618 }
619
620 // The pool was empty, so we need to get a new texture name directly using a
621 // blocking call to the main thread
622 uint32_t name = 0;
623 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
624 return name;
625}
626
Mathias Agopian3f844832013-08-07 21:24:32 -0700627void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700629}
630
Wei Wangf9b05ee2017-07-19 20:59:39 -0700631// Do not call property_set on main thread which will be blocked by init
632// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700634 ALOGI( "SurfaceFlinger's main thread ready to run. "
635 "Initializing graphics H/W...");
636
Ana Krulec757f63a2019-01-25 10:46:18 -0800637 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900638
Steven Thomasb02664d2017-07-26 18:48:28 -0700639 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800641 mScheduler =
642 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
643 auto resyncCallback =
644 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800645
Ana Krulecc2870422019-01-29 19:00:58 -0800646 mAppConnectionHandle =
647 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
648 resyncCallback,
649 impl::EventThread::InterceptVSyncsCallback());
650 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
651 resyncCallback, [this](nsecs_t timestamp) {
652 mInterceptor->saveVSyncEvent(timestamp);
653 });
654
655 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
656 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
657 mSfConnectionHandle.get());
658
Kevin DuBois413287f2019-02-25 08:46:47 -0800659 mRegionSamplingThread =
660 new RegionSamplingThread(*this, *mScheduler,
661 RegionSamplingThread::EnvironmentTimingTunables());
662
Steven Thomasb02664d2017-07-26 18:48:28 -0700663 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700664 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700665 renderEngineFeature |= (useColorManagement ?
666 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700667 renderEngineFeature |= (useContextPriority ?
668 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700669
670 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800671 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800674 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Mathias Agopian92a979a2012-08-02 18:32:23 -0700711 // initialize our drawing state
712 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700713
Andy McFadden13a082e2012-08-24 10:16:42 -0700714 // set initial conditions (e.g. unblank default device)
715 initializeDisplays();
716
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700717 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700718
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700720
721 const bool presentFenceReliable =
722 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
723 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700724
725 if (mStartPropertySetThread->Start() != NO_ERROR) {
726 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728
Ady Abraham97d04232019-03-05 19:48:12 -0800729 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800730 mScheduler->setChangeRefreshRateCallback(
731 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
732 Mutex::Autolock lock(mStateLock);
733 setRefreshRateTo(type, event);
734 });
Kevin DuBois36233132019-02-19 14:08:55 -0800735 }
Ady Abraham1902d072019-03-01 17:18:59 -0800736 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
737 getHwComposer().getConfigs(*display->getId()));
738 mRefreshRateStats =
739 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
740 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700743}
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700746 Mutex::Autolock _l(mStateLock);
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748 char value[PROPERTY_VALUE_MAX];
749
750 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100754
755 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700756 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800757
758 property_get("persist.sys.sf.color_mode", value, "0");
759 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800815status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800821 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 if (!displayId) {
823 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dominik Laskowski075d3172018-05-24 15:50:06 -0700845 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 DisplayInfo info = DisplayInfo();
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 float xdpi = hwConfig->getDpiX();
849 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700851 info.w = hwConfig->getWidth();
852 info.h = hwConfig->getHeight();
853 // Default display viewport to display width and height
854 info.viewportW = info.w;
855 info.viewportH = info.h;
856
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800857 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 // The density of the device is provided by a build property
859 float density = Density::getBuildDensity() / 160.0f;
860 if (density == 0) {
861 // the build doesn't provide a density -- this is wrong!
862 // use xdpi instead
863 ALOGE("ro.sf.lcd_density must be defined as a build property");
864 density = xdpi / 160.0f;
865 }
866 if (Density::getEmuDensity()) {
867 // if "qemu.sf.lcd_density" is specified, it overrides everything
868 xdpi = ydpi = density = Density::getEmuDensity();
869 density /= 160.0f;
870 }
871 info.density = density;
872
873 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700874 const auto display = getDefaultDisplayDeviceLocked();
875 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700876
877 // This is for screenrecord
878 const Rect viewport = display->getViewport();
879 if (viewport.isValid()) {
880 info.viewportW = uint32_t(viewport.getWidth());
881 info.viewportH = uint32_t(viewport.getHeight());
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 } else {
884 // TODO: where should this value come from?
885 static const int TV_DENSITY = 213;
886 info.density = TV_DENSITY / 160.0f;
887 info.orientation = 0;
888 }
889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 info.xdpi = xdpi;
891 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800893 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800907 info.presentationDeadline =
908 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
910 // All non-virtual displays are currently considered secure.
911 info.secure = true;
912
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800913 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700914 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800915 std::swap(info.w, info.h);
916 }
917
Michael Wright28f24d02016-07-12 13:30:53 -0700918 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700919 }
920
Dan Stoza7f7da322014-05-02 15:26:25 -0700921 return NO_ERROR;
922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
925 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700926 return BAD_VALUE;
927 }
928
Ana Krulecc2870422019-01-29 19:00:58 -0800929 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return NO_ERROR;
931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
934 const auto display = getDisplayDevice(displayToken);
935 if (!display) {
936 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Ady Abraham447052e2019-02-13 16:07:27 -0800943void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800944 Scheduler::ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800946
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 // Lock is acquired by setRefreshRateTo.
948 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800949 if (!display) {
950 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
951 displayToken.get());
952 return;
953 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700954 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955 ALOGW("Attempt to set active config %d for virtual display", mode);
956 return;
957 }
958 int currentDisplayPowerMode = display->getPowerMode();
959 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
960 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700961 return;
962 }
963
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800965 // config twice. However event generation config might have changed so we need to update it
966 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800968 const Scheduler::ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
Ady Abraham9360a222019-02-27 17:05:30 -0800969 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800970
971 if (!mDesiredActiveConfigChanged) {
972 // This is the first time we set the desired
973 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
974
975 // This will trigger HWC refresh without resetting the idle timer.
976 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 mDesiredActiveConfigChanged = true;
979 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980}
981
982status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
983 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800984
985 std::vector<int32_t> allowedConfig;
986 allowedConfig.push_back(mode);
987
988 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991void SurfaceFlinger::setActiveConfigInternal() {
992 ATRACE_CALL();
993
994 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800995 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996
997 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
998 display->setActiveConfig(mUpcomingActiveConfig.configId);
999
Ana Krulecc2870422019-01-29 19:00:58 -08001000 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001001 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1002 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001004 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001005 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1006 mUpcomingActiveConfig.configId);
1007 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001008}
1009
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001011 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012 if (mCheckPendingFence) {
1013 if (mPreviousPresentFence != Fence::NO_FENCE &&
1014 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1015 // fence has not signaled yet. wait for the next invalidate
1016 repaintEverythingForHWC();
1017 return true;
1018 }
1019
1020 // We received the present fence from the HWC, so we assume it successfully updated
1021 // the config, hence we update SF.
1022 mCheckPendingFence = false;
1023 setActiveConfigInternal();
1024 }
1025
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 // Store the local variable to release the lock.
1027 ActiveConfigInfo desiredActiveConfig;
1028 {
1029 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (!mDesiredActiveConfigChanged) {
1031 return false;
1032 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001033 desiredActiveConfig = mDesiredActiveConfig;
1034 }
1035
1036 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1038 // display is not valid or we are already in the requested mode
1039 // on both cases there is nothing left to do
1040 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1041 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1042 mDesiredActiveConfigChanged = false;
1043 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1044 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046
Ady Abraham838de062019-02-04 10:24:03 -08001047 // Desired active config was set, it is different than the config currently in use, however
1048 // allowed configs might have change by the time we process the refresh.
1049 // Make sure the desired config is still allowed
1050 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1051 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1052 mDesiredActiveConfig.configId = display->getActiveConfig();
1053 return false;
1054 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001055 mUpcomingActiveConfig = desiredActiveConfig;
1056 const auto displayId = display->getId();
1057 LOG_ALWAYS_FATAL_IF(!displayId);
1058
1059 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1060 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1061
1062 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063 mCheckPendingFence = true;
1064
1065 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001066}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1069 Vector<ColorMode>* outColorModes) {
1070 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001071 return BAD_VALUE;
1072 }
1073
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001076 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1077
1078 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1079 if (!displayId) {
1080 return NAME_NOT_FOUND;
1081 }
1082
Dominik Laskowski075d3172018-05-24 15:50:06 -07001083 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001084 }
Michael Wright28f24d02016-07-12 13:30:53 -07001085 outColorModes->clear();
1086 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1087
1088 return NO_ERROR;
1089}
1090
Daniel Solomon42d04562019-01-20 21:03:19 -08001091status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1092 ui::DisplayPrimaries &primaries) {
1093 if (!displayToken) {
1094 return BAD_VALUE;
1095 }
1096
1097 // Currently we only support this API for a single internal display.
1098 if (getInternalDisplayToken() != displayToken) {
1099 return BAD_VALUE;
1100 }
1101
1102 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1103 return NO_ERROR;
1104}
1105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1107 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001108 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001109 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001110 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001114 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 Vector<ColorMode> modes;
1116 getDisplayColorModes(displayToken, &modes);
1117 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1118 if (mode < ColorMode::NATIVE || !exists) {
1119 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1120 decodeColorMode(mode).c_str(), mode, displayToken.get());
1121 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 const auto display = getDisplayDevice(displayToken);
1124 if (!display) {
1125 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 } else if (display->isVirtual()) {
1128 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1129 decodeColorMode(mode).c_str(), mode);
1130 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001131 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1132 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133 }
1134 }));
1135
Michael Wright28f24d02016-07-12 13:30:53 -07001136 return NO_ERROR;
1137}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001138
Svetoslavd85084b2014-03-20 10:28:31 -07001139status_t SurfaceFlinger::clearAnimationFrameStats() {
1140 Mutex::Autolock _l(mStateLock);
1141 mAnimFrameTracker.clearStats();
1142 return NO_ERROR;
1143}
1144
1145status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.getStats(outStats);
1148 return NO_ERROR;
1149}
1150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1152 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 Mutex::Autolock _l(mStateLock);
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 const auto display = getDisplayDeviceLocked(displayToken);
1156 if (!display) {
1157 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 return BAD_VALUE;
1159 }
1160
Peiyong Linfb069302018-04-25 14:34:31 -07001161 // At this point the DisplayDeivce should already be set up,
1162 // meaning the luminance information is already queried from
1163 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001165 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1166 capabilities.getDesiredMaxLuminance(),
1167 capabilities.getDesiredMaxAverageLuminance(),
1168 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001169
1170 return NO_ERROR;
1171}
1172
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001173status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1174 ui::PixelFormat* outFormat,
1175 ui::Dataspace* outDataspace,
1176 uint8_t* outComponentMask) const {
1177 if (!outFormat || !outDataspace || !outComponentMask) {
1178 return BAD_VALUE;
1179 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001180 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001181 if (!display || !display->getId()) {
1182 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1183 return BAD_VALUE;
1184 }
1185 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1186 outDataspace, outComponentMask);
1187}
1188
Kevin DuBois74e53772018-11-19 10:52:38 -08001189status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1190 bool enable, uint8_t componentMask,
1191 uint64_t maxFrames) const {
1192 const auto display = getDisplayDevice(displayToken);
1193 if (!display || !display->getId()) {
1194 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1195 return BAD_VALUE;
1196 }
1197
1198 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1199 componentMask, maxFrames);
1200}
1201
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001202status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1203 uint64_t maxFrames, uint64_t timestamp,
1204 DisplayedFrameStats* outStats) const {
1205 const auto display = getDisplayDevice(displayToken);
1206 if (!display || !display->getId()) {
1207 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1208 return BAD_VALUE;
1209 }
1210
1211 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1212 outStats);
1213}
1214
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001215status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1216 if (!outSupported) {
1217 return BAD_VALUE;
1218 }
1219 *outSupported = getRenderEngine().supportsProtectedContent();
1220 return NO_ERROR;
1221}
1222
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001223status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1224 bool* outIsWideColorDisplay) const {
1225 if (!displayToken || !outIsWideColorDisplay) {
1226 return BAD_VALUE;
1227 }
1228 Mutex::Autolock _l(mStateLock);
1229 const auto display = getDisplayDeviceLocked(displayToken);
1230 if (!display) {
1231 return BAD_VALUE;
1232 }
1233 *outIsWideColorDisplay = display->hasWideColorGamut();
1234 return NO_ERROR;
1235}
1236
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001237status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001238 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001240
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 if (mInjectVSyncs == enable) {
1242 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001243 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244
Ana Krulecc2870422019-01-29 19:00:58 -08001245 auto resyncCallback =
1246 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001248 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 if (enable) {
1251 ALOGV("VSync Injections enabled");
1252 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001253 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001254 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001255 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001256 impl::EventThread::InterceptVSyncsCallback(),
1257 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001259 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260 } else {
1261 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001262 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1263 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001264 }
1265
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001266 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001267 }));
1268
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001269 return NO_ERROR;
1270}
1271
1272status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 Mutex::Autolock _l(mStateLock);
1274
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001275 if (!mInjectVSyncs) {
1276 ALOGE("VSync Injections not enabled");
1277 return BAD_VALUE;
1278 }
1279 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1280 ALOGV("Injecting VSync inside SurfaceFlinger");
1281 mVSyncInjector->onInjectSyncEvent(when);
1282 }
1283 return NO_ERROR;
1284}
1285
Lloyd Pique755e3192018-01-31 16:46:15 -08001286status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1287 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001288 // Try to acquire a lock for 1s, fail gracefully
1289 const status_t err = mStateLock.timedLock(s2ns(1));
1290 const bool locked = (err == NO_ERROR);
1291 if (!locked) {
1292 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1293 return TIMED_OUT;
1294 }
1295
1296 outLayers->clear();
1297 mCurrentState.traverseInZOrder([&](Layer* layer) {
1298 outLayers->push_back(layer->getLayerDebugInfo());
1299 });
1300
1301 mStateLock.unlock();
1302 return NO_ERROR;
1303}
1304
Peiyong Linc6780972018-10-28 15:24:08 -07001305status_t SurfaceFlinger::getCompositionPreference(
1306 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1307 Dataspace* outWideColorGamutDataspace,
1308 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001309 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001310 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001311 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001312 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001313 return NO_ERROR;
1314}
1315
Dan Stozaec460082018-12-17 15:35:09 -08001316status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1317 const sp<IBinder>& stopLayerHandle,
1318 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001319 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001320 return BAD_VALUE;
1321 }
1322 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001323 return NO_ERROR;
1324}
1325
Dan Stozaec460082018-12-17 15:35:09 -08001326status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001327 if (!listener) {
1328 return BAD_VALUE;
1329 }
Dan Stozaec460082018-12-17 15:35:09 -08001330 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001331 return NO_ERROR;
1332}
Dan Gittik57e63c52019-01-18 16:37:54 +00001333
1334status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1335 bool* outSupport) const {
1336 if (!displayToken || !outSupport) {
1337 return BAD_VALUE;
1338 }
1339 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1340 if (!displayId) {
1341 return NAME_NOT_FOUND;
1342 }
1343 *outSupport =
1344 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1345 return NO_ERROR;
1346}
1347
1348status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1349 float brightness) const {
1350 if (!displayToken) {
1351 return BAD_VALUE;
1352 }
1353 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1354 if (!displayId) {
1355 return NAME_NOT_FOUND;
1356 }
1357 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1358}
1359
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001360// ----------------------------------------------------------------------------
1361
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001362sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1363 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001364 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001365 Mutex::Autolock lock(mStateLock);
1366 return getVsyncPeriod();
1367 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001368
Ana Krulecc2870422019-01-29 19:00:58 -08001369 const auto& handle =
1370 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001371
Ana Krulecc2870422019-01-29 19:00:58 -08001372 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001373}
1374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001375// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376
1377void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001378 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001379}
1380
1381void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001382 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001383}
1384
1385void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001386 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001387}
1388
1389void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001390 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001391 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001392}
1393
1394status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001395 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001396 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001397}
1398
1399status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001400 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001401 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001402 if (res == NO_ERROR) {
1403 msg->wait();
1404 }
1405 return res;
1406}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001407
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001408void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001409 do {
1410 waitForEvent();
1411 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001412}
1413
Dominik Laskowski83b88212018-12-11 13:34:06 -08001414nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001415 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001416 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1417 return 0;
1418 }
1419
1420 const auto config = getHwComposer().getActiveConfig(*displayId);
1421 return config ? config->getVsyncPeriod() : 0;
1422}
1423
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001424void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1425 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001426 ATRACE_NAME("SF onVsync");
1427
Steven Thomas3cfac282017-02-06 12:29:30 -08001428 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001430 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 return;
1432 }
1433
Dominik Laskowski075d3172018-05-24 15:50:06 -07001434 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001435 return;
1436 }
1437
Dominik Laskowski075d3172018-05-24 15:50:06 -07001438 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001439 // For now, we don't do anything with external display vsyncs.
1440 return;
1441 }
1442
Ana Krulecc2870422019-01-29 19:00:58 -08001443 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001444}
1445
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001447 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1448 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001449}
1450
Ady Abraham838de062019-02-04 10:24:03 -08001451bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1452 std::lock_guard lock(mAllowedConfigsLock);
1453
1454 // if allowed configs are not set yet for this display, every config is considered allowed
1455 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1456 return true;
1457 }
1458
1459 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1460}
1461
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001462void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001463 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001464 return;
1465 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001466 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001467
Ana Krulec7d1d6832018-12-27 11:10:09 -08001468 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001469 const auto displayId = getInternalDisplayIdLocked();
1470 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001471 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001472
Ady Abraham1902d072019-03-01 17:18:59 -08001473 auto desiredConfigId = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate).configId;
1474 const auto display = getDisplayDeviceLocked(displayToken);
1475 if (desiredConfigId == display->getActiveConfig()) {
1476 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001477 }
Ady Abraham1902d072019-03-01 17:18:59 -08001478
1479 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1480 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1481 return;
1482 }
1483
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001484 mPhaseOffsets->setRefreshRateType(refreshRate);
Ady Abraham1902d072019-03-01 17:18:59 -08001485 setDesiredActiveConfig(getInternalDisplayTokenLocked(), desiredConfigId, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486}
1487
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001488void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001489 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001490 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001491 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492
Lloyd Piqueba04e622017-12-14 17:11:26 -08001493 // Ignore events that do not have the right sequenceId.
1494 if (sequenceId != getBE().mComposerSequenceId) {
1495 return;
1496 }
1497
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 // Only lock if we're not on the main thread. This function is normally
1499 // called on a hwbinder thread, but for the primary display it's called on
1500 // the main thread with the state lock already held, so don't attempt to
1501 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001503
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001504 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001505
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001506 if (std::this_thread::get_id() == mMainThreadId) {
1507 // Process all pending hot plug events immediately if we are on the main thread.
1508 processDisplayHotplugEventsLocked();
1509 }
1510
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001512}
1513
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001514void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001515 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001516 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001518 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001519 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001520}
1521
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001522void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001523 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001525 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001526 getHwComposer().setVsyncEnabled(*displayId,
1527 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1528 }
Mathias Agopian86303202012-07-24 22:46:10 -07001529}
1530
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001532void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001533 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534 // Clear the drawing state so that the logic inside of
1535 // handleTransactionLocked will fire. It will determine the delta between
1536 // mCurrentState and mDrawingState and re-apply all changes when we make the
1537 // transition.
1538 mDrawingState.displays.clear();
1539 mDisplays.clear();
1540}
1541
Steven Thomas050b2c82017-03-06 11:45:16 -08001542void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001543 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001544 if (!mVrFlinger)
1545 return;
1546 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001547 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001548 return;
1549 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001550
Lloyd Pique441d5042018-10-18 16:49:51 -07001551 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 ALOGE("Vr flinger is only supported for remote hardware composer"
1553 " service connections. Ignoring request to transition to vr"
1554 " flinger.");
1555 mVrFlingerRequestsDisplay = false;
1556 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001557 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001558
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001560
Steven Thomas0123ac62018-07-12 11:32:34 -07001561 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001562 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001563
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001564 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001565
1566 // Clear out all the output layers from the composition engine for all
1567 // displays before destroying the hardware composer interface. This ensures
1568 // any HWC layers are destroyed through that interface before it becomes
1569 // invalid.
1570 for (const auto& [token, displayDevice] : mDisplays) {
1571 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1572 compositionengine::Output::OutputLayers());
1573 }
1574
Steven Thomas0123ac62018-07-12 11:32:34 -07001575 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1576 // called below. Clear the reference now so we don't accidentally use it
1577 // later.
1578 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001585 // Delete the current instance before creating the new one
1586 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1587 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1588 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1589 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590
Lloyd Pique441d5042018-10-18 16:49:51 -07001591 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001592 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001593
1594 if (vrFlingerRequestsDisplay) {
1595 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001596 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001597
1598 mVisibleRegionsDirty = true;
1599 invalidateHwcGeometry();
1600
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001601 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001602 display = getDefaultDisplayDeviceLocked();
1603 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001604 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001605
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001607 const nsecs_t vsyncPeriod = getVsyncPeriod();
1608 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001609
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001610 // The present fences returned from vr_hwc are not an accurate
1611 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001612 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001613
Steven Thomasb02664d2017-07-26 18:48:28 -07001614 // Use phase of 0 since phase is not known.
1615 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001617 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001618
Ana Krulecc2870422019-01-29 19:00:58 -08001619 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001620
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001621 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001623}
1624
Mathias Agopian4fec8732012-06-29 14:12:52 -07001625void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001626 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001627 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001628 case MessageQueue::INVALIDATE: {
Alec Mouricc0fc602019-02-26 21:45:19 -08001629 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
1630 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
1631 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1632 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1633 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1634 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1635 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1636 if (frameMissed) {
1637 mFrameMissedCount++;
1638 mTimeStats->incrementMissedFrames();
1639 }
1640
Alec Mouri40189b02019-03-05 15:07:54 -08001641 if (hwcFrameMissed) {
1642 mHwcFrameMissedCount++;
1643 }
1644
1645 if (gpuFrameMissed) {
1646 mGpuFrameMissedCount++;
1647 }
1648
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001649 if (mUseSmart90ForVideo) {
1650 // This call is made each time SF wakes up and creates a new frame. It is part
1651 // of video detection feature.
1652 mScheduler->updateFpsBasedOnNativeWindowApi();
1653 }
1654
Ady Abrahamb838aed2019-02-12 15:30:16 -08001655 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001656 break;
1657 }
1658
Alec Mourife3dc942019-02-12 14:19:18 -08001659 // For now, only propagate backpressure when missing a hwc frame.
1660 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001661 if (mPropagateBackpressure) {
1662 signalLayerUpdate();
1663 break;
1664 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001665 }
Dan Stoza50182882016-07-08 12:02:20 -07001666
Steven Thomas050b2c82017-03-06 11:45:16 -08001667 // Now that we're going to make it to the handleMessageTransaction()
1668 // call below it's safe to call updateVrFlinger(), which will
1669 // potentially trigger a display handoff.
1670 updateVrFlinger();
1671
Dan Stoza6b9454d2014-11-07 16:00:59 -08001672 bool refreshNeeded = handleMessageTransaction();
1673 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001674
1675 updateCursorAsync();
1676 updateInputFlinger();
1677
Dan Stoza58784442014-12-02 16:58:17 -08001678 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001679 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001680 // Signal a refresh if a transaction modified the window state,
1681 // a new buffer was latched, or if HWC has requested a full
1682 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001683 signalRefresh();
1684 }
1685 break;
1686 }
1687 case MessageQueue::REFRESH: {
1688 handleMessageRefresh();
1689 break;
1690 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001691 }
1692}
1693
Dan Stoza6b9454d2014-11-07 16:00:59 -08001694bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001695 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001696 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001697
1698 // Apply any ready transactions in the queues if there are still transactions that have not been
1699 // applied, wake up during the next vsync period and check again
1700 bool transactionNeeded = false;
1701 if (!flushTransactionQueues()) {
1702 transactionNeeded = true;
1703 }
1704
Mathias Agopian4fec8732012-06-29 14:12:52 -07001705 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001706 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001708
1709 if (transactionNeeded) {
1710 setTransactionFlags(eTransactionNeeded);
1711 }
1712
1713 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714}
1715
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001718
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001719 mRefreshPending = false;
1720
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001721 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001722 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001723 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001724 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001725 for (const auto& [token, display] : mDisplays) {
1726 beginFrame(display);
1727 prepareFrame(display);
1728 doDebugFlashRegions(display, repaintEverything);
1729 doComposition(display, repaintEverything);
1730 }
1731
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001733
1734 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001735 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001736
Dan Stozabfbffeb2016-07-21 14:49:33 -07001737 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001738 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001739 for (const auto& [token, displayDevice] : mDisplays) {
1740 auto display = displayDevice->getCompositionDisplay();
1741 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001742 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001743 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001744 mHadDeviceComposition =
1745 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001746 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001747
Jorim Jaggi90535212018-05-23 23:44:06 +02001748 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001749
David Sodman7e4ae112018-02-09 15:02:28 -08001750 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001752
David Sodmanfa9b2af2017-12-24 13:28:59 -08001753
1754bool SurfaceFlinger::handleMessageInvalidate() {
1755 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001756 bool refreshNeeded = handlePageFlip();
1757
Vishnu Nair4351ad52019-02-11 14:13:02 -08001758 if (mVisibleRegionsDirty) {
1759 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001760 if (mTracingEnabled) {
1761 mTracing.notify("visibleRegionsDirty");
1762 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001763 }
1764
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001765 for (auto& layer : mLayersPendingRefresh) {
1766 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001767 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001768 invalidateLayerStack(layer, visibleReg);
1769 }
1770 mLayersPendingRefresh.clear();
1771 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001772}
1773
David Sodman79bba0e2018-08-05 18:07:49 -07001774void SurfaceFlinger::calculateWorkingSet() {
1775 ATRACE_CALL();
1776 ALOGV(__FUNCTION__);
1777
David Sodman79bba0e2018-08-05 18:07:49 -07001778 // build the h/w work list
1779 if (CC_UNLIKELY(mGeometryInvalid)) {
1780 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 for (const auto& [token, displayDevice] : mDisplays) {
1782 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001783
Lloyd Piquea83776c2019-01-29 18:42:32 -08001784 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001785
Lloyd Piquea83776c2019-01-29 18:42:32 -08001786 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1787 auto& compositionState = layer->editState();
1788 compositionState.forceClientComposition = false;
1789 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1790 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792
Lloyd Piquea83776c2019-01-29 18:42:32 -08001793 // The output Z order is set here based on a simple counter.
1794 compositionState.z = zOrder++;
1795
1796 // Update the display independent composition state. This goes
1797 // to the general composition layer state structure.
1798 // TODO: Do this once per compositionengine::CompositionLayer.
1799 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1800 true);
1801
1802 // Recalculate the geometry state of the output layer.
1803 layer->updateCompositionState(true);
1804
1805 // Write the updated geometry state to the HWC
1806 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001807 }
1808 }
1809 }
1810
1811 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 for (const auto& [token, displayDevice] : mDisplays) {
1813 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001814 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001816 continue;
1817 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001818 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001819
1820 if (mDrawingState.colorMatrixChanged) {
1821 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001822 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001823 Dataspace targetDataspace = Dataspace::UNKNOWN;
1824 if (useColorManagement) {
1825 ColorMode colorMode;
1826 RenderIntent renderIntent;
1827 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1828 display->setColorMode(colorMode, targetDataspace, renderIntent);
1829 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001830 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001831 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001832 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001833 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1834 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001835 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001836 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001837 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1838 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001839 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001840 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001841 }
1842
Peiyong Lind3788632018-09-18 16:01:31 -07001843 // TODO(b/111562338) remove when composer 2.3 is shipped.
1844 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001845 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001846 }
1847
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001848 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001849 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001850 }
1851
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001852 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001853 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001854 layer->setCompositionType(displayDevice,
1855 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001856 continue;
1857 }
1858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001860 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001861 displayDevice->getSupportedPerFrameMetadata(),
1862 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1863 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001864 }
1865 }
1866
1867 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001868
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001869 for (const auto& [token, displayDevice] : mDisplays) {
1870 auto display = displayDevice->getCompositionDisplay();
1871 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001872 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1873 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1874 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001875 }
1876 }
David Sodman79bba0e2018-08-05 18:07:49 -07001877}
1878
Lloyd Pique32cbe282018-10-19 13:09:22 -07001879void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1880 bool repaintEverything) {
1881 auto display = displayDevice->getCompositionDisplay();
1882 const auto& displayState = display->getState();
1883
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884 // is debugging enabled
1885 if (CC_LIKELY(!mDebugRegion))
1886 return;
1887
Lloyd Pique32cbe282018-10-19 13:09:22 -07001888 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001889 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001890 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001891 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001892 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001893 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001894 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001896 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897 }
1898 }
1899
Lloyd Pique32cbe282018-10-19 13:09:22 -07001900 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901
1902 if (mDebugRegion > 1) {
1903 usleep(mDebugRegion * 1000);
1904 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001905
Lloyd Pique32cbe282018-10-19 13:09:22 -07001906 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907}
1908
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001909void SurfaceFlinger::logLayerStats() {
1910 ATRACE_CALL();
1911 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001912 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001914 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001916 }
1917 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001918
1919 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001920 }
1921}
1922
David Sodman2b406362017-12-15 13:33:47 -08001923void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 ATRACE_CALL();
1926 ALOGV("preComposition");
1927
David Sodman2b406362017-12-15 13:33:47 -08001928 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1929
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001931 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001932 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933 needExtraInvalidate = true;
1934 }
Robert Carr2047fae2016-11-28 14:09:09 -08001935 });
1936
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 if (needExtraInvalidate) {
1938 signalLayerUpdate();
1939 }
1940}
1941
Ana Krulece588e312018-09-18 12:32:24 -07001942void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1943 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Update queue of past composite+present times and determine the
1945 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001948 while (!getBE().mCompositePresentTimes.empty()) {
1949 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 // Cached values should have been updated before calling this method,
1951 // which helps avoid duplicate syscalls.
1952 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1953 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1954 break;
1955 }
1956 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001957 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 }
1959
1960 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001961 while (getBE().mCompositePresentTimes.size() > 16) {
1962 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963 }
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001966}
1967
Ana Krulece588e312018-09-18 12:32:24 -07001968void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1969 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // Integer division and modulo round toward 0 not -inf, so we need to
1971 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001972 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1973 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1974 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
Ana Krulec757f63a2019-01-25 10:46:18 -08001976 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001977 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001978 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001979 }
1980
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 // Snap the latency to a value that removes scheduling jitter from the
1982 // composition and present times, which often have >1ms of jitter.
1983 // Reducing jitter is important if an app attempts to extrapolate
1984 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001985 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001987 nsecs_t bias = stats.vsyncPeriod / 2;
1988 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1989 nsecs_t snappedCompositeToPresentLatency =
1990 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991
David Sodman99974d22017-11-28 12:04:33 -08001992 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001993 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1994 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001995 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001996}
1997
David Sodman2b406362017-12-15 13:33:47 -08001998void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001999{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 ATRACE_CALL();
2001 ALOGV("postComposition");
2002
Brian Anderson3546a3f2016-07-14 11:51:14 -07002003 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002004 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002005 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002006 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002007 }
2008
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002009 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002010 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011
David Sodman73beded2017-11-15 11:56:06 -08002012 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002013 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002014 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002015 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002016 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2017 ->getRenderSurface()
2018 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002019 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020 } else {
2021 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2022 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002025 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2026 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002027 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029
Ana Krulece588e312018-09-18 12:32:24 -07002030 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002031 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032
David Sodman2b406362017-12-15 13:33:47 -08002033 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 // when we started doing work for this frame, but that should be okay
2035 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002036 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002037 CompositorTiming compositorTiming;
2038 {
David Sodman99974d22017-11-28 12:04:33 -08002039 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2040 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002041 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042
Robert Carr2047fae2016-11-28 14:09:09 -08002043 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 bool frameLatched =
2045 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2046 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002047 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002048 recordBufferingStats(layer->getName().string(),
2049 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002050 }
Robert Carr2047fae2016-11-28 14:09:09 -08002051 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002052
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002053 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002054 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002055 }
2056
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002057 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002058 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2059 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002060 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002061 }
2062 }
2063
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002064 if (mAnimCompositionPending) {
2065 mAnimCompositionPending = false;
2066
Brian Anderson4e606e32017-03-16 15:34:57 -07002067 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002069 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002071 // The HWC doesn't support present fences, so use the refresh
2072 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 const nsecs_t presentTime =
2074 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002075 mAnimFrameTracker.setActualPresentTime(presentTime);
2076 }
2077 mAnimFrameTracker.advanceFrame();
2078 }
Dan Stozab90cf072015-03-05 11:05:59 -08002079
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002080 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002081 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002082 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002083 }
2084
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002085 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002086
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2088 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002089 return;
2090 }
2091
2092 nsecs_t currentTime = systemTime();
2093 if (mHasPoweredOff) {
2094 mHasPoweredOff = false;
2095 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002096 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002097 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002098 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2099 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002100 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002101 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002102 }
David Sodman4a36e932017-11-07 14:29:47 -08002103 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002104 }
David Sodman4a36e932017-11-07 14:29:47 -08002105 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002106
2107 {
2108 std::lock_guard lock(mTexturePoolMutex);
2109 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2110 if (refillCount > 0) {
2111 const size_t offset = mTexturePool.size();
2112 mTexturePool.resize(mTexturePoolSize);
2113 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2114 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2115 }
2116 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002117
Marissa Wallfda30bb2018-10-12 11:34:28 -07002118 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002119 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002120
Kevin DuBois413287f2019-02-25 08:46:47 -08002121 if (mLumaSampling && mRegionSamplingThread) {
2122 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002123 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002124}
2125
Vishnu Nair4351ad52019-02-11 14:13:02 -08002126void SurfaceFlinger::computeLayerBounds() {
2127 for (const auto& pair : mDisplays) {
2128 const auto& displayDevice = pair.second;
2129 const auto display = displayDevice->getCompositionDisplay();
2130 for (const auto& layer : mDrawingState.layersSortedByZ) {
2131 // only consider the layers on the given layer stack
2132 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002133 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002134 }
2135
2136 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2137 }
2138 }
2139}
2140
Mathias Agopiancd60f992012-08-16 16:28:27 -07002141void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 ATRACE_CALL();
2143 ALOGV("rebuildLayerStacks");
2144
Mathias Agopiancd60f992012-08-16 16:28:27 -07002145 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002146 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002147 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002148 mVisibleRegionsDirty = false;
2149 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002150
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002151 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002152 const auto& displayDevice = pair.second;
2153 auto display = displayDevice->getCompositionDisplay();
2154 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002155 Region opaqueRegion;
2156 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002157 compositionengine::Output::OutputLayers layersSortedByZ;
2158 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002159 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 const ui::Transform& tr = displayState.transform;
2161 const Rect bounds = displayState.bounds;
2162 if (displayState.isEnabled) {
2163 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002164
Jeff Sharkey76488112017-02-27 14:15:18 -07002165 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002166 auto compositionLayer = layer->getCompositionLayer();
2167 if (compositionLayer == nullptr) {
2168 return;
2169 }
2170
Lloyd Pique32cbe282018-10-19 13:09:22 -07002171 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002172 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2173 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2174
Lloyd Pique07e33212018-12-18 16:33:37 -08002175 bool needsOutputLayer = false;
2176
Lloyd Piqueef36b002019-01-23 17:52:04 -08002177 if (display->belongsInOutput(layer->getLayerStack(),
2178 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002179 Region drawRegion(tr.transform(
2180 layer->visibleNonTransparentRegion));
2181 drawRegion.andSelf(bounds);
2182 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002183 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002184 }
Chia-I Wu83806892017-11-16 10:50:20 -08002185 }
2186
Lloyd Pique07e33212018-12-18 16:33:37 -08002187 if (needsOutputLayer) {
2188 layersSortedByZ.emplace_back(
2189 display->getOrCreateOutputLayer(displayId, compositionLayer,
2190 layerFE));
2191 deprecated_layersSortedByZ.add(layer);
2192
2193 auto& outputLayerState = layersSortedByZ.back()->editState();
2194 outputLayerState.visibleRegion =
2195 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2196 } else if (displayId) {
2197 // For layers that are being removed from a HWC display,
2198 // and that have queued frames, add them to a a list of
2199 // released layers so we can properly set a fence.
2200 bool hasExistingOutputLayer =
2201 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2202 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2203 mLayersWithQueuedFrames.cend(),
2204 layer) != mLayersWithQueuedFrames.cend();
2205
2206 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002207 layersNeedingFences.add(layer);
2208 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002209 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 });
2211 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002212
2213 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2214
2215 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002216 displayDevice->setLayersNeedingFences(layersNeedingFences);
2217
2218 Region undefinedRegion{bounds};
2219 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2220
2221 display->editState().undefinedRegion = undefinedRegion;
2222 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002223 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002224 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002226
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002227// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002228// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002229// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002230// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002231// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002232// The returned HDR data space is one of
2233// - Dataspace::UNKNOWN
2234// - Dataspace::BT2020_HLG
2235// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2237 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002238 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002239 *outHdrDataSpace = Dataspace::UNKNOWN;
2240
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002242 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002243 case Dataspace::V0_SCRGB:
2244 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002245 case Dataspace::BT2020:
2246 case Dataspace::BT2020_ITU:
2247 case Dataspace::BT2020_LINEAR:
2248 case Dataspace::DISPLAY_BT2020:
2249 bestDataSpace = Dataspace::DISPLAY_BT2020;
2250 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002251 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002252 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002253 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002254 case Dataspace::BT2020_PQ:
2255 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002256 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002257 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002259 case Dataspace::BT2020_HLG:
2260 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002261 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002262 // When there's mixed PQ content and HLG content, we set the HDR
2263 // data space to be BT2020_PQ and convert HLG to PQ.
2264 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2265 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002266 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 break;
2268 default:
2269 break;
2270 }
Romain Guy54f154a2017-10-24 21:40:32 +01002271 }
2272
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002274}
2275
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2278 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002279 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2280 *outMode = ColorMode::NATIVE;
2281 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002284 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002285
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002289 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2290
Peiyong Lina3ea5592019-02-10 14:45:00 -08002291 switch (mForceColorMode) {
2292 case ColorMode::SRGB:
2293 bestDataSpace = Dataspace::V0_SRGB;
2294 break;
2295 case ColorMode::DISPLAY_P3:
2296 bestDataSpace = Dataspace::DISPLAY_P3;
2297 break;
2298 default:
2299 break;
2300 }
2301
Peiyong Lindfde5112018-06-05 10:58:41 -07002302 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002303 const bool isHdr =
2304 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002305 if (isHdr) {
2306 bestDataSpace = hdrDataSpace;
2307 }
2308
Chia-I Wu0d711262018-05-21 15:19:35 -07002309 RenderIntent intent;
2310 switch (mDisplayColorSetting) {
2311 case DisplayColorSetting::MANAGED:
2312 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002313 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002314 break;
2315 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002316 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002317 break;
2318 default: // vendor display color setting
2319 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2320 break;
2321 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002322
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002323 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002324}
2325
Lloyd Pique32cbe282018-10-19 13:09:22 -07002326void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2327 auto display = displayDevice->getCompositionDisplay();
2328 const auto& displayState = display->getState();
2329
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002330 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002331 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2332 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002333
David Sodmanfa9b2af2017-12-24 13:28:59 -08002334 // If nothing has changed (!dirty), don't recompose.
2335 // If something changed, but we don't currently have any visible layers,
2336 // and didn't when we last did a composition, then skip it this time.
2337 // The second rule does two things:
2338 // - When all layers are removed from a display, we'll emit one black
2339 // frame, then nothing more until we get new layers.
2340 // - When a display is created with a private layer stack, we won't
2341 // emit any black frames until a layer is added to the layer stack.
2342 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002343
Dominik Laskowski075d3172018-05-24 15:50:06 -07002344 const char flagPrefix[] = {'-', '+'};
2345 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002346 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2347 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2348 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2349 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002350
Lloyd Pique31cb2942018-10-19 17:23:03 -07002351 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002352
David Sodmanfa9b2af2017-12-24 13:28:59 -08002353 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002354 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002355 }
2356}
2357
Lloyd Pique32cbe282018-10-19 13:09:22 -07002358void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
2361
2362 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002363 return;
David Sodman2b406362017-12-15 13:33:47 -08002364 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002365
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002366 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002367 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002368 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002369}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002370
Lloyd Pique32cbe282018-10-19 13:09:22 -07002371void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002372 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 ALOGV("doComposition");
2374
Lloyd Pique32cbe282018-10-19 13:09:22 -07002375 auto display = displayDevice->getCompositionDisplay();
2376 const auto& displayState = display->getState();
2377
2378 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002379 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002380 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002381
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002383 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002384
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002386 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002387 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002388 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002389}
2390
David Sodmanfa9b2af2017-12-24 13:28:59 -08002391void SurfaceFlinger::postFrame()
2392{
2393 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 const auto display = getDefaultDisplayDeviceLocked();
2395 if (display && getHwComposer().isConnected(*display->getId())) {
2396 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2398 logFrameStats();
2399 }
2400 }
2401}
2402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002404 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 auto display = displayDevice->getCompositionDisplay();
2408 const auto& displayState = display->getState();
2409 const auto displayId = display->getId();
2410
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002412
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 if (displayId) {
2415 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002416 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002417 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002418 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002419 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002420 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002421
Chia-I Wu7b549592017-11-15 09:14:57 -08002422 // The layer buffer from the previous frame (if any) is released
2423 // by HWC only when the release fence from this frame (if any) is
2424 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002425 if (layer->getState().hwc) {
2426 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002427 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002428 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2429 usedClientComposition =
2430 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002431 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002432
2433 // If the layer was client composited in the previous frame, we
2434 // need to merge with the previous client target acquire fence.
2435 // Since we do not track that, always merge with the current
2436 // client target acquire fence when it is available, even though
2437 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002438 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002439 releaseFence =
2440 Fence::merge("LayerRelease", releaseFence,
2441 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002442 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002443
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002444 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 }
Chia-I Wu83806892017-11-16 10:50:20 -08002446
2447 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002449 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002452 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002454 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002455 }
2456 }
2457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId) {
2459 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002460 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462}
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465{
Mathias Agopian841cde52012-03-01 15:44:37 -08002466 ATRACE_CALL();
2467
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002468 // here we keep a copy of the drawing state (that is the state that's
2469 // going to be overwritten by handleTransactionLocked()) outside of
2470 // mStateLock so that the side-effects of the State assignment
2471 // don't happen with mStateLock held (which can cause deadlocks).
2472 State drawingState(mDrawingState);
2473
Mathias Agopianca4d3602011-05-19 15:38:14 -07002474 Mutex::Autolock _l(mStateLock);
2475 const nsecs_t now = systemTime();
2476 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 // Here we're guaranteed that some transaction flags are set
2479 // so we can call handleTransactionLocked() unconditionally.
2480 // We call getTransactionFlags(), which will also clear the flags,
2481 // with mStateLock held to guarantee that mCurrentState won't change
2482 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002483
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002484 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002487
Mathias Agopianca4d3602011-05-19 15:38:14 -07002488 mLastTransactionTime = systemTime() - now;
2489 mDebugInTransaction = 0;
2490 invalidateHwcGeometry();
2491 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002492}
2493
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2495 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 const std::optional<DisplayIdentificationInfo> info =
2497 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002500 continue;
2501 }
2502
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002505 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 mPhysicalDisplayTokens[info->id] = new BBinder();
2507 DisplayDeviceState state;
2508 state.displayId = info->id;
2509 state.isSecure = true; // All physical displays are currently considered secure.
2510 state.displayName = info->name;
2511 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2512 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002513 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002515 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002516
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2518 if (index >= 0) {
2519 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2520 mInterceptor->saveDisplayDeletion(state.sequenceId);
2521 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002522 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 }
2525
2526 processDisplayChangesLocked();
2527 }
2528
2529 mPendingHotplugEvents.clear();
2530}
2531
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002532void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002533 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2534 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002535}
2536
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002539 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 const sp<IGraphicBufferProducer>& producer) {
2541 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002542 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002544 creationArgs.isSecure = state.isSecure;
2545 creationArgs.displaySurface = dispSurface;
2546 creationArgs.hasWideColorGamut = false;
2547 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002548
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002549 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 creationArgs.isPrimary = isInternalDisplay;
2551
2552 if (useColorManagement && displayId) {
2553 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002555 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002558
Dominik Laskowski7e045462018-05-30 13:02:02 -07002559 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002561 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002562 }
tangrobin6753a022018-08-10 10:58:54 +08002563 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 if (displayId) {
2566 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002567 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002569 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570
Lloyd Pique90c115d2018-09-18 21:39:42 -07002571 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002573 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575 // Make sure that composition can never be stalled by a virtual display
2576 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002577 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002578 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2580 }
2581
Dominik Laskowski075d3172018-05-24 15:50:06 -07002582 creationArgs.displayInstallOrientation =
2583 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002584
Lloyd Pique99d3da52018-01-22 17:48:03 -08002585 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002586 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002587
Lloyd Pique90c115d2018-09-18 21:39:42 -07002588 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002589
2590 if (maxFrameBufferAcquiredBuffers >= 3) {
2591 nativeWindowSurface->preallocateBuffers();
2592 }
2593
2594 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002595 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002596 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002598 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002600 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2601 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 if (!state.isVirtual()) {
2603 LOG_ALWAYS_FATAL_IF(!displayId);
2604 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002605 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002607 display->setLayerStack(state.layerStack);
2608 display->setProjection(state.orientation, state.viewport, state.frame);
2609 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002611 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612}
2613
Lloyd Pique347200f2017-12-14 17:00:15 -08002614void SurfaceFlinger::processDisplayChangesLocked() {
2615 // here we take advantage of Vector's copy-on-write semantics to
2616 // improve performance by skipping the transaction entirely when
2617 // know that the lists are identical
2618 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2619 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2620 if (!curr.isIdenticalTo(draw)) {
2621 mVisibleRegionsDirty = true;
2622 const size_t cc = curr.size();
2623 size_t dc = draw.size();
2624
2625 // find the displays that were removed
2626 // (ie: in drawing state but not in current state)
2627 // also handle displays that changed
2628 // (ie: displays that are in both lists)
2629 for (size_t i = 0; i < dc;) {
2630 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2631 if (j < 0) {
2632 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002633 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002634 // Save display ID before disconnecting.
2635 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002636 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002637
2638 if (!display->isVirtual()) {
2639 LOG_ALWAYS_FATAL_IF(!displayId);
2640 dispatchDisplayHotplugEvent(displayId->value, false);
2641 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002642 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002643
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002644 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 } else {
2646 // this display is in both lists. see if something changed.
2647 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2650 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2651 if (state_binder != draw_binder) {
2652 // changing the surface is like destroying and
2653 // recreating the DisplayDevice, so we just remove it
2654 // from the drawing state, so that it get re-added
2655 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002657 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002659 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 mDrawingState.displays.removeItemsAt(i);
2661 dc--;
2662 // at this point we must loop to the next item
2663 continue;
2664 }
2665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002667 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 }
2670 if ((state.orientation != draw[i].orientation) ||
2671 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 }
2674 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002676 }
2677 }
2678 }
2679 ++i;
2680 }
2681
2682 // find displays that were added
2683 // (ie: in current state but not in drawing state)
2684 for (size_t i = 0; i < cc; i++) {
2685 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2686 const DisplayDeviceState& state(curr[i]);
2687
Lloyd Pique542307f2018-10-19 13:24:08 -07002688 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 sp<IGraphicBufferProducer> producer;
2690 sp<IGraphicBufferProducer> bqProducer;
2691 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002692 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002695 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 // Virtual displays without a surface are dormant:
2697 // they have external state (layer stack, projection,
2698 // etc.) but no internal state (i.e. a DisplayDevice).
2699 if (state.surface != nullptr) {
2700 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002701 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 int width = 0;
2703 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2704 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2705 int height = 0;
2706 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2707 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2708 int intFormat = 0;
2709 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2710 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002711 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712
Dominik Laskowski075d3172018-05-24 15:50:06 -07002713 displayId =
2714 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716
2717 // TODO: Plumb requested format back up to consumer
2718
2719 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 bqProducer, bqConsumer,
2722 state.displayName);
2723
2724 dispSurface = vds;
2725 producer = vds;
2726 }
2727 } else {
2728 ALOGE_IF(state.surface != nullptr,
2729 "adding a supported display, but rendering "
2730 "surface is provided (%p), ignoring it",
2731 state.surface.get());
2732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 displayId = state.displayId;
2734 LOG_ALWAYS_FATAL_IF(!displayId);
2735 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 producer = bqProducer;
2737 }
2738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002742 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002744 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002745 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002746 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747 }
2748 }
2749 }
2750 }
2751 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002752
2753 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002754}
2755
Mathias Agopian87baae12012-07-31 12:38:26 -07002756void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002757{
Dan Stoza7dde5992015-05-22 09:51:44 -07002758 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002759 mCurrentState.traverseInZOrder([](Layer* layer) {
2760 layer->notifyAvailableFrames();
2761 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002762
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 /*
2764 * Traversal of the children
2765 * (perform the transaction for each of them if needed)
2766 */
2767
Mathias Agopian3559b072012-08-15 13:46:03 -07002768 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002769 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002771 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772
2773 const uint32_t flags = layer->doTransaction(0);
2774 if (flags & Layer::eVisibleRegion)
2775 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002776
2777 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002778 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002779 }
Robert Carr2047fae2016-11-28 14:09:09 -08002780 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 }
2782
2783 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 */
2786
Mathias Agopiane57f2922012-08-09 16:29:12 -07002787 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002789 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002792 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002793 // The transform hint might have changed for some layers
2794 // (either because a display has changed, or because a layer
2795 // as changed).
2796 //
2797 // Walk through all the layers in currentLayers,
2798 // and update their transform hint.
2799 //
2800 // If a layer is visible only on a single display, then that
2801 // display is used to calculate the hint, otherwise we use the
2802 // default display.
2803 //
2804 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2805 // the hint is set before we acquire a buffer from the surface texture.
2806 //
2807 // NOTE: layer transactions have taken place already, so we use their
2808 // drawing state. However, SurfaceFlinger's own transaction has not
2809 // happened yet, so we must use the current state layer list
2810 // (soon to become the drawing state list).
2811 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002812 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002813 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002814 bool first = true;
2815 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002816 // NOTE: we rely on the fact that layers are sorted by
2817 // layerStack first (so we don't have to traverse the list
2818 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002820 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002821 currentlayerStack = layerStack;
2822 // figure out if this layerstack is mirrored
2823 // (more than one display) if so, pick the default display,
2824 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002825 hintDisplay = nullptr;
2826 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002827 if (display->getCompositionDisplay()
2828 ->belongsInOutput(layer->getLayerStack(),
2829 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 if (hintDisplay) {
2831 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002832 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002835 }
2836 }
2837 }
2838 }
Chet Haase91d25932013-04-11 15:24:55 -07002839
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002841 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2842 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002843
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002844 // could be null when this layer is using a layerStack
2845 // that is not visible on any display. Also can occur at
2846 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002847 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002848 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002849
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002850 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002851 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 if (hintDisplay) {
2853 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002854 }
Robert Carr2047fae2016-11-28 14:09:09 -08002855
2856 first = false;
2857 });
Mathias Agopian84300952012-11-21 16:02:13 -08002858 }
2859
2860
Mathias Agopian3559b072012-08-15 13:46:03 -07002861 /*
2862 * Perform our own transaction if needed
2863 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864
2865 if (mLayersAdded) {
2866 mLayersAdded = false;
2867 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002868 mVisibleRegionsDirty = true;
2869 }
2870
2871 // some layers might have been removed, so
2872 // we need to update the regions they're exposing.
2873 if (mLayersRemoved) {
2874 mLayersRemoved = false;
2875 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002876 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002878 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002879 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002880 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002881 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002882 }
Robert Carr2047fae2016-11-28 14:09:09 -08002883 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 }
2885
Vishnu Nairec0ab382019-02-13 15:32:56 -08002886 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002888}
2889
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002890void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002891 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002892 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002893 return;
2894 }
2895
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002896 if (mVisibleRegionsDirty || mInputInfoChanged) {
2897 mInputInfoChanged = false;
2898 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002899 } else if (mInputWindowCommands.syncInputWindows) {
2900 // If the caller requested to sync input windows, but there are no
2901 // changes to input windows, notify immediately.
2902 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002903 }
2904
2905 executeInputWindowCommands();
2906}
2907
2908void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002909 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002910
2911 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2912 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002913 // When calculating the screen bounds we ignore the transparent region since it may
2914 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002915 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002916 }
2917 });
chaviw291d88a2019-02-14 10:33:58 -08002918
2919 mInputFlinger->setInputWindows(inputHandles,
2920 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2921 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002922}
2923
Vishnu Nairec0ab382019-02-13 15:32:56 -08002924void SurfaceFlinger::commitInputWindowCommands() {
2925 mInputWindowCommands.merge(mPendingInputWindowCommands);
2926 mPendingInputWindowCommands.clear();
2927}
2928
chaviwfbe5d9c2018-12-26 12:23:37 -08002929void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002930 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2931 if (transferTouchFocusCommand.fromToken != nullptr &&
2932 transferTouchFocusCommand.toToken != nullptr &&
2933 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2934 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2935 transferTouchFocusCommand.toToken);
2936 }
2937 }
2938
2939 mInputWindowCommands.clear();
2940}
2941
Riley Andrews03414a12014-07-01 14:22:59 -07002942void SurfaceFlinger::updateCursorAsync()
2943{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002944 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002945 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002946 continue;
2947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002949 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2950 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002951 }
2952 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002953}
2954
chaviw61626f22018-11-15 16:26:27 -08002955void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2956 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002957 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002958 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002959 }
2960 layer->releasePendingBuffer(systemTime());
2961}
2962
Mathias Agopian4fec8732012-06-29 14:12:52 -07002963void SurfaceFlinger::commitTransaction()
2964{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002965 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002966 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967 for (const auto& l : mLayersPendingRemoval) {
2968 recordBufferingStats(l->getName().string(),
2969 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002970
Lloyd Pique07e33212018-12-18 16:33:37 -08002971 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002972 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002973 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002974 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 }
2976 mLayersPendingRemoval.clear();
2977 }
2978
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002979 // If this transaction is part of a window animation then the next frame
2980 // we composite should be considered an animation as well.
2981 mAnimCompositionPending = mAnimTransactionPending;
2982
Nataniel Borges2b796da2019-02-15 13:32:18 -08002983 withTracingLock([&]() {
2984 mDrawingState = mCurrentState;
2985 // clear the "changed" flags in current state
2986 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002987
Nataniel Borges2b796da2019-02-15 13:32:18 -08002988 mDrawingState.traverseInZOrder([](Layer* layer) { layer->commitChildList(); });
Robert Carr1f0a16a2016-10-24 16:27:39 -07002989 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002990
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002991 mTransactionPending = false;
2992 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002993 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994}
2995
Nataniel Borges2b796da2019-02-15 13:32:18 -08002996void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2997 if (mTracingEnabledChanged) {
2998 mTracingEnabled = mTracing.isEnabled();
2999 mTracingEnabledChanged = false;
3000 }
3001
3002 // Synchronize with Tracing thread
3003 std::unique_lock<std::mutex> lock;
3004 if (mTracingEnabled) {
3005 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3006 }
3007
3008 lockedOperation();
3009
3010 // Synchronize with Tracing thread
3011 if (mTracingEnabled) {
3012 lock.unlock();
3013 }
3014}
3015
Lloyd Pique32cbe282018-10-19 13:09:22 -07003016void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003017 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003018 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003020
Lloyd Pique32cbe282018-10-19 13:09:22 -07003021 auto display = displayDevice->getCompositionDisplay();
3022
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023 Region aboveOpaqueLayers;
3024 Region aboveCoveredLayers;
3025 Region dirty;
3026
Mathias Agopian87baae12012-07-31 12:38:26 -07003027 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028
Robert Carr2047fae2016-11-28 14:09:09 -08003029 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003030 // start with the whole surface at its current location
3031 const Layer::State& s(layer->getDrawingState());
3032
Jesse Hall01e29052013-02-19 16:13:35 -08003033 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003034 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003035 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003037
Mathias Agopianab028732010-03-16 16:41:46 -07003038 /*
3039 * opaqueRegion: area of a surface that is fully opaque.
3040 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003042
3043 /*
3044 * visibleRegion: area of a surface that is visible on screen
3045 * and not fully transparent. This is essentially the layer's
3046 * footprint minus the opaque regions above it.
3047 * Areas covered by a translucent surface are considered visible.
3048 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003050
3051 /*
3052 * coveredRegion: area of a surface that is covered by all
3053 * visible regions above it (which includes the translucent areas).
3054 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003056
Jesse Halla8026d22012-09-25 13:25:04 -07003057 /*
3058 * transparentRegion: area of a surface that is hinted to be completely
3059 * transparent. This is only used to tell when the layer has no visible
3060 * non-transparent regions and can be removed from the layer list. It
3061 * does not affect the visibleRegion of this layer or any layers
3062 * beneath it. The hint may not be correct if apps don't respect the
3063 * SurfaceView restrictions (which, sadly, some don't).
3064 */
3065 Region transparentRegion;
3066
Mathias Agopianab028732010-03-16 16:41:46 -07003067
3068 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003069 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003070 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003071 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003074 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003075 if (!visibleRegion.isEmpty()) {
3076 // Remove the transparent area from the visible region
3077 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003078 if (tr.preserveRects()) {
3079 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003080 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003081 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003082 // transformation too complex, can't do the
3083 // transparent region optimization.
3084 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 }
Mathias Agopianab028732010-03-16 16:41:46 -07003086 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Mathias Agopianab028732010-03-16 16:41:46 -07003088 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003090 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003091 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003092 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003093 // the opaque region is the layer's footprint
3094 opaqueRegion = visibleRegion;
3095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 }
3097 }
3098
Robert Carre5f4f692018-01-12 13:12:28 -08003099 if (visibleRegion.isEmpty()) {
3100 layer->clearVisibilityRegions();
3101 return;
3102 }
3103
Mathias Agopianab028732010-03-16 16:41:46 -07003104 // Clip the covered region to the visible region
3105 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3106
3107 // Update aboveCoveredLayers for next (lower) layer
3108 aboveCoveredLayers.orSelf(visibleRegion);
3109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 // subtract the opaque region covered by the layers above us
3111 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112
3113 // compute this layer's dirty region
3114 if (layer->contentDirty) {
3115 // we need to invalidate the whole region
3116 dirty = visibleRegion;
3117 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003118 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 layer->contentDirty = false;
3120 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003121 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003122 * the exposed region consists of two components:
3123 * 1) what's VISIBLE now and was COVERED before
3124 * 2) what's EXPOSED now less what was EXPOSED before
3125 *
3126 * note that (1) is conservative, we start with the whole
3127 * visible region but only keep what used to be covered by
3128 * something -- which mean it may have been exposed.
3129 *
3130 * (2) handles areas that were not covered by anything but got
3131 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003132 */
Mathias Agopianab028732010-03-16 16:41:46 -07003133 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003134 const Region oldVisibleRegion = layer->visibleRegion;
3135 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003136 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3137 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 }
3139 dirty.subtractSelf(aboveOpaqueLayers);
3140
3141 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003142 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143
Mathias Agopianab028732010-03-16 16:41:46 -07003144 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003146
Jesse Halla8026d22012-09-25 13:25:04 -07003147 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 layer->setVisibleRegion(visibleRegion);
3149 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003150 layer->setVisibleNonTransparentRegion(
3151 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003152 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
Mathias Agopian87baae12012-07-31 12:38:26 -07003154 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Chia-I Wuab0c3192017-08-01 11:29:00 -07003157void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003158 for (const auto& [token, displayDevice] : mDisplays) {
3159 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003160 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003161 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003162 }
3163 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003164}
3165
Dan Stoza6b9454d2014-11-07 16:00:59 -08003166bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003168 ALOGV("handlePageFlip");
3169
Brian Andersond6927fb2016-07-23 23:37:30 -07003170 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171
Mathias Agopian4fec8732012-06-29 14:12:52 -07003172 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003173 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003174 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003175
3176 // Store the set of layers that need updates. This set must not change as
3177 // buffers are being latched, as this could result in a deadlock.
3178 // Example: Two producers share the same command stream and:
3179 // 1.) Layer 0 is latched
3180 // 2.) Layer 0 gets a new frame
3181 // 2.) Layer 1 gets a new frame
3182 // 3.) Layer 1 is latched.
3183 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3184 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003185 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003186 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003187 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003188 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003189 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003190 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003191 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003192 } else {
3193 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003195 } else {
3196 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003197 }
Robert Carr2047fae2016-11-28 14:09:09 -08003198 });
3199
Lloyd Piquef2c79392018-12-20 16:23:33 -08003200 if (!mLayersWithQueuedFrames.empty()) {
3201 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3202 // writes to Layer current state. See also b/119481871
3203 Mutex::Autolock lock(mStateLock);
3204
3205 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003206 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003207 mLayersPendingRefresh.push_back(layer);
3208 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003209 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003210 if (layer->isBufferLatched()) {
3211 newDataLatched = true;
3212 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003213 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003214 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003215
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003216 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003217
3218 // If we will need to wake up at some time in the future to deal with a
3219 // queued frame that shouldn't be displayed during this vsync period, wake
3220 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003221 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222 signalLayerUpdate();
3223 }
3224
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003225 // enter boot animation on first buffer latch
3226 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3227 ALOGI("Enter boot animation");
3228 mBootStage = BootStage::BOOTANIMATION;
3229 }
3230
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003232 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Mathias Agopianad456f92011-01-13 17:53:01 -08003235void SurfaceFlinger::invalidateHwcGeometry()
3236{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003237 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003238}
3239
Lloyd Pique32cbe282018-10-19 13:09:22 -07003240void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003241 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003242 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003243 // We only need to actually compose the display if:
3244 // 1) It is being handled by hardware composer, which may need this to
3245 // keep its virtual display state machine in sync, or
3246 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003247 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003248 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003249 return;
3250 }
3251
Dan Stoza9e56aa02015-11-02 13:00:03 -08003252 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003253 base::unique_fd readyFence;
3254 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003255
3256 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003257 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258}
3259
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003260bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3261 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003262 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003263 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003264
Lloyd Pique32cbe282018-10-19 13:09:22 -07003265 auto display = displayDevice->getCompositionDisplay();
3266 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003267 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003268 auto& renderEngine = getRenderEngine();
3269 const bool supportProtectedContent =
3270 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003271
3272 const Region bounds(displayState.bounds);
3273 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003274 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003275 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003276
Peiyong Lind3788632018-09-18 16:01:31 -07003277 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003278 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003279
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003280 renderengine::DisplaySettings clientCompositionDisplay;
3281 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3282 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003283 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003284
Dan Stoza9e56aa02015-11-02 13:00:03 -08003285 if (hasClientComposition) {
3286 ALOGV("hasClientComposition");
3287
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003288 if (displayDevice->isPrimary() && supportProtectedContent) {
3289 bool needsProtected = false;
3290 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3291 // If the layer is a protected layer, mark protected context is needed.
3292 if (layer->isProtected()) {
3293 needsProtected = true;
3294 break;
3295 }
3296 }
3297 if (needsProtected != renderEngine.isProtected() &&
3298 renderEngine.useProtectedContext(needsProtected)) {
3299 display->getRenderSurface()->setProtected(needsProtected);
3300 }
3301 }
3302
Alec Mouri6338c9d2019-02-07 16:57:51 -08003303 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003304
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003305 if (buf == nullptr) {
3306 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3307 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003309 return false;
3310 }
3311
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003312 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3313 clientCompositionDisplay.clip = displayState.scissor;
3314 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003315 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003316
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003317 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003318 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003319 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003320 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003321 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003322 clientCompositionDisplay.outputDataspace = outputDataspace;
3323 clientCompositionDisplay.maxLuminance =
3324 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003325
Lloyd Pique441d5042018-10-18 16:49:51 -07003326 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003327 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003328 getHwComposer()
3329 .hasDisplayCapability(displayId,
3330 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003331
Peiyong Lind3788632018-09-18 16:01:31 -07003332 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003333 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3334 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003335 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003336 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003337 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003338
Mathias Agopian85d751c2012-08-29 16:59:24 -07003339 /*
3340 * and then, render the layers targeted at the framebuffer
3341 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003344 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003345 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003347 const Region viewportRegion(displayState.viewport);
3348 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003349 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003350 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003351 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003352 switch (layer->getCompositionType(displayDevice)) {
3353 case Hwc2::IComposerClient::Composition::CURSOR:
3354 case Hwc2::IComposerClient::Composition::DEVICE:
3355 case Hwc2::IComposerClient::Composition::SIDEBAND:
3356 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003357 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003358 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003359 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003360 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003361 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003362 // never clear the very first layer since we're
3363 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003364 renderengine::LayerSettings layerSettings;
3365 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003366 bool prepared =
3367 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3368 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003369
3370 if (prepared) {
3371 layerSettings.source.buffer.buffer = nullptr;
3372 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3373 layerSettings.alpha = half(0.0);
3374 layerSettings.disableBlending = true;
3375 clientCompositionLayers.push_back(layerSettings);
3376 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003377 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003378 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003379 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003380 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003381 renderengine::LayerSettings layerSettings;
3382 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003383 layer->prepareClientLayer(renderArea, clip, clearRegion,
3384 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 if (prepared) {
3386 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003387 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003388 break;
3389 }
3390 default:
3391 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003392 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003393 } else {
3394 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003395 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003396 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003397 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003398
Alec Mouri820c7402019-01-23 13:02:39 -08003399 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003400 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003401 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003402
3403 // We boost GPU frequency here because there will be color spaces conversion
3404 // and it's expensive. We boost the GPU frequency so that GPU composition can
3405 // finish in time. We must reset GPU frequency afterwards, because high frequency
3406 // consumes extra battery.
3407 const bool expensiveRenderingExpected =
3408 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3409 if (expensiveRenderingExpected && displayId) {
3410 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3411 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003412 if (!debugRegion.isEmpty()) {
3413 Region::const_iterator it = debugRegion.begin();
3414 Region::const_iterator end = debugRegion.end();
3415 while (it != end) {
3416 const Rect& rect = *it++;
3417 renderengine::LayerSettings layerSettings;
3418 layerSettings.source.buffer.buffer = nullptr;
3419 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3420 layerSettings.geometry.boundaries = rect.toFloatRect();
3421 layerSettings.alpha = half(1.0);
3422 clientCompositionLayers.push_back(layerSettings);
3423 }
3424 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003425 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3426 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003427 if (expensiveRenderingExpected && displayId) {
3428 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3429 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003430 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003431 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003432}
3433
Chia-I Wu28e3a252018-09-07 12:05:02 -07003434void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003435 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003436 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437}
3438
Dan Stoza7d89d062015-04-30 13:29:25 -07003439status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003440 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003441 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003442 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003443 const sp<Layer>& parent,
3444 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003445{
Dan Stoza7d89d062015-04-30 13:29:25 -07003446 // add this layer to the current state list
3447 {
3448 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003449 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003450 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3451 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003452 return NO_MEMORY;
3453 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003454 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003456 } else if (parent == nullptr) {
3457 lbc->onRemovedFromCurrentState();
3458 } else if (parent->isRemovedFromCurrentState()) {
3459 parent->addChild(lbc);
3460 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003461 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003462 parent->addChild(lbc);
3463 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003464
Yiwei Zhang243b3782018-05-15 17:40:04 -07003465 if (gbc != nullptr) {
3466 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3467 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3468 mMaxGraphicBufferProducerListSize,
3469 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3470 mGraphicBufferProducerList.size(),
3471 mMaxGraphicBufferProducerListSize, mNumLayers);
3472 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003473 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003474 }
3475
Mathias Agopian96f08192010-06-02 23:28:45 -07003476 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003477 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003478
Dan Stoza7d89d062015-04-30 13:29:25 -07003479 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003480}
3481
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003482uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003483 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003484}
3485
Mathias Agopian3f844832013-08-07 21:24:32 -07003486uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003487 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488}
3489
Mathias Agopian3f844832013-08-07 21:24:32 -07003490uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003491 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003492}
3493
3494uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003495 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003496 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003497 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003498 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003499 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 }
3501 return old;
3502}
3503
Marissa Wall713b63f2018-10-17 15:42:43 -07003504bool SurfaceFlinger::flushTransactionQueues() {
3505 Mutex::Autolock _l(mStateLock);
3506 auto it = mTransactionQueues.begin();
3507 while (it != mTransactionQueues.end()) {
3508 auto& [applyToken, transactionQueue] = *it;
3509
3510 while (!transactionQueue.empty()) {
Marissa Wall78b72202019-03-15 14:58:34 -07003511 const auto&
3512 [states, displays, flags, desiredPresentTime, uncacheBuffer, postTime,
3513 privileged] = transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003514 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003515 break;
3516 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003517 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003518 desiredPresentTime, uncacheBuffer, postTime, privileged,
3519 /*isMainThread*/ true);
Marissa Wall713b63f2018-10-17 15:42:43 -07003520 transactionQueue.pop();
3521 }
3522
3523 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3524 }
3525 return mTransactionQueues.empty();
3526}
3527
chaviwca27f252018-02-06 16:46:39 -08003528bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3529 for (const ComposerState& state : states) {
3530 // Here we need to check that the interface we're given is indeed
3531 // one of our own. A malicious client could give us a nullptr
3532 // IInterface, or one of its own or even one of our own but a
3533 // different type. All these situations would cause us to crash.
3534 if (state.client == nullptr) {
3535 return true;
3536 }
3537
3538 sp<IBinder> binder = IInterface::asBinder(state.client);
3539 if (binder == nullptr) {
3540 return true;
3541 }
3542
3543 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3544 return true;
3545 }
3546 }
3547 return false;
3548}
3549
Marissa Wall17b4e452018-12-26 16:32:34 -08003550bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3551 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003552 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003553 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3554 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3555 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3556 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3557 return false;
3558 }
3559
Marissa Wall713b63f2018-10-17 15:42:43 -07003560 for (const ComposerState& state : states) {
3561 const layer_state_t& s = state.state;
3562 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3563 continue;
3564 }
3565 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003566 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003567 }
3568 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003569 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003570}
3571
3572void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3573 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003574 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003575 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003576 int64_t desiredPresentTime,
3577 const cached_buffer_t& uncacheBuffer) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003578 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003579
Valerie Haubc6ddb12019-03-08 11:10:15 -08003580 const int64_t postTime = systemTime();
3581
Robert Carr14167e02019-02-13 13:50:55 -08003582 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3583
Mathias Agopian698c0872011-06-28 19:09:31 -07003584 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585
chaviwca27f252018-02-06 16:46:39 -08003586 if (containsAnyInvalidClientState(states)) {
3587 return;
3588 }
3589
Marissa Wall713b63f2018-10-17 15:42:43 -07003590 // If its TransactionQueue already has a pending TransactionState or if it is pending
3591 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003592 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003593 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall78b72202019-03-15 14:58:34 -07003594 uncacheBuffer, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003595 setTransactionFlags(eTransactionNeeded);
3596 return;
3597 }
3598
Valerie Haubc6ddb12019-03-08 11:10:15 -08003599 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall78b72202019-03-15 14:58:34 -07003600 uncacheBuffer, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003601}
3602
3603void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003604 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003605 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003606 const int64_t desiredPresentTime,
3607 const cached_buffer_t& uncacheBuffer,
3608 const int64_t postTime, bool privileged,
3609 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003610 uint32_t transactionFlags = 0;
3611
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003612 if (flags & eAnimation) {
3613 // For window updates that are part of an animation we must wait for
3614 // previous animation "frames" to be handled.
3615 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003616 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003617 if (CC_UNLIKELY(err != NO_ERROR)) {
3618 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003619 // caller after a few seconds.
3620 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3621 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003622 mAnimTransactionPending = false;
3623 break;
3624 }
3625 }
3626 }
3627
chaviwca27f252018-02-06 16:46:39 -08003628 for (const DisplayState& display : displays) {
3629 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003630 }
3631
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003633 for (const ComposerState& state : states) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003634 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged);
chaviwca27f252018-02-06 16:46:39 -08003635 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003636 // If the state doesn't require a traversal and there are callbacks, send them now
3637 if (!(clientStateFlags & eTraversalNeeded)) {
3638 mTransactionCompletedThread.sendCallbacks();
3639 }
3640 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003641
chaviw273171b2018-12-26 11:46:30 -08003642 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3643
Marissa Wall78b72202019-03-15 14:58:34 -07003644 if (uncacheBuffer.token) {
3645 BufferStateLayerCache::getInstance().erase(uncacheBuffer.token, uncacheBuffer.cacheId);
3646 }
3647
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003648 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3649 // anyway. This can be used as a flush mechanism for previous async transactions.
3650 // Empty animation transaction can be used to simulate back-pressure, so also force a
3651 // transaction for empty animation transactions.
3652 if (transactionFlags == 0 &&
3653 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003654 transactionFlags = eTransactionNeeded;
3655 }
3656
Mathias Agopian386aa982011-11-07 21:58:03 -08003657 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003658 if (mInterceptor->isEnabled()) {
3659 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003660 }
Irvel468051e2016-06-13 16:44:44 -07003661
Mathias Agopian386aa982011-11-07 21:58:03 -08003662 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003663 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3664 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003665 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003666
3667 // if this is a synchronous transaction, wait for it to take effect
3668 // before returning.
3669 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003670 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003671 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003672 if (flags & eAnimation) {
3673 mAnimTransactionPending = true;
3674 }
chaviw95ef3c42019-02-14 10:55:09 -08003675
3676 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
Valerie Hau0779ded2019-03-19 12:43:04 -07003677
3678 // applyTransactionState can be called by either the main SF thread or by
3679 // another process through setTransactionState. While a given process may wish
3680 // to wait on synchronous transactions, the main SF thread should never
3681 // be blocked. Therefore, we only wait if isMainThread is false.
3682 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003683 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3684 if (CC_UNLIKELY(err != NO_ERROR)) {
3685 // just in case something goes wrong in SF, return to the
3686 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003687 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3688 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003689 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003690 break;
3691 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003692 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693 }
3694}
3695
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003696uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3697 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3698 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003699
Mathias Agopiane57f2922012-08-09 16:29:12 -07003700 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003701 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3702
3703 const uint32_t what = s.what;
3704 if (what & DisplayState::eSurfaceChanged) {
3705 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3706 state.surface = s.surface;
3707 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003708 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003709 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003710 if (what & DisplayState::eLayerStackChanged) {
3711 if (state.layerStack != s.layerStack) {
3712 state.layerStack = s.layerStack;
3713 flags |= eDisplayTransactionNeeded;
3714 }
3715 }
3716 if (what & DisplayState::eDisplayProjectionChanged) {
3717 if (state.orientation != s.orientation) {
3718 state.orientation = s.orientation;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 if (state.frame != s.frame) {
3722 state.frame = s.frame;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 if (state.viewport != s.viewport) {
3726 state.viewport = s.viewport;
3727 flags |= eDisplayTransactionNeeded;
3728 }
3729 }
3730 if (what & DisplayState::eDisplaySizeChanged) {
3731 if (state.width != s.width) {
3732 state.width = s.width;
3733 flags |= eDisplayTransactionNeeded;
3734 }
3735 if (state.height != s.height) {
3736 state.height = s.height;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 }
3740
Mathias Agopiane57f2922012-08-09 16:29:12 -07003741 return flags;
3742}
3743
Robert Carr14167e02019-02-13 13:50:55 -08003744bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003745 IPCThreadState* ipc = IPCThreadState::self();
3746 const int pid = ipc->getCallingPid();
3747 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003748 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003749 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003750 return false;
3751 }
3752 return true;
3753}
3754
Robert Carr14167e02019-02-13 13:50:55 -08003755uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003756 int64_t desiredPresentTime, int64_t postTime,
3757 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003758 const layer_state_t& s = composerState.state;
3759 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3760
Mathias Agopian13127d82013-03-05 17:47:11 -08003761 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (layer == nullptr) {
3763 return 0;
3764 }
3765
chaviw8b3871a2017-11-01 17:41:01 -07003766 uint32_t flags = 0;
3767
Garfield Tan8a3083e2018-12-03 13:21:07 -08003768 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003769 bool geometryAppliesWithResize =
3770 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003771
3772 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3773 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003774 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003775 layer->pushPendingState();
3776 }
3777
chaviw8b3871a2017-11-01 17:41:01 -07003778 if (what & layer_state_t::ePositionChanged) {
3779 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3780 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 }
3783 if (what & layer_state_t::eLayerChanged) {
3784 // NOTE: index needs to be calculated before we update the state
3785 const auto& p = layer->getParent();
3786 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003787 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003788 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003789 mCurrentState.layersSortedByZ.removeAt(idx);
3790 mCurrentState.layersSortedByZ.add(layer);
3791 // we need traversal (state changed)
3792 // AND transaction (list changed)
3793 flags |= eTransactionNeeded|eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 } else {
3796 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
3799 }
chaviw8b3871a2017-11-01 17:41:01 -07003800 }
3801 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003802 // NOTE: index needs to be calculated before we update the state
3803 const auto& p = layer->getParent();
3804 if (p == nullptr) {
3805 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3806 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3807 mCurrentState.layersSortedByZ.removeAt(idx);
3808 mCurrentState.layersSortedByZ.add(layer);
3809 // we need traversal (state changed)
3810 // AND transaction (list changed)
3811 flags |= eTransactionNeeded|eTraversalNeeded;
3812 }
3813 } else {
3814 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 }
3818 }
3819 if (what & layer_state_t::eSizeChanged) {
3820 if (layer->setSize(s.w, s.h)) {
3821 flags |= eTraversalNeeded;
3822 }
3823 }
3824 if (what & layer_state_t::eAlphaChanged) {
3825 if (layer->setAlpha(s.alpha))
3826 flags |= eTraversalNeeded;
3827 }
3828 if (what & layer_state_t::eColorChanged) {
3829 if (layer->setColor(s.color))
3830 flags |= eTraversalNeeded;
3831 }
Peiyong Lind3788632018-09-18 16:01:31 -07003832 if (what & layer_state_t::eColorTransformChanged) {
3833 if (layer->setColorTransform(s.colorTransform)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003837 if (what & layer_state_t::eBackgroundColorChanged) {
3838 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3839 flags |= eTraversalNeeded;
3840 }
3841 }
chaviw8b3871a2017-11-01 17:41:01 -07003842 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003843 // TODO: b/109894387
3844 //
3845 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3846 // rotation. To see the problem observe that if we have a square parent, and a child
3847 // of the same size, then we rotate the child 45 degrees around it's center, the child
3848 // must now be cropped to a non rectangular 8 sided region.
3849 //
3850 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3851 // private API, and the WindowManager only uses rotation in one case, which is on a top
3852 // level layer in which cropping is not an issue.
3853 //
3854 // However given that abuse of rotation matrices could lead to surfaces extending outside
3855 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3856 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3857 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003858 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003859 flags |= eTraversalNeeded;
3860 }
3861 if (what & layer_state_t::eTransparentRegionChanged) {
3862 if (layer->setTransparentRegionHint(s.transparentRegion))
3863 flags |= eTraversalNeeded;
3864 }
3865 if (what & layer_state_t::eFlagsChanged) {
3866 if (layer->setFlags(s.flags, s.mask))
3867 flags |= eTraversalNeeded;
3868 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003869 if (what & layer_state_t::eCropChanged_legacy) {
3870 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003871 flags |= eTraversalNeeded;
3872 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003873 if (what & layer_state_t::eCornerRadiusChanged) {
3874 if (layer->setCornerRadius(s.cornerRadius))
3875 flags |= eTraversalNeeded;
3876 }
chaviw8b3871a2017-11-01 17:41:01 -07003877 if (what & layer_state_t::eLayerStackChanged) {
3878 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3879 // We only allow setting layer stacks for top level layers,
3880 // everything else inherits layer stack from its parent.
3881 if (layer->hasParent()) {
3882 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3883 layer->getName().string());
3884 } else if (idx < 0) {
3885 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3886 "that also does not appear in the top level layer list. Something"
3887 " has gone wrong.", layer->getName().string());
3888 } else if (layer->setLayerStack(s.layerStack)) {
3889 mCurrentState.layersSortedByZ.removeAt(idx);
3890 mCurrentState.layersSortedByZ.add(layer);
3891 // we need traversal (state changed)
3892 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003893 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003894 }
3895 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003896 if (what & layer_state_t::eDeferTransaction_legacy) {
3897 if (s.barrierHandle_legacy != nullptr) {
3898 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3899 } else if (s.barrierGbp_legacy != nullptr) {
3900 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003901 if (authenticateSurfaceTextureLocked(gbp)) {
3902 const auto& otherLayer =
3903 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003904 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003905 } else {
3906 ALOGE("Attempt to defer transaction to to an"
3907 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003908 }
3909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 // We don't trigger a traversal here because if no other state is
3911 // changed, we don't want this to cause any more work
3912 }
3913 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003914 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003915 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003916 if (!hadParent) {
3917 mCurrentState.layersSortedByZ.remove(layer);
3918 }
chaviw8b3871a2017-11-01 17:41:01 -07003919 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 }
3922 if (what & layer_state_t::eReparentChildren) {
3923 if (layer->reparentChildren(s.reparentHandle)) {
3924 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003925 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003926 }
chaviw8b3871a2017-11-01 17:41:01 -07003927 if (what & layer_state_t::eDetachChildren) {
3928 layer->detachChildren();
3929 }
3930 if (what & layer_state_t::eOverrideScalingModeChanged) {
3931 layer->setOverrideScalingMode(s.overrideScalingMode);
3932 // We don't trigger a traversal here because if no other state is
3933 // changed, we don't want this to cause any more work
3934 }
Marissa Wall61c58622018-07-18 10:12:20 -07003935 if (what & layer_state_t::eTransformChanged) {
3936 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3937 }
3938 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3939 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3940 flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eCropChanged) {
3943 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3944 }
Marissa Wall861616d2018-10-22 12:52:23 -07003945 if (what & layer_state_t::eFrameChanged) {
3946 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3947 }
Marissa Wall61c58622018-07-18 10:12:20 -07003948 if (what & layer_state_t::eAcquireFenceChanged) {
3949 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eDataspaceChanged) {
3952 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eHdrMetadataChanged) {
3955 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3956 }
3957 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3958 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eApiChanged) {
3961 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eSidebandStreamChanged) {
3964 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3965 }
Robert Carr720e5062018-07-30 17:45:14 -07003966 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003967 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003968 layer->setInputInfo(s.inputInfo);
3969 flags |= eTraversalNeeded;
3970 } else {
3971 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3972 }
Robert Carr720e5062018-07-30 17:45:14 -07003973 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003974 if (what & layer_state_t::eMetadataChanged) {
3975 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3976 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003977 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3978 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3979 flags |= eTraversalNeeded;
3980 }
3981 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003982 std::vector<sp<CallbackHandle>> callbackHandles;
3983 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3984 mTransactionCompletedThread.run();
3985 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3986 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3987 }
3988 }
Marissa Wall78b72202019-03-15 14:58:34 -07003989 bool bufferChanged = what & layer_state_t::eBufferChanged;
3990 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3991 sp<GraphicBuffer> buffer;
3992 if (bufferChanged && cacheIdChanged) {
3993 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.cacheId,
Marissa Wall73411622019-01-25 10:45:41 -08003994 s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003995 buffer = s.buffer;
3996 } else if (cacheIdChanged) {
3997 buffer = BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3998 s.cachedBuffer.cacheId);
3999 } else if (bufferChanged) {
4000 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004001 }
Marissa Wall78b72202019-03-15 14:58:34 -07004002 if (buffer) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004003 if (layer->setBuffer(buffer)) {
4004 flags |= eTraversalNeeded;
4005 layer->setPostTime(postTime);
4006 layer->setDesiredPresentTime(desiredPresentTime);
4007 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004008 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004009 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4010 // Do not put anything that updates layer state or modifies flags after
4011 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004012 return flags;
4013}
4014
chaviw273171b2018-12-26 11:46:30 -08004015uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4016 uint32_t flags = 0;
4017 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4018 flags |= eTraversalNeeded;
4019 }
4020
chaviwa911b102019-02-14 10:18:33 -08004021 if (inputWindowCommands.syncInputWindows) {
4022 flags |= eTraversalNeeded;
4023 }
4024
Vishnu Nairec0ab382019-02-13 15:32:56 -08004025 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004026 return flags;
4027}
4028
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004029status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4030 uint32_t h, PixelFormat format, uint32_t flags,
4031 LayerMetadata metadata, sp<IBinder>* handle,
4032 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004033 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004034 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004035 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004036 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004037 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004038
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004039 status_t result = NO_ERROR;
4040
4041 sp<Layer> layer;
4042
Cody Northropbc755282017-03-31 12:00:08 -06004043 String8 uniqueName = getUniqueLayerName(name);
4044
Evan Roskya1f1e152019-01-24 16:17:46 -08004045 bool primaryDisplayOnly = false;
4046
4047 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4048 // TODO b/64227542
4049 if (metadata.has(METADATA_WINDOW_TYPE)) {
4050 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4051 if (windowType == 441731) {
4052 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4053 primaryDisplayOnly = true;
4054 }
4055 }
4056
Mathias Agopian3165cc22012-08-08 19:42:09 -07004057 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004058 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004059 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4060 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004061
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004063 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004064 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4065 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004066 break;
chaviw13fdc492017-06-27 12:40:18 -07004067 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004068 // check if buffer size is set for color layer.
4069 if (w > 0 || h > 0) {
4070 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4071 int(w), int(h));
4072 return BAD_VALUE;
4073 }
4074
Evan Roskya1f1e152019-01-24 16:17:46 -08004075 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4076 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004078 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004079 // check if buffer size is set for container layer.
4080 if (w > 0 || h > 0) {
4081 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4082 int(w), int(h));
4083 return BAD_VALUE;
4084 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004085 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4086 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004087 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004088 default:
4089 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 break;
4091 }
4092
Dan Stoza7d89d062015-04-30 13:29:25 -07004093 if (result != NO_ERROR) {
4094 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004095 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004096
Evan Roskya1f1e152019-01-24 16:17:46 -08004097 if (primaryDisplayOnly) {
4098 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004099 }
4100
Robert Carrb89ea9d2018-12-10 13:01:14 -08004101 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4102 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4103 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004104 if (result != NO_ERROR) {
4105 return result;
4106 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004107 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004108
4109 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004110 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111}
4112
Cody Northropbc755282017-03-31 12:00:08 -06004113String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4114{
4115 bool matchFound = true;
4116 uint32_t dupeCounter = 0;
4117
4118 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4119 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4120
Dan Stoza436ccf32018-06-21 12:10:12 -07004121 // Grab the state lock since we're accessing mCurrentState
4122 Mutex::Autolock lock(mStateLock);
4123
Cody Northropbc755282017-03-31 12:00:08 -06004124 // Loop over layers until we're sure there is no matching name
4125 while (matchFound) {
4126 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004127 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004128 if (layer->getName() == uniqueName) {
4129 matchFound = true;
4130 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4131 }
4132 });
4133 }
4134
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004135 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4136 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004137
4138 return uniqueName;
4139}
4140
Marissa Wallfd668622018-05-10 10:21:13 -07004141status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4142 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004143 LayerMetadata metadata, PixelFormat& format,
4144 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004145 sp<IGraphicBufferProducer>* gbp,
4146 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004148 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 case PIXEL_FORMAT_TRANSPARENT:
4150 case PIXEL_FORMAT_TRANSLUCENT:
4151 format = PIXEL_FORMAT_RGBA_8888;
4152 break;
4153 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004154 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 break;
4156 }
4157
Evan Roskya1f1e152019-01-24 16:17:46 -08004158 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4159 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004160 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004162 *handle = layer->getHandle();
4163 *gbp = layer->getProducer();
4164 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004165 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166
Marissa Wallfd668622018-05-10 10:21:13 -07004167 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004168 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169}
4170
Marissa Wall61c58622018-07-18 10:12:20 -07004171status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4172 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004173 LayerMetadata metadata, sp<IBinder>* handle,
4174 sp<Layer>* outLayer) {
4175 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4176 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004177 *handle = layer->getHandle();
4178 *outLayer = layer;
4179
4180 return NO_ERROR;
4181}
4182
Evan Roskya1f1e152019-01-24 16:17:46 -08004183status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4184 uint32_t h, uint32_t flags, LayerMetadata metadata,
4185 sp<IBinder>* handle, sp<Layer>* outLayer) {
4186 *outLayer = getFactory().createColorLayer(
4187 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004189 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004190}
4191
Evan Roskya1f1e152019-01-24 16:17:46 -08004192status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4193 uint32_t w, uint32_t h, uint32_t flags,
4194 LayerMetadata metadata, sp<IBinder>* handle,
4195 sp<Layer>* outLayer) {
4196 *outLayer = getFactory().createContainerLayer(
4197 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004198 *handle = (*outLayer)->getHandle();
4199 return NO_ERROR;
4200}
4201
4202
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004203void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004204 mLayersPendingRemoval.add(layer);
4205 mLayersRemoved = true;
4206 setTransactionFlags(eTransactionNeeded);
4207}
4208
Robert Carr695d5282018-12-18 15:27:58 -08004209void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004210{
Robert Carr2e102c92018-10-23 12:11:15 -07004211 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004212 // If a layer has a parent, we allow it to out-live it's handle
4213 // with the idea that the parent holds a reference and will eventually
4214 // be cleaned up. However no one cleans up the top-level so we do so
4215 // here.
4216 if (layer->getParent() == nullptr) {
4217 mCurrentState.layersSortedByZ.remove(layer);
4218 }
4219 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004220 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004221}
4222
Mathias Agopianb60314a2012-04-10 22:09:54 -07004223// ---------------------------------------------------------------------------
4224
Andy McFadden13a082e2012-08-24 10:16:42 -07004225void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 const auto display = getDefaultDisplayDeviceLocked();
4227 if (!display) return;
4228
4229 const sp<IBinder> token = display->getDisplayToken().promote();
4230 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004231
Jesse Hall01e29052013-02-19 16:13:35 -08004232 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004233 Vector<ComposerState> state;
4234 Vector<DisplayState> displays;
4235 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004236 d.what = DisplayState::eDisplayProjectionChanged |
4237 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004239 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004240 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004241 d.frame.makeInvalid();
4242 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004243 d.width = 0;
4244 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004245 displays.add(d);
Marissa Wall78b72202019-03-15 14:58:34 -07004246 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004247
Dominik Laskowskie9774092018-12-11 10:04:24 -08004248 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004249
Dominik Laskowski83b88212018-12-11 13:34:06 -08004250 const nsecs_t vsyncPeriod = getVsyncPeriod();
4251 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004252
Brian Andersond0010582017-03-07 13:20:31 -08004253 // Use phase of 0 since phase is not known.
4254 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004256 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004257}
4258
4259void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004260 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004261 postMessageAsync(
4262 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004263}
4264
Dominik Laskowskie9774092018-12-11 10:04:24 -08004265void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004266 if (display->isVirtual()) {
4267 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004268 return;
4269 }
4270
Dominik Laskowski075d3172018-05-24 15:50:06 -07004271 const auto displayId = display->getId();
4272 LOG_ALWAYS_FATAL_IF(!displayId);
4273
Dominik Laskowski34157762018-10-31 13:07:19 -07004274 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275
4276 int currentMode = display->getPowerMode();
4277 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004278 return;
4279 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 display->setPowerMode(mode);
4282
Lloyd Pique4dccc412018-01-22 17:21:36 -08004283 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004285 }
4286
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004287 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004288 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004289 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004291 mScheduler->onScreenAcquired(mAppConnectionHandle);
4292 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004293 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004294
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004295 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004296 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004297 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004298
4299 struct sched_param param = {0};
4300 param.sched_priority = 1;
4301 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4302 ALOGW("Couldn't set SCHED_FIFO on display on");
4303 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004305 // Turn off the display
4306 struct sched_param param = {0};
4307 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4308 ALOGW("Couldn't set SCHED_OTHER on display off");
4309 }
4310
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004312 mScheduler->disableHardwareVsync(true);
4313 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004314 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004315
Dominik Laskowski075d3172018-05-24 15:50:06 -07004316 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004317 mVisibleRegionsDirty = true;
4318 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004319 } else if (mode == HWC_POWER_MODE_DOZE ||
4320 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004321 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004323 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004324 mScheduler->onScreenAcquired(mAppConnectionHandle);
4325 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004326 }
4327 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4328 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004330 mScheduler->disableHardwareVsync(true);
4331 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004332 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004333 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004334 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004335 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004336 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004337 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004339 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004340 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004341 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004342 // Update refresh rate stats.
4343 mRefreshRateStats->setPowerMode(mode);
4344 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004345 }
4346
Dominik Laskowski34157762018-10-31 13:07:19 -07004347 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004348}
4349
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004350void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004351 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004352 const auto display = getDisplayDevice(displayToken);
4353 if (!display) {
4354 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4355 displayToken.get());
4356 } else if (display->isVirtual()) {
4357 ALOGW("Attempt to set power mode %d for virtual display", mode);
4358 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004359 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004360 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004361 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004362}
4363
4364// ---------------------------------------------------------------------------
4365
Dominik Laskowskic2867142019-01-21 11:33:38 -08004366status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4367 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004368 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004369
Mathias Agopianbd115332013-04-18 16:41:04 -07004370 IPCThreadState* ipc = IPCThreadState::self();
4371 const int pid = ipc->getCallingPid();
4372 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004373
Mathias Agopianbd115332013-04-18 16:41:04 -07004374 if ((uid != AID_SHELL) &&
4375 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4377 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004379 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004380 // (this would indicate SF is stuck, but we want to be able to
4381 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004382 status_t err = mStateLock.timedLock(s2ns(1));
4383 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004384 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result,
4386 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4387 "(no locks held)\n",
4388 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004389 }
4390
Dominik Laskowskic2867142019-01-21 11:33:38 -08004391 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393 static const std::unordered_map<std::string, Dumper> dumpers = {
4394 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4395 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4396 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004397 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004398 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004399 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4401 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4403 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4404 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4405 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4406 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4407 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004408 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4410 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004411
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004413
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4415 (it->second)(args, asProto, result);
4416 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004417 if (asProto) {
4418 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4419 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4420 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004421 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004422 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004423 }
4424
Mathias Agopian9795c422009-08-26 16:36:26 -07004425 if (locked) {
4426 mStateLock.unlock();
4427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004428 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004429 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 return NO_ERROR;
4431}
4432
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004433status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4434 if (asProto && mTracing.isEnabled()) {
4435 mTracing.writeToFileAsync();
4436 }
4437
4438 return doDump(fd, DumpArgs(), asProto);
4439}
4440
Dominik Laskowskic2867142019-01-21 11:33:38 -08004441void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 mCurrentState.traverseInZOrder(
4443 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004444}
4445
Dominik Laskowskic2867142019-01-21 11:33:38 -08004446void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004447 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004448
Dominik Laskowskic2867142019-01-21 11:33:38 -08004449 if (args.size() > 1) {
4450 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004451 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004452 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004453 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004454 }
Robert Carr2047fae2016-11-28 14:09:09 -08004455 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004456 } else {
4457 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458 }
4459}
4460
Dominik Laskowskic2867142019-01-21 11:33:38 -08004461void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004462 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004464 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004465 }
Robert Carr2047fae2016-11-28 14:09:09 -08004466 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004467
Svetoslavd85084b2014-03-20 10:28:31 -07004468 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004469}
4470
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4472 mTimeStats->parseArgs(asProto, args, result);
4473}
4474
Jamie Gennis6547ff42013-07-16 20:12:42 -07004475// This should only be called from the main thread. Otherwise it would need
4476// the lock and should use mCurrentState rather than mDrawingState.
4477void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004478 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004479 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004480 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004481
4482 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4483}
4484
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004486 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004487
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004488 if (isLayerTripleBufferingDisabled())
4489 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004490
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4492 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4493 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4494 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4495 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4496 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004498}
4499
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004500void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004501 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004502 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004503 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004504 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004505
Ady Abraham97d04232019-03-05 19:48:12 -08004506 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004507 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4508 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004509 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004510}
4511
Yiwei Zhang5434a782018-12-05 18:06:32 -08004512void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4513 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004514 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4515 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004516 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004517 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004519 }
David Sodman4a36e932017-11-07 14:29:47 -08004520 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004521 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004522 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4524 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004525}
4526
Dan Stozae77c7662016-05-13 11:37:28 -07004527void SurfaceFlinger::recordBufferingStats(const char* layerName,
4528 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004529 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4530 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004531 for (const auto& segment : history) {
4532 if (!segment.usedThirdBuffer) {
4533 stats.twoBufferTime += segment.totalTime;
4534 }
4535 if (segment.occupancyAverage < 1.0f) {
4536 stats.doubleBufferedTime += segment.totalTime;
4537 } else if (segment.occupancyAverage < 2.0f) {
4538 stats.tripleBufferedTime += segment.totalTime;
4539 }
4540 ++stats.numSegments;
4541 stats.totalTime += segment.totalTime;
4542 }
4543}
4544
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4546 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004547
4548 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4549 const size_t count = currentLayers.size();
4550 for (size_t i=0 ; i<count ; i++) {
4551 currentLayers[i]->dumpFrameEvents(result);
4552 }
4553}
4554
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004556 result.append("Buffering stats:\n");
4557 result.append(" [Layer name] <Active time> <Two buffer> "
4558 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004559 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004560 typedef std::tuple<std::string, float, float, float> BufferTuple;
4561 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004562 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004563 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004564 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004565 if (stats.numSegments == 0) {
4566 continue;
4567 }
4568 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4569 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4570 stats.totalTime;
4571 float doubleBufferRatio = static_cast<float>(
4572 stats.doubleBufferedTime) / stats.totalTime;
4573 float tripleBufferRatio = static_cast<float>(
4574 stats.tripleBufferedTime) / stats.totalTime;
4575 sorted.insert({activeTime, {name, twoBufferRatio,
4576 doubleBufferRatio, tripleBufferRatio}});
4577 }
4578 for (const auto& sortedPair : sorted) {
4579 float activeTime = sortedPair.first;
4580 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4582 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004583 }
4584 result.append("\n");
4585}
4586
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004588 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004589 const auto displayId = display->getId();
4590 if (!displayId) {
4591 continue;
4592 }
4593 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004594 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004595 continue;
4596 }
4597
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result,
4599 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4600 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 uint8_t port;
4602 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004603 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 result.append("no identification data\n");
4605 continue;
4606 }
4607
4608 if (!isEdid(data)) {
4609 result.append("unknown identification data: ");
4610 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004612 }
4613 result.append("\n");
4614 continue;
4615 }
4616
4617 const auto edid = parseEdid(data);
4618 if (!edid) {
4619 result.append("invalid EDID: ");
4620 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004622 }
4623 result.append("\n");
4624 continue;
4625 }
4626
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628 result.append(edid->displayName.data(), edid->displayName.length());
4629 result.append("\"\n");
4630 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004631}
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4634 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4635 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4636 StringAppendF(&result, "DisplayColorSetting: %s\n",
4637 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004638
4639 // TODO: print out if wide-color mode is active or not
4640
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004641 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004642 const auto displayId = display->getId();
4643 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004644 continue;
4645 }
4646
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004648 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004649 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004651 }
4652
Lloyd Pique32cbe282018-10-19 13:09:22 -07004653 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 StringAppendF(&result, " Current color mode: %s (%d)\n",
4655 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004656 }
4657 result.append("\n");
4658}
4659
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004660LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004661 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004662 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4663 const State& state = useDrawing ? mDrawingState : mCurrentState;
4664 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004665 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004666 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004667 });
4668
4669 return layersProto;
4670}
4671
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004672LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4673 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004674 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004675
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004676 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004677 resolution->set_w(displayDevice->getWidth());
4678 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004679
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004680 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004681 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004682
Lloyd Pique32cbe282018-10-19 13:09:22 -07004683 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4684 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4685 layersProto.set_global_transform(displayState.orientation);
4686
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004687 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004690 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004691 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004692 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004693 }
4694 });
4695
4696 return layersProto;
4697}
4698
Dominik Laskowskic2867142019-01-21 11:33:38 -08004699void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4700 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 Colorizer colorizer(colorize);
4702
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703 // figure out if we're stuck somewhere
4704 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004705 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004706 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4707
4708 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004709 * Dump library configuration.
4710 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711
4712 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004713 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004715 appendSfConfigString(result);
4716 appendUiConfigString(result);
4717 appendGuiConfigString(result);
4718 result.append("\n");
4719
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004720 result.append("\nDisplay identification data:\n");
4721 dumpDisplayIdentificationData(result);
4722
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004723 result.append("\nWide-Color information:\n");
4724 dumpWideColorInfo(result);
4725
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004726 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004727 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004728 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004729 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004730 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004731
Andy McFadden41d67d72014-04-25 16:58:34 -07004732 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004733 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004734 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004735 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004736 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004737
Dan Stozab90cf072015-03-05 11:05:59 -08004738 dumpStaticScreenStats(result);
4739 result.append("\n");
4740
Alec Mouri40189b02019-03-05 15:07:54 -08004741 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4742 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4743 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004744
Dan Stozae77c7662016-05-13 11:37:28 -07004745 dumpBufferingStats(result);
4746
Andy McFadden4803b742012-09-24 19:07:20 -07004747 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004748 * Dump the visible layer list
4749 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4752 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4753 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004755
Chia-I Wu2f884132018-09-13 15:17:58 -07004756 {
4757 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4758 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004759 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004760 result.append("\n");
4761 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762
Lloyd Pique207def92019-02-28 16:09:52 -08004763 {
4764 StringAppendF(&result, "Composition layers\n");
4765 mDrawingState.traverseInZOrder([&](Layer* layer) {
4766 auto compositionLayer = layer->getCompositionLayer();
4767 if (compositionLayer) compositionLayer->dump(result);
4768 });
4769 }
4770
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004772 * Dump Display state
4773 */
4774
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004778 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004779 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004780 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004781 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004782
4783 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004784 * Dump SurfaceFlinger global state
4785 */
4786
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004788 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004790
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004791 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004792
Dominik Laskowski075d3172018-05-24 15:50:06 -07004793 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004794 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4795 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4797 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004798 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799 StringAppendF(&result,
4800 " transaction-flags : %08x\n"
4801 " gpu_to_cpu_unsupported : %d\n",
4802 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004803
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004804 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004805 displayId && getHwComposer().isConnected(*displayId)) {
4806 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004807 StringAppendF(&result,
4808 " refresh-rate : %f fps\n"
4809 " x-dpi : %f\n"
4810 " y-dpi : %f\n",
4811 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4812 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004813 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816
Dan Stozae22aec72016-08-01 13:20:59 -07004817 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004818 * Tracing state
4819 */
4820 mTracing.dump(result);
4821 result.append("\n");
4822
4823 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004824 * HWC layer minidump
4825 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004826 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004827 const auto displayId = display->getId();
4828 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004829 continue;
4830 }
4831
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004833 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004834 const sp<DisplayDevice> displayDevice = display;
4835 mCurrentState.traverseInZOrder(
4836 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004837 result.append("\n");
4838 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839
4840 /*
4841 * Dump HWComposer state
4842 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004843 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004844 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004847 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004848 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
4850 /*
4851 * Dump gralloc state
4852 */
4853 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4854 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004855
4856 /*
4857 * Dump VrFlinger state if in use.
4858 */
4859 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4860 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004862 result.append("\n");
4863 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004864
4865 /**
4866 * Scheduler dump state.
4867 */
Ana Krulecc2870422019-01-29 19:00:58 -08004868 result.append("\nScheduler state:\n");
4869 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004870 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004871 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004872}
4873
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004875 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004876 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004877 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004878 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004879 }
4880 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004881
Dominik Laskowski34157762018-10-31 13:07:19 -07004882 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004883 static const Vector<sp<Layer>> empty;
4884 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004885}
4886
Chia-I Wu28f320b2018-05-03 11:02:56 -07004887void SurfaceFlinger::updateColorMatrixLocked() {
4888 mat4 colorMatrix;
4889 if (mGlobalSaturationFactor != 1.0f) {
4890 // Rec.709 luma coefficients
4891 float3 luminance{0.213f, 0.715f, 0.072f};
4892 luminance *= 1.0f - mGlobalSaturationFactor;
4893 mat4 saturationMatrix = mat4(
4894 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4895 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4896 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4897 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4898 );
4899 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4900 } else {
4901 colorMatrix = mClientColorMatrix * mDaltonizer();
4902 }
4903
4904 if (mCurrentState.colorMatrix != colorMatrix) {
4905 mCurrentState.colorMatrix = colorMatrix;
4906 mCurrentState.colorMatrixChanged = true;
4907 setTransactionFlags(eTransactionNeeded);
4908 }
4909}
4910
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004911status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912#pragma clang diagnostic push
4913#pragma clang diagnostic error "-Wswitch-enum"
4914 switch (static_cast<ISurfaceComposerTag>(code)) {
4915 // These methods should at minimum make sure that the client requested
4916 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004917 case BOOT_FINISHED:
4918 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 case CREATE_DISPLAY:
4920 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004921 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 case GET_ANIMATION_FRAME_STATS:
4923 case GET_HDR_CAPABILITIES:
4924 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004925 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004926 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004928 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004929 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004930 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004931 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4932 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004933 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4934 IPCThreadState* ipc = IPCThreadState::self();
4935 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4936 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004937 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 }
Robert Carr1db73f62016-12-21 12:58:51 -08004939 return OK;
4940 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004941 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004942 IPCThreadState* ipc = IPCThreadState::self();
4943 const int pid = ipc->getCallingPid();
4944 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4946 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004947 return PERMISSION_DENIED;
4948 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004950 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 // Used by apps to hook Choreographer to SurfaceFlinger.
4952 case CREATE_DISPLAY_EVENT_CONNECTION:
4953 // The following calls are currently used by clients that do not
4954 // request necessary permissions. However, they do not expose any secret
4955 // information, so it is OK to pass them.
4956 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004957 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004958 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004959 case GET_PHYSICAL_DISPLAY_IDS:
4960 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004961 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004962 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004963 case GET_DISPLAY_CONFIGS:
4964 case GET_DISPLAY_STATS:
4965 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4966 // Calling setTransactionState is safe, because you need to have been
4967 // granted a reference to Client* and Handle* to do anything with it.
4968 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004969 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004970 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004971 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004972 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004973 case IS_WIDE_COLOR_DISPLAY:
4974 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4975 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 return OK;
4977 }
4978 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004979 case CAPTURE_SCREEN:
4980 case ADD_REGION_SAMPLING_LISTENER:
4981 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004982 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004983 IPCThreadState* ipc = IPCThreadState::self();
4984 const int pid = ipc->getCallingPid();
4985 const int uid = ipc->getCallingUid();
4986 if ((uid != AID_GRAPHICS) &&
4987 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4988 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4989 return PERMISSION_DENIED;
4990 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 return OK;
4992 }
4993 // The following codes are deprecated and should never be allowed to access SF.
4994 case CONNECT_DISPLAY_UNUSED:
4995 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4996 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4997 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004998 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000
5001 // These codes are used for the IBinder protocol to either interrogate the recipient
5002 // side of the transaction for its canonical interface descriptor or to dump its state.
5003 // We let them pass by default.
5004 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5005 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5006 code == IBinder::SYSPROPS_TRANSACTION) {
5007 return OK;
5008 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005009 // Numbers from 1000 to 1032 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005011 if (code >= 1000 && code <= 1032) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5013 return OK;
5014 }
5015 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5016 return PERMISSION_DENIED;
5017#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005018}
5019
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5021 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005022 status_t credentialCheck = CheckTransactCodeCredentials(code);
5023 if (credentialCheck != OK) {
5024 return credentialCheck;
5025 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005026
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005027 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5028 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005029 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005030 IPCThreadState* ipc = IPCThreadState::self();
5031 const int uid = ipc->getCallingUid();
5032 if (CC_UNLIKELY(uid != AID_SYSTEM
5033 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005034 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005035 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005036 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 return PERMISSION_DENIED;
5038 }
5039 int n;
5040 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005041 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005042 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 return NO_ERROR;
5044 case 1002: // SHOW_UPDATES
5045 n = data.readInt32();
5046 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005047 invalidateHwcGeometry();
5048 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005051 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005052 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005054 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005055 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005056 setTransactionFlags(
5057 eTransactionNeeded|
5058 eDisplayTransactionNeeded|
5059 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005060 return NO_ERROR;
5061 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005062 case 1006:{ // send empty update
5063 signalRefresh();
5064 return NO_ERROR;
5065 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005066 case 1008: // toggle use of hw composer
5067 n = data.readInt32();
5068 mDebugDisableHWC = n ? 1 : 0;
5069 invalidateHwcGeometry();
5070 repaintEverything();
5071 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005072 case 1009: // toggle use of transform hint
5073 n = data.readInt32();
5074 mDebugDisableTransformHint = n ? 1 : 0;
5075 invalidateHwcGeometry();
5076 repaintEverything();
5077 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005078 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005079 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005080 reply->writeInt32(0);
5081 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005082 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005083 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 return NO_ERROR;
5085 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005086 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005087 if (!display) {
5088 return NAME_NOT_FOUND;
5089 }
5090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005092 return NO_ERROR;
5093 }
5094 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005096 // daltonize
5097 n = data.readInt32();
5098 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005099 case 1:
5100 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5101 break;
5102 case 2:
5103 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5104 break;
5105 case 3:
5106 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5107 break;
5108 default:
5109 mDaltonizer.setType(ColorBlindnessType::None);
5110 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005111 }
5112 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005113 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005114 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005115 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005116 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005117
5118 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005119 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005121 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005122 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005123 // apply a color matrix
5124 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005125 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005126 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005127 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005128 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005129 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005130 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005131 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005132 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005133 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005134 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005135
5136 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5137 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005138 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005139 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5140 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5141 }
5142
Chia-I Wu28f320b2018-05-03 11:02:56 -07005143 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005144 return NO_ERROR;
5145 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005146 // This is an experimental interface
5147 // Needs to be shifted to proper binder interface when we productize
5148 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005149 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005150 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005151 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005152 return NO_ERROR;
5153 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005154 case 1017: {
5155 n = data.readInt32();
5156 mForceFullDamage = static_cast<bool>(n);
5157 return NO_ERROR;
5158 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005159 case 1018: { // Modify Choreographer's phase offset
5160 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005161 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005162 return NO_ERROR;
5163 }
5164 case 1019: { // Modify SurfaceFlinger's phase offset
5165 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005166 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005167 return NO_ERROR;
5168 }
Irvel468051e2016-06-13 16:44:44 -07005169 case 1020: { // Layer updates interceptor
5170 n = data.readInt32();
5171 if (n) {
5172 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005173 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005174 }
5175 else{
5176 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005177 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005178 }
5179 return NO_ERROR;
5180 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005181 case 1021: { // Disable HWC virtual displays
5182 n = data.readInt32();
5183 mUseHwcVirtualDisplays = !n;
5184 return NO_ERROR;
5185 }
Romain Guy0147a172017-06-01 13:53:56 -07005186 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005187 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005188 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005189
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005191 return NO_ERROR;
5192 }
Romain Guy54f154a2017-10-24 21:40:32 +01005193 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005194 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005195 invalidateHwcGeometry();
5196 repaintEverything();
5197 return NO_ERROR;
5198 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005199 // Deprecate, use 1030 to check whether the device is color managed.
5200 case 1024: {
5201 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005202 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005203 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005204 n = data.readInt32();
5205 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005206 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005207 Mutex::Autolock lock(mStateLock);
5208 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005209 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005210 reply->writeInt32(NO_ERROR);
5211 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005212 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005213 bool writeFile = false;
5214 {
5215 Mutex::Autolock lock(mStateLock);
5216 mTracingEnabledChanged = true;
5217 writeFile = mTracing.disable();
5218 }
5219
5220 if (writeFile) {
5221 reply->writeInt32(mTracing.writeToFile());
5222 } else {
5223 reply->writeInt32(NO_ERROR);
5224 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005225 }
5226 return NO_ERROR;
5227 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005228 case 1026: { // Get layer tracing status
5229 reply->writeBool(mTracing.isEnabled());
5230 return NO_ERROR;
5231 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005232 // Is a DisplayColorSetting supported?
5233 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005234 const auto display = getDefaultDisplayDevice();
5235 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005236 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005237 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005238
5239 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5240 switch (setting) {
5241 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005242 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005243 break;
5244 case DisplayColorSetting::UNMANAGED:
5245 reply->writeBool(true);
5246 break;
5247 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005248 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005249 break;
5250 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005251 reply->writeBool(
5252 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005253 break;
5254 }
5255 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005256 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005257 // Is VrFlinger active?
5258 case 1028: {
5259 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005260 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005261 return NO_ERROR;
5262 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005263 // Set buffer size for SF tracing (value in KB)
5264 case 1029: {
5265 n = data.readInt32();
5266 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5267 ALOGW("Invalid buffer size: %d KB", n);
5268 reply->writeInt32(BAD_VALUE);
5269 return BAD_VALUE;
5270 }
5271
5272 ALOGD("Updating trace buffer to %d KB", n);
5273 mTracing.setBufferSize(n * 1024);
5274 reply->writeInt32(NO_ERROR);
5275 return NO_ERROR;
5276 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005277 // Is device color managed?
5278 case 1030: {
5279 reply->writeBool(useColorManagement);
5280 return NO_ERROR;
5281 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005282 // Override default composition data space
5283 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5284 // && adb shell stop zygote && adb shell start zygote
5285 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5286 // adb shell stop zygote && adb shell start zygote
5287 case 1031: {
5288 Mutex::Autolock _l(mStateLock);
5289 n = data.readInt32();
5290 if (n) {
5291 n = data.readInt32();
5292 if (n) {
5293 Dataspace dataspace = static_cast<Dataspace>(n);
5294 if (!validateCompositionDataspace(dataspace)) {
5295 return BAD_VALUE;
5296 }
5297 mDefaultCompositionDataspace = dataspace;
5298 }
5299 n = data.readInt32();
5300 if (n) {
5301 Dataspace dataspace = static_cast<Dataspace>(n);
5302 if (!validateCompositionDataspace(dataspace)) {
5303 return BAD_VALUE;
5304 }
5305 mWideColorGamutCompositionDataspace = dataspace;
5306 }
5307 } else {
5308 // restore composition data space.
5309 mDefaultCompositionDataspace = defaultCompositionDataspace;
5310 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5311 }
5312 return NO_ERROR;
5313 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005314 case 1032: {
5315 n = data.readInt32();
5316 mDebugEnableProtectedContent = n;
5317 return NO_ERROR;
5318 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 }
5320 }
5321 return err;
5322}
5323
Steven Thomas6d8110b2017-08-31 18:24:21 -07005324void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005325 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005326 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005327}
5328
Ana Krulec7d1d6832018-12-27 11:10:09 -08005329void SurfaceFlinger::repaintEverythingForHWC() {
5330 mRepaintEverything = true;
5331 mEventQueue->invalidateForHWC();
5332}
5333
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5335class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005336public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005337 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5338 ~WindowDisconnector() {
5339 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005340 }
5341
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005342private:
5343 ANativeWindow* mWindow;
5344 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005345};
5346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005347status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005348 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5349 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005350 uint32_t reqWidth, uint32_t reqHeight,
5351 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005352 ISurfaceComposer::Rotation rotation,
5353 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005354 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005355
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005356 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005357
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005358 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 sp<DisplayDevice> display;
5361 {
5362 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005363
Chia-I Wu20261cb2018-08-23 12:55:44 -07005364 display = getDisplayDeviceLocked(displayToken);
5365 if (!display) return BAD_VALUE;
5366
Chia-I Wucb023152018-08-28 12:57:23 -07005367 // set the requested width/height to the logical display viewport size
5368 // by default
5369 if (reqWidth == 0 || reqHeight == 0) {
5370 reqWidth = uint32_t(display->getViewport().width());
5371 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005372 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005373 }
5374
Peiyong Lin0e003c92018-09-17 11:09:51 -07005375 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005376 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005377
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005378 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5379 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005380 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5381 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005382}
5383
5384status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005385 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5386 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005387 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005388 ATRACE_CALL();
5389
5390 class LayerRenderArea : public RenderArea {
5391 public:
Robert Carr578038f2018-03-09 12:25:24 -08005392 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005393 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5394 bool childrenOnly)
5395 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005396 mLayer(layer),
5397 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005398 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005399 mFlinger(flinger),
5400 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005401 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005402 Rect getBounds() const override {
5403 const Layer::State& layerState(mLayer->getDrawingState());
5404 return mLayer->getBufferSize(layerState);
5405 }
Marissa Wall61c58622018-07-18 10:12:20 -07005406 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005407 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005408 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005409 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005410 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005411 }
chaviwa76b2712017-09-20 12:02:26 -07005412 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005413 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005414 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005415 Rect getSourceCrop() const override {
5416 if (mCrop.isEmpty()) {
5417 return getBounds();
5418 } else {
5419 return mCrop;
5420 }
5421 }
Robert Carr578038f2018-03-09 12:25:24 -08005422 class ReparentForDrawing {
5423 public:
5424 const sp<Layer>& oldParent;
5425 const sp<Layer>& newParent;
5426
Vishnu Nair4351ad52019-02-11 14:13:02 -08005427 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5428 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005429 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005430 // Compute and cache the bounds for the new parent layer.
5431 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005432 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005433 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005434 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005435 };
5436
5437 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005438 const Rect sourceCrop = getSourceCrop();
5439 // no need to check rotation because there is none
5440 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5441 sourceCrop.height() != getReqHeight();
5442
Robert Carr578038f2018-03-09 12:25:24 -08005443 if (!mChildrenOnly) {
5444 mTransform = mLayer->getTransform().inverse();
5445 drawLayers();
5446 } else {
5447 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005448 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005449 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005450 bounds.getWidth(), bounds.getHeight(), 0,
5451 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005452
Vishnu Nair4351ad52019-02-11 14:13:02 -08005453 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005454 drawLayers();
5455 }
5456 }
chaviwa76b2712017-09-20 12:02:26 -07005457
chaviwa76b2712017-09-20 12:02:26 -07005458 private:
chaviw7206d492017-11-10 16:16:12 -08005459 const sp<Layer> mLayer;
5460 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005461
5462 // In the "childrenOnly" case we reparent the children to a screenshot
5463 // layer which has no properties set and which does not draw.
5464 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005465 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005466 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005467
5468 SurfaceFlinger* mFlinger;
5469 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005470 };
5471
5472 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5473 auto parent = layerHandle->owner.promote();
5474
Robert Carr2e102c92018-10-23 12:11:15 -07005475 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005476 ALOGE("captureLayers called with a removed parent");
5477 return NAME_NOT_FOUND;
5478 }
5479
Robert Carr578038f2018-03-09 12:25:24 -08005480 const int uid = IPCThreadState::self()->getCallingUid();
5481 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005482 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005483 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5484 return PERMISSION_DENIED;
5485 }
5486
chaviw7206d492017-11-10 16:16:12 -08005487 Rect crop(sourceCrop);
5488 if (sourceCrop.width() <= 0) {
5489 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005490 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005491 }
5492
5493 if (sourceCrop.height() <= 0) {
5494 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005495 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005496 }
5497
5498 int32_t reqWidth = crop.width() * frameScale;
5499 int32_t reqHeight = crop.height() * frameScale;
5500
Chia-I Wu20261cb2018-08-23 12:55:44 -07005501 // really small crop or frameScale
5502 if (reqWidth <= 0) {
5503 reqWidth = 1;
5504 }
5505 if (reqHeight <= 0) {
5506 reqHeight = 1;
5507 }
5508
Peiyong Lin0e003c92018-09-17 11:09:51 -07005509 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005510
Robert Carr578038f2018-03-09 12:25:24 -08005511 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005512 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5513 if (!layer->isVisible()) {
5514 return;
Robert Carr578038f2018-03-09 12:25:24 -08005515 } else if (childrenOnly && layer == parent.get()) {
5516 return;
chaviwa76b2712017-09-20 12:02:26 -07005517 }
5518 visitor(layer);
5519 });
5520 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005521 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005522}
5523
5524status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5525 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005526 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005527 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005528 bool useIdentityTransform) {
5529 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005530
Peiyong Lin0e003c92018-09-17 11:09:51 -07005531 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005532 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5533 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005534 *outBuffer =
5535 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5536 static_cast<android_pixel_format>(reqPixelFormat), 1,
5537 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005539 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005540}
5541
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005542status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5543 TraverseLayersFunction traverseLayers,
5544 const sp<GraphicBuffer>& buffer,
5545 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005546 // This mutex protects syncFd and captureResult for communication of the return values from the
5547 // main thread back to this Binder thread
5548 std::mutex captureMutex;
5549 std::condition_variable captureCondition;
5550 std::unique_lock<std::mutex> captureLock(captureMutex);
5551 int syncFd = -1;
5552 std::optional<status_t> captureResult;
5553
Robert Carr03480e22018-01-04 16:02:06 -08005554 const int uid = IPCThreadState::self()->getCallingUid();
5555 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5556
Dominik Laskowski8c001672018-05-30 16:52:06 -07005557 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005558 // If there is a refresh pending, bug out early and tell the binder thread to try again
5559 // after the refresh.
5560 if (mRefreshPending) {
5561 ATRACE_NAME("Skipping screenshot for now");
5562 std::unique_lock<std::mutex> captureLock(captureMutex);
5563 captureResult = std::make_optional<status_t>(EAGAIN);
5564 captureCondition.notify_one();
5565 return;
5566 }
5567
5568 status_t result = NO_ERROR;
5569 int fd = -1;
5570 {
5571 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005572 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005573 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005574 useIdentityTransform, forSystem, &fd);
5575 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005576 }
5577
5578 {
5579 std::unique_lock<std::mutex> captureLock(captureMutex);
5580 syncFd = fd;
5581 captureResult = std::make_optional<status_t>(result);
5582 captureCondition.notify_one();
5583 }
5584 });
5585
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005586 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005587 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005588 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005589 while (*captureResult == EAGAIN) {
5590 captureResult.reset();
5591 result = postMessageAsync(message);
5592 if (result != NO_ERROR) {
5593 return result;
5594 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 }
5597 result = *captureResult;
5598 }
5599
5600 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 sync_wait(syncFd, -1);
5602 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005604
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005606}
5607
chaviwa76b2712017-09-20 12:02:26 -07005608void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005609 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005610 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5611 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005612 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005613
chaviwa76b2712017-09-20 12:02:26 -07005614 const auto reqWidth = renderArea.getReqWidth();
5615 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005616 const auto sourceCrop = renderArea.getSourceCrop();
5617 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005618
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005619 renderengine::DisplaySettings clientCompositionDisplay;
5620 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005621
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005622 // assume that bounds are never offset, and that they are the same as the
5623 // buffer bounds.
5624 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5625 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005626 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005627 mat4 rotMatrix;
5628 // Displacement for repositioning the clipping rectangle after rotating it
5629 // with the rotation hint.
5630 int displacementX = 0;
5631 int displacementY = 0;
5632 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5633 switch (rotation) {
5634 case ui::Transform::ROT_90:
5635 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5636 displacementX = reqWidth;
5637 break;
5638 case ui::Transform::ROT_180:
5639 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5640 displacementX = reqWidth;
5641 displacementY = reqHeight;
5642 break;
5643 case ui::Transform::ROT_270:
5644 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5645 displacementY = reqHeight;
5646 break;
5647 default:
5648 break;
5649 }
5650 // We need to transform the clipping window into the right spot.
5651 // First, rotate the clipping rectangle by the rotation hint to get the
5652 // right orientation
5653 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5654 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5655 const vec4 rotClipTL = rotMatrix * clipTL;
5656 const vec4 rotClipBR = rotMatrix * clipBR;
5657 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5658 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5659 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5660 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5661
5662 // Now reposition the clipping rectangle with the displacement vector
5663 // computed above.
5664 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5665
5666 clientCompositionDisplay.clip =
5667 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5668 newClipRight + displacementX, newClipBottom + displacementY);
5669
5670 // We need to perform the same transformation in layer space, so propagate
5671 // it to the global transform.
5672 mat4 clipTransform = displacementMat * rotMatrix;
5673 clientCompositionDisplay.globalTransform *= clipTransform;
5674 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5675 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005676
chaviw50da5042018-04-09 13:49:37 -07005677 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005678
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005679 renderengine::LayerSettings fillLayer;
5680 fillLayer.source.buffer.buffer = nullptr;
5681 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5682 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5683 fillLayer.alpha = half(alpha);
5684 clientCompositionLayers.push_back(fillLayer);
5685
5686 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005687 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005688 renderengine::LayerSettings layerSettings;
5689 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005690 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005691 if (prepared) {
5692 clientCompositionLayers.push_back(layerSettings);
5693 }
chaviwa76b2712017-09-20 12:02:26 -07005694 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695
5696 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005697 // Use an empty fence for the buffer fence, since we just created the buffer so
5698 // there is no need for synchronization with the GPU.
5699 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005700 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005701 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005702 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005703 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005704
5705 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005706}
5707
chaviwa76b2712017-09-20 12:02:26 -07005708status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5709 TraverseLayersFunction traverseLayers,
5710 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005711 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005712 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005713 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005714 ATRACE_CALL();
5715
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005716 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005717
5718 traverseLayers([&](Layer* layer) {
5719 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5720 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005721
Robert Carr03480e22018-01-04 16:02:06 -08005722 // We allow the system server to take screenshots of secure layers for
5723 // use in situations like the Screen-rotation animation and place
5724 // the impetus on WindowManager to not persist them.
5725 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005726 ALOGW("FB is protected: PERMISSION_DENIED");
5727 return PERMISSION_DENIED;
5728 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005729 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005730 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005731}
5732
chaviw95ef3c42019-02-14 10:55:09 -08005733void SurfaceFlinger::setInputWindowsFinished() {
5734 Mutex::Autolock _l(mStateLock);
5735
5736 mPendingSyncInputWindows = false;
5737 mTransactionCV.broadcast();
5738}
chaviw5f21a5e2019-02-14 10:00:34 -08005739
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005740// ---------------------------------------------------------------------------
5741
Dan Stoza412903f2017-04-27 13:42:17 -07005742void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5743 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005744}
5745
Dan Stoza412903f2017-04-27 13:42:17 -07005746void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5747 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005748}
5749
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005750void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005751 const LayerVector::Visitor& visitor) {
5752 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005753 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005754 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005755 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005756 continue;
5757 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005758 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005759 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005760 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005761 return;
5762 }
chaviwa76b2712017-09-20 12:02:26 -07005763 if (!layer->isVisible()) {
5764 return;
5765 }
5766 visitor(layer);
5767 });
5768 }
5769}
5770
Ady Abraham838de062019-02-04 10:24:03 -08005771void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5772 const android::sp<android::IBinder>& displayToken,
5773 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5774 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5775 if (!displayId) {
5776 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5777 return;
5778 }
5779
5780 ALOGV("Updating allowed configs");
5781 {
5782 std::lock_guard lock(mAllowedConfigsLock);
5783 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5784 }
5785
5786 // make sure that the current config is still allowed
5787 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5788 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005789 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
5790 if (isConfigAllowed(*displayId, config.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005791 // TODO: we switch to the first allowed config. In the future
5792 // we may want to enhance this logic to pick a similar config
5793 // to the current one
Ady Abraham1902d072019-03-01 17:18:59 -08005794 ALOGV("Old config is not allowed - switching to config %d", config.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005795 setDesiredActiveConfig(displayToken, config.configId,
5796 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005797 break;
5798 }
5799 }
5800 }
Ady Abraham97d04232019-03-05 19:48:12 -08005801
5802 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5803 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5804 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
5805 const auto performanceRefreshRate =
5806 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
5807 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ady Abraham97d04232019-03-05 19:48:12 -08005808 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5809 }
5810 }
Ady Abraham838de062019-02-04 10:24:03 -08005811}
5812
5813status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5814 const std::vector<int32_t>& allowedConfigs) {
5815 ATRACE_CALL();
5816
5817 if (!displayToken) {
5818 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5819 return BAD_VALUE;
5820 }
5821
5822 if (!allowedConfigs.size()) {
5823 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5824 return BAD_VALUE;
5825 }
5826
5827 {
5828 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5829 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5830 if (!displayId) {
5831 ALOGE("setAllowedDisplayConfigs: display not found");
5832 return NAME_NOT_FOUND;
5833 }
5834 }
5835
5836 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5837 for (int config : allowedConfigs) {
5838 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5839 allowedDisplayConfigsBuilder.addConfig(config);
5840 }
5841 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5842 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5843 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5844 }));
5845 return NO_ERROR;
5846}
5847
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005848status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5849 std::vector<int32_t>* outAllowedConfigs) {
5850 ATRACE_CALL();
5851
5852 if (!displayToken) {
5853 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5854 return BAD_VALUE;
5855 }
5856
5857 if (!outAllowedConfigs) {
5858 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5859 return BAD_VALUE;
5860 }
5861
5862 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5863 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5864 if (!displayId) {
5865 ALOGE("getAllowedDisplayConfigs: display not found");
5866 return NAME_NOT_FOUND;
5867 }
5868
5869 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5870 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5871 if (allowedConfigIterator != mAllowedConfigs.end()) {
5872 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5873 }
5874
5875 return NO_ERROR;
5876}
5877
chaviw291d88a2019-02-14 10:33:58 -08005878// ----------------------------------------------------------------------------
5879
5880void SetInputWindowsListener::onSetInputWindowsFinished() {
5881 mFlinger->setInputWindowsFinished();
5882}
5883
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005884}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005885
Lloyd Pique074e8122018-07-26 12:57:23 -07005886
Mathias Agopian3f844832013-08-07 21:24:32 -07005887#if defined(__gl_h_)
5888#error "don't include gl/gl.h in this file"
5889#endif
5890
5891#if defined(__gl2_h_)
5892#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005893#endif