blob: f6251b8a4bd9bcf7cf47e7aa6468ee5f6d848706 [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()) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003511 const auto& [states, displays, flags, desiredPresentTime, postTime, privileged] =
Robert Carr14167e02019-02-13 13:50:55 -08003512 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003513 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003514 break;
3515 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003516 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
Valerie Hau0779ded2019-03-19 12:43:04 -07003517 desiredPresentTime, postTime, privileged, /*isMainThread*/ true);
Marissa Wall713b63f2018-10-17 15:42:43 -07003518 transactionQueue.pop();
3519 }
3520
3521 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3522 }
3523 return mTransactionQueues.empty();
3524}
3525
chaviwca27f252018-02-06 16:46:39 -08003526bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3527 for (const ComposerState& state : states) {
3528 // Here we need to check that the interface we're given is indeed
3529 // one of our own. A malicious client could give us a nullptr
3530 // IInterface, or one of its own or even one of our own but a
3531 // different type. All these situations would cause us to crash.
3532 if (state.client == nullptr) {
3533 return true;
3534 }
3535
3536 sp<IBinder> binder = IInterface::asBinder(state.client);
3537 if (binder == nullptr) {
3538 return true;
3539 }
3540
3541 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3542 return true;
3543 }
3544 }
3545 return false;
3546}
3547
Marissa Wall17b4e452018-12-26 16:32:34 -08003548bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3549 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003550 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003551 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3552 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3553 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3554 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3555 return false;
3556 }
3557
Marissa Wall713b63f2018-10-17 15:42:43 -07003558 for (const ComposerState& state : states) {
3559 const layer_state_t& s = state.state;
3560 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3561 continue;
3562 }
3563 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003564 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003565 }
3566 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003567 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003568}
3569
3570void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3571 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003572 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 const InputWindowCommands& inputWindowCommands,
3574 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003575 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003576
Valerie Haubc6ddb12019-03-08 11:10:15 -08003577 const int64_t postTime = systemTime();
3578
Robert Carr14167e02019-02-13 13:50:55 -08003579 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3580
Mathias Agopian698c0872011-06-28 19:09:31 -07003581 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003582
chaviwca27f252018-02-06 16:46:39 -08003583 if (containsAnyInvalidClientState(states)) {
3584 return;
3585 }
3586
Marissa Wall713b63f2018-10-17 15:42:43 -07003587 // If its TransactionQueue already has a pending TransactionState or if it is pending
3588 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003589 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003590 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003591 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003592 setTransactionFlags(eTransactionNeeded);
3593 return;
3594 }
3595
Valerie Haubc6ddb12019-03-08 11:10:15 -08003596 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
3597 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003598}
3599
3600void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003601 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003602 const InputWindowCommands& inputWindowCommands,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003603 const int64_t desiredPresentTime, const int64_t postTime,
Valerie Hau0779ded2019-03-19 12:43:04 -07003604 bool privileged, bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003605 uint32_t transactionFlags = 0;
3606
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003607 if (flags & eAnimation) {
3608 // For window updates that are part of an animation we must wait for
3609 // previous animation "frames" to be handled.
3610 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003611 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003612 if (CC_UNLIKELY(err != NO_ERROR)) {
3613 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003614 // caller after a few seconds.
3615 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3616 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003617 mAnimTransactionPending = false;
3618 break;
3619 }
3620 }
3621 }
3622
chaviwca27f252018-02-06 16:46:39 -08003623 for (const DisplayState& display : displays) {
3624 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003625 }
3626
Marissa Walle2ffb422018-10-12 11:33:52 -07003627 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003628 for (const ComposerState& state : states) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003629 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged);
chaviwca27f252018-02-06 16:46:39 -08003630 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003631 // If the state doesn't require a traversal and there are callbacks, send them now
3632 if (!(clientStateFlags & eTraversalNeeded)) {
3633 mTransactionCompletedThread.sendCallbacks();
3634 }
3635 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003636
chaviw273171b2018-12-26 11:46:30 -08003637 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3638
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003639 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3640 // anyway. This can be used as a flush mechanism for previous async transactions.
3641 // Empty animation transaction can be used to simulate back-pressure, so also force a
3642 // transaction for empty animation transactions.
3643 if (transactionFlags == 0 &&
3644 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003645 transactionFlags = eTransactionNeeded;
3646 }
3647
Mathias Agopian386aa982011-11-07 21:58:03 -08003648 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003649 if (mInterceptor->isEnabled()) {
3650 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003651 }
Irvel468051e2016-06-13 16:44:44 -07003652
Mathias Agopian386aa982011-11-07 21:58:03 -08003653 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003654 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3655 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003656 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003657
3658 // if this is a synchronous transaction, wait for it to take effect
3659 // before returning.
3660 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003661 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003662 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003663 if (flags & eAnimation) {
3664 mAnimTransactionPending = true;
3665 }
chaviw95ef3c42019-02-14 10:55:09 -08003666
3667 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
Valerie Hau0779ded2019-03-19 12:43:04 -07003668
3669 // applyTransactionState can be called by either the main SF thread or by
3670 // another process through setTransactionState. While a given process may wish
3671 // to wait on synchronous transactions, the main SF thread should never
3672 // be blocked. Therefore, we only wait if isMainThread is false.
3673 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003674 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3675 if (CC_UNLIKELY(err != NO_ERROR)) {
3676 // just in case something goes wrong in SF, return to the
3677 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003678 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3679 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003680 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003681 break;
3682 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684 }
3685}
3686
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003687uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3688 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3689 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003690
Mathias Agopiane57f2922012-08-09 16:29:12 -07003691 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003692 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3693
3694 const uint32_t what = s.what;
3695 if (what & DisplayState::eSurfaceChanged) {
3696 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3697 state.surface = s.surface;
3698 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003699 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003700 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003701 if (what & DisplayState::eLayerStackChanged) {
3702 if (state.layerStack != s.layerStack) {
3703 state.layerStack = s.layerStack;
3704 flags |= eDisplayTransactionNeeded;
3705 }
3706 }
3707 if (what & DisplayState::eDisplayProjectionChanged) {
3708 if (state.orientation != s.orientation) {
3709 state.orientation = s.orientation;
3710 flags |= eDisplayTransactionNeeded;
3711 }
3712 if (state.frame != s.frame) {
3713 state.frame = s.frame;
3714 flags |= eDisplayTransactionNeeded;
3715 }
3716 if (state.viewport != s.viewport) {
3717 state.viewport = s.viewport;
3718 flags |= eDisplayTransactionNeeded;
3719 }
3720 }
3721 if (what & DisplayState::eDisplaySizeChanged) {
3722 if (state.width != s.width) {
3723 state.width = s.width;
3724 flags |= eDisplayTransactionNeeded;
3725 }
3726 if (state.height != s.height) {
3727 state.height = s.height;
3728 flags |= eDisplayTransactionNeeded;
3729 }
3730 }
3731
Mathias Agopiane57f2922012-08-09 16:29:12 -07003732 return flags;
3733}
3734
Robert Carr14167e02019-02-13 13:50:55 -08003735bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003736 IPCThreadState* ipc = IPCThreadState::self();
3737 const int pid = ipc->getCallingPid();
3738 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003739 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003740 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003741 return false;
3742 }
3743 return true;
3744}
3745
Robert Carr14167e02019-02-13 13:50:55 -08003746uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003747 int64_t desiredPresentTime, int64_t postTime,
3748 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003749 const layer_state_t& s = composerState.state;
3750 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3751
Mathias Agopian13127d82013-03-05 17:47:11 -08003752 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003753 if (layer == nullptr) {
3754 return 0;
3755 }
3756
chaviw8b3871a2017-11-01 17:41:01 -07003757 uint32_t flags = 0;
3758
Garfield Tan8a3083e2018-12-03 13:21:07 -08003759 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003760 bool geometryAppliesWithResize =
3761 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003762
3763 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3764 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003765 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003766 layer->pushPendingState();
3767 }
3768
chaviw8b3871a2017-11-01 17:41:01 -07003769 if (what & layer_state_t::ePositionChanged) {
3770 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3771 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003772 }
chaviw8b3871a2017-11-01 17:41:01 -07003773 }
3774 if (what & layer_state_t::eLayerChanged) {
3775 // NOTE: index needs to be calculated before we update the state
3776 const auto& p = layer->getParent();
3777 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003778 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003779 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003780 mCurrentState.layersSortedByZ.removeAt(idx);
3781 mCurrentState.layersSortedByZ.add(layer);
3782 // we need traversal (state changed)
3783 // AND transaction (list changed)
3784 flags |= eTransactionNeeded|eTraversalNeeded;
3785 }
chaviw8b3871a2017-11-01 17:41:01 -07003786 } else {
3787 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003788 flags |= eTransactionNeeded|eTraversalNeeded;
3789 }
3790 }
chaviw8b3871a2017-11-01 17:41:01 -07003791 }
3792 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003793 // NOTE: index needs to be calculated before we update the state
3794 const auto& p = layer->getParent();
3795 if (p == nullptr) {
3796 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3797 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3798 mCurrentState.layersSortedByZ.removeAt(idx);
3799 mCurrentState.layersSortedByZ.add(layer);
3800 // we need traversal (state changed)
3801 // AND transaction (list changed)
3802 flags |= eTransactionNeeded|eTraversalNeeded;
3803 }
3804 } else {
3805 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3806 flags |= eTransactionNeeded|eTraversalNeeded;
3807 }
chaviw8b3871a2017-11-01 17:41:01 -07003808 }
3809 }
3810 if (what & layer_state_t::eSizeChanged) {
3811 if (layer->setSize(s.w, s.h)) {
3812 flags |= eTraversalNeeded;
3813 }
3814 }
3815 if (what & layer_state_t::eAlphaChanged) {
3816 if (layer->setAlpha(s.alpha))
3817 flags |= eTraversalNeeded;
3818 }
3819 if (what & layer_state_t::eColorChanged) {
3820 if (layer->setColor(s.color))
3821 flags |= eTraversalNeeded;
3822 }
Peiyong Lind3788632018-09-18 16:01:31 -07003823 if (what & layer_state_t::eColorTransformChanged) {
3824 if (layer->setColorTransform(s.colorTransform)) {
3825 flags |= eTraversalNeeded;
3826 }
3827 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003828 if (what & layer_state_t::eBackgroundColorChanged) {
3829 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3830 flags |= eTraversalNeeded;
3831 }
3832 }
chaviw8b3871a2017-11-01 17:41:01 -07003833 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003834 // TODO: b/109894387
3835 //
3836 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3837 // rotation. To see the problem observe that if we have a square parent, and a child
3838 // of the same size, then we rotate the child 45 degrees around it's center, the child
3839 // must now be cropped to a non rectangular 8 sided region.
3840 //
3841 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3842 // private API, and the WindowManager only uses rotation in one case, which is on a top
3843 // level layer in which cropping is not an issue.
3844 //
3845 // However given that abuse of rotation matrices could lead to surfaces extending outside
3846 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3847 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3848 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003849 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003850 flags |= eTraversalNeeded;
3851 }
3852 if (what & layer_state_t::eTransparentRegionChanged) {
3853 if (layer->setTransparentRegionHint(s.transparentRegion))
3854 flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eFlagsChanged) {
3857 if (layer->setFlags(s.flags, s.mask))
3858 flags |= eTraversalNeeded;
3859 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003860 if (what & layer_state_t::eCropChanged_legacy) {
3861 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003862 flags |= eTraversalNeeded;
3863 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003864 if (what & layer_state_t::eCornerRadiusChanged) {
3865 if (layer->setCornerRadius(s.cornerRadius))
3866 flags |= eTraversalNeeded;
3867 }
chaviw8b3871a2017-11-01 17:41:01 -07003868 if (what & layer_state_t::eLayerStackChanged) {
3869 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3870 // We only allow setting layer stacks for top level layers,
3871 // everything else inherits layer stack from its parent.
3872 if (layer->hasParent()) {
3873 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3874 layer->getName().string());
3875 } else if (idx < 0) {
3876 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3877 "that also does not appear in the top level layer list. Something"
3878 " has gone wrong.", layer->getName().string());
3879 } else if (layer->setLayerStack(s.layerStack)) {
3880 mCurrentState.layersSortedByZ.removeAt(idx);
3881 mCurrentState.layersSortedByZ.add(layer);
3882 // we need traversal (state changed)
3883 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003884 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003885 }
3886 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003887 if (what & layer_state_t::eDeferTransaction_legacy) {
3888 if (s.barrierHandle_legacy != nullptr) {
3889 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3890 } else if (s.barrierGbp_legacy != nullptr) {
3891 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003892 if (authenticateSurfaceTextureLocked(gbp)) {
3893 const auto& otherLayer =
3894 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003895 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003896 } else {
3897 ALOGE("Attempt to defer transaction to to an"
3898 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003899 }
3900 }
chaviw8b3871a2017-11-01 17:41:01 -07003901 // We don't trigger a traversal here because if no other state is
3902 // changed, we don't want this to cause any more work
3903 }
3904 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003905 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003906 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003907 if (!hadParent) {
3908 mCurrentState.layersSortedByZ.remove(layer);
3909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003911 }
chaviw8b3871a2017-11-01 17:41:01 -07003912 }
3913 if (what & layer_state_t::eReparentChildren) {
3914 if (layer->reparentChildren(s.reparentHandle)) {
3915 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003916 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003917 }
chaviw8b3871a2017-11-01 17:41:01 -07003918 if (what & layer_state_t::eDetachChildren) {
3919 layer->detachChildren();
3920 }
3921 if (what & layer_state_t::eOverrideScalingModeChanged) {
3922 layer->setOverrideScalingMode(s.overrideScalingMode);
3923 // We don't trigger a traversal here because if no other state is
3924 // changed, we don't want this to cause any more work
3925 }
Marissa Wall61c58622018-07-18 10:12:20 -07003926 if (what & layer_state_t::eTransformChanged) {
3927 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3928 }
3929 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3930 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3931 flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eCropChanged) {
3934 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3935 }
Marissa Wall861616d2018-10-22 12:52:23 -07003936 if (what & layer_state_t::eFrameChanged) {
3937 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3938 }
Marissa Wall61c58622018-07-18 10:12:20 -07003939 if (what & layer_state_t::eAcquireFenceChanged) {
3940 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eDataspaceChanged) {
3943 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eHdrMetadataChanged) {
3946 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3949 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eApiChanged) {
3952 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eSidebandStreamChanged) {
3955 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3956 }
Robert Carr720e5062018-07-30 17:45:14 -07003957 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003958 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003959 layer->setInputInfo(s.inputInfo);
3960 flags |= eTraversalNeeded;
3961 } else {
3962 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3963 }
Robert Carr720e5062018-07-30 17:45:14 -07003964 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003965 if (what & layer_state_t::eMetadataChanged) {
3966 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3967 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003968 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3969 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3970 flags |= eTraversalNeeded;
3971 }
3972 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003973 std::vector<sp<CallbackHandle>> callbackHandles;
3974 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3975 mTransactionCompletedThread.run();
3976 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3977 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3978 }
3979 }
Marissa Wall73411622019-01-25 10:45:41 -08003980
3981 if (what & layer_state_t::eBufferChanged) {
3982 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3983 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3984 s.buffer);
3985 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003986 if (what & layer_state_t::eCachedBufferChanged) {
3987 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003988 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3989 s.cachedBuffer.bufferId);
Valerie Haubc6ddb12019-03-08 11:10:15 -08003990 if (layer->setBuffer(buffer)) {
3991 flags |= eTraversalNeeded;
3992 layer->setPostTime(postTime);
3993 layer->setDesiredPresentTime(desiredPresentTime);
3994 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003995 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003996 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3997 // Do not put anything that updates layer state or modifies flags after
3998 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003999 return flags;
4000}
4001
chaviw273171b2018-12-26 11:46:30 -08004002uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4003 uint32_t flags = 0;
4004 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4005 flags |= eTraversalNeeded;
4006 }
4007
chaviwa911b102019-02-14 10:18:33 -08004008 if (inputWindowCommands.syncInputWindows) {
4009 flags |= eTraversalNeeded;
4010 }
4011
Vishnu Nairec0ab382019-02-13 15:32:56 -08004012 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004013 return flags;
4014}
4015
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004016status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4017 uint32_t h, PixelFormat format, uint32_t flags,
4018 LayerMetadata metadata, sp<IBinder>* handle,
4019 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004020 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004021 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004022 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004023 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004024 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004025
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004026 status_t result = NO_ERROR;
4027
4028 sp<Layer> layer;
4029
Cody Northropbc755282017-03-31 12:00:08 -06004030 String8 uniqueName = getUniqueLayerName(name);
4031
Evan Roskya1f1e152019-01-24 16:17:46 -08004032 bool primaryDisplayOnly = false;
4033
4034 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4035 // TODO b/64227542
4036 if (metadata.has(METADATA_WINDOW_TYPE)) {
4037 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4038 if (windowType == 441731) {
4039 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4040 primaryDisplayOnly = true;
4041 }
4042 }
4043
Mathias Agopian3165cc22012-08-08 19:42:09 -07004044 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004045 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004046 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4047 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004050 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004051 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4052 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004053 break;
chaviw13fdc492017-06-27 12:40:18 -07004054 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004055 // check if buffer size is set for color layer.
4056 if (w > 0 || h > 0) {
4057 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4058 int(w), int(h));
4059 return BAD_VALUE;
4060 }
4061
Evan Roskya1f1e152019-01-24 16:17:46 -08004062 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4063 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004065 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004066 // check if buffer size is set for container layer.
4067 if (w > 0 || h > 0) {
4068 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4069 int(w), int(h));
4070 return BAD_VALUE;
4071 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004072 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4073 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004074 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004075 default:
4076 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077 break;
4078 }
4079
Dan Stoza7d89d062015-04-30 13:29:25 -07004080 if (result != NO_ERROR) {
4081 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004083
Evan Roskya1f1e152019-01-24 16:17:46 -08004084 if (primaryDisplayOnly) {
4085 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004086 }
4087
Robert Carrb89ea9d2018-12-10 13:01:14 -08004088 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4089 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4090 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004091 if (result != NO_ERROR) {
4092 return result;
4093 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004094 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004095
4096 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004097 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004098}
4099
Cody Northropbc755282017-03-31 12:00:08 -06004100String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4101{
4102 bool matchFound = true;
4103 uint32_t dupeCounter = 0;
4104
4105 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4106 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4107
Dan Stoza436ccf32018-06-21 12:10:12 -07004108 // Grab the state lock since we're accessing mCurrentState
4109 Mutex::Autolock lock(mStateLock);
4110
Cody Northropbc755282017-03-31 12:00:08 -06004111 // Loop over layers until we're sure there is no matching name
4112 while (matchFound) {
4113 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004114 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004115 if (layer->getName() == uniqueName) {
4116 matchFound = true;
4117 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4118 }
4119 });
4120 }
4121
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004122 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4123 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004124
4125 return uniqueName;
4126}
4127
Marissa Wallfd668622018-05-10 10:21:13 -07004128status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4129 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004130 LayerMetadata metadata, PixelFormat& format,
4131 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004132 sp<IGraphicBufferProducer>* gbp,
4133 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004135 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 case PIXEL_FORMAT_TRANSPARENT:
4137 case PIXEL_FORMAT_TRANSLUCENT:
4138 format = PIXEL_FORMAT_RGBA_8888;
4139 break;
4140 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004141 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 break;
4143 }
4144
Evan Roskya1f1e152019-01-24 16:17:46 -08004145 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4146 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004147 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004149 *handle = layer->getHandle();
4150 *gbp = layer->getProducer();
4151 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153
Marissa Wallfd668622018-05-10 10:21:13 -07004154 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004155 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156}
4157
Marissa Wall61c58622018-07-18 10:12:20 -07004158status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4159 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004160 LayerMetadata metadata, sp<IBinder>* handle,
4161 sp<Layer>* outLayer) {
4162 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4163 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004164 *handle = layer->getHandle();
4165 *outLayer = layer;
4166
4167 return NO_ERROR;
4168}
4169
Evan Roskya1f1e152019-01-24 16:17:46 -08004170status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4171 uint32_t h, uint32_t flags, LayerMetadata metadata,
4172 sp<IBinder>* handle, sp<Layer>* outLayer) {
4173 *outLayer = getFactory().createColorLayer(
4174 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004175 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004176 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004177}
4178
Evan Roskya1f1e152019-01-24 16:17:46 -08004179status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4180 uint32_t w, uint32_t h, uint32_t flags,
4181 LayerMetadata metadata, sp<IBinder>* handle,
4182 sp<Layer>* outLayer) {
4183 *outLayer = getFactory().createContainerLayer(
4184 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004185 *handle = (*outLayer)->getHandle();
4186 return NO_ERROR;
4187}
4188
4189
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004190void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004191 mLayersPendingRemoval.add(layer);
4192 mLayersRemoved = true;
4193 setTransactionFlags(eTransactionNeeded);
4194}
4195
Robert Carr695d5282018-12-18 15:27:58 -08004196void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004197{
Robert Carr2e102c92018-10-23 12:11:15 -07004198 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004199 // If a layer has a parent, we allow it to out-live it's handle
4200 // with the idea that the parent holds a reference and will eventually
4201 // be cleaned up. However no one cleans up the top-level so we do so
4202 // here.
4203 if (layer->getParent() == nullptr) {
4204 mCurrentState.layersSortedByZ.remove(layer);
4205 }
4206 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004207 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004208}
4209
Mathias Agopianb60314a2012-04-10 22:09:54 -07004210// ---------------------------------------------------------------------------
4211
Andy McFadden13a082e2012-08-24 10:16:42 -07004212void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004213 const auto display = getDefaultDisplayDeviceLocked();
4214 if (!display) return;
4215
4216 const sp<IBinder> token = display->getDisplayToken().promote();
4217 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004218
Jesse Hall01e29052013-02-19 16:13:35 -08004219 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004220 Vector<ComposerState> state;
4221 Vector<DisplayState> displays;
4222 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004223 d.what = DisplayState::eDisplayProjectionChanged |
4224 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004225 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004226 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004227 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004228 d.frame.makeInvalid();
4229 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004230 d.width = 0;
4231 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004232 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004233 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004234
Dominik Laskowskie9774092018-12-11 10:04:24 -08004235 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004236
Dominik Laskowski83b88212018-12-11 13:34:06 -08004237 const nsecs_t vsyncPeriod = getVsyncPeriod();
4238 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004239
Brian Andersond0010582017-03-07 13:20:31 -08004240 // Use phase of 0 since phase is not known.
4241 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004242 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004243 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004244}
4245
4246void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004247 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004248 postMessageAsync(
4249 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004250}
4251
Dominik Laskowskie9774092018-12-11 10:04:24 -08004252void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004253 if (display->isVirtual()) {
4254 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004255 return;
4256 }
4257
Dominik Laskowski075d3172018-05-24 15:50:06 -07004258 const auto displayId = display->getId();
4259 LOG_ALWAYS_FATAL_IF(!displayId);
4260
Dominik Laskowski34157762018-10-31 13:07:19 -07004261 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004262
4263 int currentMode = display->getPowerMode();
4264 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 return;
4266 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004267
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004268 display->setPowerMode(mode);
4269
Lloyd Pique4dccc412018-01-22 17:21:36 -08004270 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004271 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004272 }
4273
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004274 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004275 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004278 mScheduler->onScreenAcquired(mAppConnectionHandle);
4279 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004282 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004283 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004284 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004285
4286 struct sched_param param = {0};
4287 param.sched_priority = 1;
4288 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4289 ALOGW("Couldn't set SCHED_FIFO on display on");
4290 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004291 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004292 // Turn off the display
4293 struct sched_param param = {0};
4294 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4295 ALOGW("Couldn't set SCHED_OTHER on display off");
4296 }
4297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004299 mScheduler->disableHardwareVsync(true);
4300 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004301 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 mVisibleRegionsDirty = true;
4305 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004306 } else if (mode == HWC_POWER_MODE_DOZE ||
4307 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004308 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004309 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004311 mScheduler->onScreenAcquired(mAppConnectionHandle);
4312 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004313 }
4314 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4315 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004317 mScheduler->disableHardwareVsync(true);
4318 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004319 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004320 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004321 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004322 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004324 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004325
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004326 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004327 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004328 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004329 // Update refresh rate stats.
4330 mRefreshRateStats->setPowerMode(mode);
4331 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004332 }
4333
Dominik Laskowski34157762018-10-31 13:07:19 -07004334 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004335}
4336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004337void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004338 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004339 const auto display = getDisplayDevice(displayToken);
4340 if (!display) {
4341 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4342 displayToken.get());
4343 } else if (display->isVirtual()) {
4344 ALOGW("Attempt to set power mode %d for virtual display", mode);
4345 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004346 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004347 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004348 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004349}
4350
4351// ---------------------------------------------------------------------------
4352
Dominik Laskowskic2867142019-01-21 11:33:38 -08004353status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4354 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004356
Mathias Agopianbd115332013-04-18 16:41:04 -07004357 IPCThreadState* ipc = IPCThreadState::self();
4358 const int pid = ipc->getCallingPid();
4359 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004360
Mathias Agopianbd115332013-04-18 16:41:04 -07004361 if ((uid != AID_SHELL) &&
4362 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004363 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4364 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004366 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004367 // (this would indicate SF is stuck, but we want to be able to
4368 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004369 status_t err = mStateLock.timedLock(s2ns(1));
4370 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004371 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372 StringAppendF(&result,
4373 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4374 "(no locks held)\n",
4375 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004376 }
4377
Dominik Laskowskic2867142019-01-21 11:33:38 -08004378 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380 static const std::unordered_map<std::string, Dumper> dumpers = {
4381 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4382 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4383 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004384 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004385 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004386 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004387 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4388 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4390 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4391 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4392 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4393 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4394 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004395 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004396 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4397 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004398
Dominik Laskowskic2867142019-01-21 11:33:38 -08004399 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400
Dominik Laskowskic2867142019-01-21 11:33:38 -08004401 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4402 (it->second)(args, asProto, result);
4403 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004404 if (asProto) {
4405 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4406 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4407 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004409 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004410 }
4411
Mathias Agopian9795c422009-08-26 16:36:26 -07004412 if (locked) {
4413 mStateLock.unlock();
4414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004415 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004417 return NO_ERROR;
4418}
4419
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004420status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4421 if (asProto && mTracing.isEnabled()) {
4422 mTracing.writeToFileAsync();
4423 }
4424
4425 return doDump(fd, DumpArgs(), asProto);
4426}
4427
Dominik Laskowskic2867142019-01-21 11:33:38 -08004428void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004429 mCurrentState.traverseInZOrder(
4430 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004431}
4432
Dominik Laskowskic2867142019-01-21 11:33:38 -08004433void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004434 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004435
Dominik Laskowskic2867142019-01-21 11:33:38 -08004436 if (args.size() > 1) {
4437 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004438 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004439 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004440 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004441 }
Robert Carr2047fae2016-11-28 14:09:09 -08004442 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004443 } else {
4444 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445 }
4446}
4447
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004449 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004450 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004451 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004452 }
Robert Carr2047fae2016-11-28 14:09:09 -08004453 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004454
Svetoslavd85084b2014-03-20 10:28:31 -07004455 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004456}
4457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4459 mTimeStats->parseArgs(asProto, args, result);
4460}
4461
Jamie Gennis6547ff42013-07-16 20:12:42 -07004462// This should only be called from the main thread. Otherwise it would need
4463// the lock and should use mCurrentState rather than mDrawingState.
4464void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004465 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004466 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004467 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004468
4469 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4470}
4471
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004473 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004474
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004475 if (isLayerTripleBufferingDisabled())
4476 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4479 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4480 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4481 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4482 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4483 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004484 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004485}
4486
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004487void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004488 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004489 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004490 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004491 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004492
Ady Abraham97d04232019-03-05 19:48:12 -08004493 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004494 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4495 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004496 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004497}
4498
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4500 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004501 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4502 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004503 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004504 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004506 }
David Sodman4a36e932017-11-07 14:29:47 -08004507 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004508 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004509 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004510 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4511 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004512}
4513
Dan Stozae77c7662016-05-13 11:37:28 -07004514void SurfaceFlinger::recordBufferingStats(const char* layerName,
4515 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004516 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4517 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004518 for (const auto& segment : history) {
4519 if (!segment.usedThirdBuffer) {
4520 stats.twoBufferTime += segment.totalTime;
4521 }
4522 if (segment.occupancyAverage < 1.0f) {
4523 stats.doubleBufferedTime += segment.totalTime;
4524 } else if (segment.occupancyAverage < 2.0f) {
4525 stats.tripleBufferedTime += segment.totalTime;
4526 }
4527 ++stats.numSegments;
4528 stats.totalTime += segment.totalTime;
4529 }
4530}
4531
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4533 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004534
4535 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4536 const size_t count = currentLayers.size();
4537 for (size_t i=0 ; i<count ; i++) {
4538 currentLayers[i]->dumpFrameEvents(result);
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004543 result.append("Buffering stats:\n");
4544 result.append(" [Layer name] <Active time> <Two buffer> "
4545 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004546 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004547 typedef std::tuple<std::string, float, float, float> BufferTuple;
4548 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004549 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004550 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004551 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004552 if (stats.numSegments == 0) {
4553 continue;
4554 }
4555 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4556 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4557 stats.totalTime;
4558 float doubleBufferRatio = static_cast<float>(
4559 stats.doubleBufferedTime) / stats.totalTime;
4560 float tripleBufferRatio = static_cast<float>(
4561 stats.tripleBufferedTime) / stats.totalTime;
4562 sorted.insert({activeTime, {name, twoBufferRatio,
4563 doubleBufferRatio, tripleBufferRatio}});
4564 }
4565 for (const auto& sortedPair : sorted) {
4566 float activeTime = sortedPair.first;
4567 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4569 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004570 }
4571 result.append("\n");
4572}
4573
Yiwei Zhang5434a782018-12-05 18:06:32 -08004574void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004575 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004576 const auto displayId = display->getId();
4577 if (!displayId) {
4578 continue;
4579 }
4580 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004581 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004582 continue;
4583 }
4584
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585 StringAppendF(&result,
4586 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4587 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004588 uint8_t port;
4589 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004590 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004591 result.append("no identification data\n");
4592 continue;
4593 }
4594
4595 if (!isEdid(data)) {
4596 result.append("unknown identification data: ");
4597 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004599 }
4600 result.append("\n");
4601 continue;
4602 }
4603
4604 const auto edid = parseEdid(data);
4605 if (!edid) {
4606 result.append("invalid EDID: ");
4607 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 }
4610 result.append("\n");
4611 continue;
4612 }
4613
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004615 result.append(edid->displayName.data(), edid->displayName.length());
4616 result.append("\"\n");
4617 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004618}
4619
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4621 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4622 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4623 StringAppendF(&result, "DisplayColorSetting: %s\n",
4624 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625
4626 // TODO: print out if wide-color mode is active or not
4627
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004628 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 const auto displayId = display->getId();
4630 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004631 continue;
4632 }
4633
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004635 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004636 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004637 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004638 }
4639
Lloyd Pique32cbe282018-10-19 13:09:22 -07004640 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, " Current color mode: %s (%d)\n",
4642 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004643 }
4644 result.append("\n");
4645}
4646
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004647LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4648 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004649 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004650 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4651 const State& state = useDrawing ? mDrawingState : mCurrentState;
4652 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004653 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004654 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004655 });
4656
4657 return layersProto;
4658}
4659
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004660LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4661 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004662 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004663
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004664 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004665 resolution->set_w(displayDevice->getWidth());
4666 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004667
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004668 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004669 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004670
Lloyd Pique32cbe282018-10-19 13:09:22 -07004671 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4672 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4673 layersProto.set_global_transform(displayState.orientation);
4674
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004675 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004676 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004677 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004678 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004679 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004680 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004681 }
4682 });
4683
4684 return layersProto;
4685}
4686
Dominik Laskowskic2867142019-01-21 11:33:38 -08004687void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4688 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 Colorizer colorizer(colorize);
4690
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691 // figure out if we're stuck somewhere
4692 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4695
4696 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004697 * Dump library configuration.
4698 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004699
4700 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004701 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004703 appendSfConfigString(result);
4704 appendUiConfigString(result);
4705 appendGuiConfigString(result);
4706 result.append("\n");
4707
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004708 result.append("\nDisplay identification data:\n");
4709 dumpDisplayIdentificationData(result);
4710
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004711 result.append("\nWide-Color information:\n");
4712 dumpWideColorInfo(result);
4713
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004715 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004717 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004718 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004719
Andy McFadden41d67d72014-04-25 16:58:34 -07004720 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004721 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004722 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004723 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004724 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004725
Dan Stozab90cf072015-03-05 11:05:59 -08004726 dumpStaticScreenStats(result);
4727 result.append("\n");
4728
Alec Mouri40189b02019-03-05 15:07:54 -08004729 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4730 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4731 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004732
Dan Stozae77c7662016-05-13 11:37:28 -07004733 dumpBufferingStats(result);
4734
Andy McFadden4803b742012-09-24 19:07:20 -07004735 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004736 * Dump the visible layer list
4737 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4740 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4741 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004742 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004743
Chia-I Wu2f884132018-09-13 15:17:58 -07004744 {
4745 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4746 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004748 result.append("\n");
4749 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750
Lloyd Pique207def92019-02-28 16:09:52 -08004751 {
4752 StringAppendF(&result, "Composition layers\n");
4753 mDrawingState.traverseInZOrder([&](Layer* layer) {
4754 auto compositionLayer = layer->getCompositionLayer();
4755 if (compositionLayer) compositionLayer->dump(result);
4756 });
4757 }
4758
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004760 * Dump Display state
4761 */
4762
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004764 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004766 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004767 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004768 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004769 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004770
4771 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772 * Dump SurfaceFlinger global state
4773 */
4774
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004776 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004779 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
Dominik Laskowski075d3172018-05-24 15:50:06 -07004781 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004782 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4783 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4785 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004786 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result,
4788 " transaction-flags : %08x\n"
4789 " gpu_to_cpu_unsupported : %d\n",
4790 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004791
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004792 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004793 displayId && getHwComposer().isConnected(*displayId)) {
4794 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 StringAppendF(&result,
4796 " refresh-rate : %f fps\n"
4797 " x-dpi : %f\n"
4798 " y-dpi : %f\n",
4799 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4800 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004801 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004804
Dan Stozae22aec72016-08-01 13:20:59 -07004805 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004806 * Tracing state
4807 */
4808 mTracing.dump(result);
4809 result.append("\n");
4810
4811 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004812 * HWC layer minidump
4813 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004814 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815 const auto displayId = display->getId();
4816 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004817 continue;
4818 }
4819
Yiwei Zhang5434a782018-12-05 18:06:32 -08004820 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004821 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004822 const sp<DisplayDevice> displayDevice = display;
4823 mCurrentState.traverseInZOrder(
4824 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004825 result.append("\n");
4826 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004827
4828 /*
4829 * Dump HWComposer state
4830 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004832 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004833 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004834 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004835 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004836 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
4838 /*
4839 * Dump gralloc state
4840 */
4841 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4842 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004843
4844 /*
4845 * Dump VrFlinger state if in use.
4846 */
4847 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4848 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004850 result.append("\n");
4851 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004852
4853 /**
4854 * Scheduler dump state.
4855 */
Ana Krulecc2870422019-01-29 19:00:58 -08004856 result.append("\nScheduler state:\n");
4857 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004858 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004859 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004860}
4861
Dominik Laskowski075d3172018-05-24 15:50:06 -07004862const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004863 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004864 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004865 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004866 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004867 }
4868 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004869
Dominik Laskowski34157762018-10-31 13:07:19 -07004870 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004871 static const Vector<sp<Layer>> empty;
4872 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004873}
4874
Chia-I Wu28f320b2018-05-03 11:02:56 -07004875void SurfaceFlinger::updateColorMatrixLocked() {
4876 mat4 colorMatrix;
4877 if (mGlobalSaturationFactor != 1.0f) {
4878 // Rec.709 luma coefficients
4879 float3 luminance{0.213f, 0.715f, 0.072f};
4880 luminance *= 1.0f - mGlobalSaturationFactor;
4881 mat4 saturationMatrix = mat4(
4882 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4883 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4884 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4885 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4886 );
4887 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4888 } else {
4889 colorMatrix = mClientColorMatrix * mDaltonizer();
4890 }
4891
4892 if (mCurrentState.colorMatrix != colorMatrix) {
4893 mCurrentState.colorMatrix = colorMatrix;
4894 mCurrentState.colorMatrixChanged = true;
4895 setTransactionFlags(eTransactionNeeded);
4896 }
4897}
4898
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004899status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900#pragma clang diagnostic push
4901#pragma clang diagnostic error "-Wswitch-enum"
4902 switch (static_cast<ISurfaceComposerTag>(code)) {
4903 // These methods should at minimum make sure that the client requested
4904 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004905 case BOOT_FINISHED:
4906 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 case CREATE_DISPLAY:
4908 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004909 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 case GET_ANIMATION_FRAME_STATS:
4911 case GET_HDR_CAPABILITIES:
4912 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004913 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004914 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004916 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004917 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004918 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004919 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4920 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004921 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4922 IPCThreadState* ipc = IPCThreadState::self();
4923 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4924 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004925 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 }
Robert Carr1db73f62016-12-21 12:58:51 -08004927 return OK;
4928 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004930 IPCThreadState* ipc = IPCThreadState::self();
4931 const int pid = ipc->getCallingPid();
4932 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004933 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4934 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004935 return PERMISSION_DENIED;
4936 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 // Used by apps to hook Choreographer to SurfaceFlinger.
4940 case CREATE_DISPLAY_EVENT_CONNECTION:
4941 // The following calls are currently used by clients that do not
4942 // request necessary permissions. However, they do not expose any secret
4943 // information, so it is OK to pass them.
4944 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004945 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004947 case GET_PHYSICAL_DISPLAY_IDS:
4948 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004950 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 case GET_DISPLAY_CONFIGS:
4952 case GET_DISPLAY_STATS:
4953 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4954 // Calling setTransactionState is safe, because you need to have been
4955 // granted a reference to Client* and Handle* to do anything with it.
4956 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004957 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004958 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004959 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004960 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004961 case IS_WIDE_COLOR_DISPLAY:
4962 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4963 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964 return OK;
4965 }
4966 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004967 case CAPTURE_SCREEN:
4968 case ADD_REGION_SAMPLING_LISTENER:
4969 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004971 IPCThreadState* ipc = IPCThreadState::self();
4972 const int pid = ipc->getCallingPid();
4973 const int uid = ipc->getCallingUid();
4974 if ((uid != AID_GRAPHICS) &&
4975 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4976 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4977 return PERMISSION_DENIED;
4978 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 return OK;
4980 }
4981 // The following codes are deprecated and should never be allowed to access SF.
4982 case CONNECT_DISPLAY_UNUSED:
4983 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4984 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4985 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988
4989 // These codes are used for the IBinder protocol to either interrogate the recipient
4990 // side of the transaction for its canonical interface descriptor or to dump its state.
4991 // We let them pass by default.
4992 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4993 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4994 code == IBinder::SYSPROPS_TRANSACTION) {
4995 return OK;
4996 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004997 // Numbers from 1000 to 1033 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 // in onTransact verifies that the user is root, and has access to use SF.
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004999 if (code >= 1000 && code <= 1033) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5001 return OK;
5002 }
5003 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5004 return PERMISSION_DENIED;
5005#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005006}
5007
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5009 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005010 status_t credentialCheck = CheckTransactCodeCredentials(code);
5011 if (credentialCheck != OK) {
5012 return credentialCheck;
5013 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5016 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005017 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005018 IPCThreadState* ipc = IPCThreadState::self();
5019 const int uid = ipc->getCallingUid();
5020 if (CC_UNLIKELY(uid != AID_SYSTEM
5021 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005022 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005023 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005024 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 return PERMISSION_DENIED;
5026 }
5027 int n;
5028 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005029 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005030 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 return NO_ERROR;
5032 case 1002: // SHOW_UPDATES
5033 n = data.readInt32();
5034 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005035 invalidateHwcGeometry();
5036 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005039 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005040 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005042 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005043 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005044 setTransactionFlags(
5045 eTransactionNeeded|
5046 eDisplayTransactionNeeded|
5047 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005048 return NO_ERROR;
5049 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005050 case 1006:{ // send empty update
5051 signalRefresh();
5052 return NO_ERROR;
5053 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005054 case 1008: // toggle use of hw composer
5055 n = data.readInt32();
5056 mDebugDisableHWC = n ? 1 : 0;
5057 invalidateHwcGeometry();
5058 repaintEverything();
5059 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005060 case 1009: // toggle use of transform hint
5061 n = data.readInt32();
5062 mDebugDisableTransformHint = n ? 1 : 0;
5063 invalidateHwcGeometry();
5064 repaintEverything();
5065 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005067 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005068 reply->writeInt32(0);
5069 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005070 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005071 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005072 return NO_ERROR;
5073 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005075 if (!display) {
5076 return NAME_NOT_FOUND;
5077 }
5078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005079 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005080 return NO_ERROR;
5081 }
5082 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005084 // daltonize
5085 n = data.readInt32();
5086 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005087 case 1:
5088 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5089 break;
5090 case 2:
5091 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5092 break;
5093 case 3:
5094 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5095 break;
5096 default:
5097 mDaltonizer.setType(ColorBlindnessType::None);
5098 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005099 }
5100 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005101 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005102 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005103 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005104 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005105
5106 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005107 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005108 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005109 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 // apply a color matrix
5112 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005114 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005115 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005116 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005117 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005118 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005119 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005120 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005121 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005122 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005123
5124 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5125 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005126 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005127 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5128 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5129 }
5130
Chia-I Wu28f320b2018-05-03 11:02:56 -07005131 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005132 return NO_ERROR;
5133 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005134 // This is an experimental interface
5135 // Needs to be shifted to proper binder interface when we productize
5136 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005137 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005138 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005139 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005140 return NO_ERROR;
5141 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005142 case 1017: {
5143 n = data.readInt32();
5144 mForceFullDamage = static_cast<bool>(n);
5145 return NO_ERROR;
5146 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005147 case 1018: { // Modify Choreographer's phase offset
5148 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005149 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005150 return NO_ERROR;
5151 }
5152 case 1019: { // Modify SurfaceFlinger's phase offset
5153 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005154 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005155 return NO_ERROR;
5156 }
Irvel468051e2016-06-13 16:44:44 -07005157 case 1020: { // Layer updates interceptor
5158 n = data.readInt32();
5159 if (n) {
5160 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005161 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005162 }
5163 else{
5164 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005165 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005166 }
5167 return NO_ERROR;
5168 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005169 case 1021: { // Disable HWC virtual displays
5170 n = data.readInt32();
5171 mUseHwcVirtualDisplays = !n;
5172 return NO_ERROR;
5173 }
Romain Guy0147a172017-06-01 13:53:56 -07005174 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005175 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005176 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005177
Chia-I Wu28f320b2018-05-03 11:02:56 -07005178 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005179 return NO_ERROR;
5180 }
Romain Guy54f154a2017-10-24 21:40:32 +01005181 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005182 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005183 invalidateHwcGeometry();
5184 repaintEverything();
5185 return NO_ERROR;
5186 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005187 // Deprecate, use 1030 to check whether the device is color managed.
5188 case 1024: {
5189 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005190 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005191 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005192 n = data.readInt32();
5193 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005194 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005195 Mutex::Autolock lock(mStateLock);
5196 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005197 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005198 reply->writeInt32(NO_ERROR);
5199 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005200 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005201 bool writeFile = false;
5202 {
5203 Mutex::Autolock lock(mStateLock);
5204 mTracingEnabledChanged = true;
5205 writeFile = mTracing.disable();
5206 }
5207
5208 if (writeFile) {
5209 reply->writeInt32(mTracing.writeToFile());
5210 } else {
5211 reply->writeInt32(NO_ERROR);
5212 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005213 }
5214 return NO_ERROR;
5215 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005216 case 1026: { // Get layer tracing status
5217 reply->writeBool(mTracing.isEnabled());
5218 return NO_ERROR;
5219 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005220 // Is a DisplayColorSetting supported?
5221 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005222 const auto display = getDefaultDisplayDevice();
5223 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005224 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005225 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005226
5227 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5228 switch (setting) {
5229 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005230 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005231 break;
5232 case DisplayColorSetting::UNMANAGED:
5233 reply->writeBool(true);
5234 break;
5235 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005236 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005237 break;
5238 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005239 reply->writeBool(
5240 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005241 break;
5242 }
5243 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005244 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005245 // Is VrFlinger active?
5246 case 1028: {
5247 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005248 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005249 return NO_ERROR;
5250 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005251 // Set buffer size for SF tracing (value in KB)
5252 case 1029: {
5253 n = data.readInt32();
5254 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5255 ALOGW("Invalid buffer size: %d KB", n);
5256 reply->writeInt32(BAD_VALUE);
5257 return BAD_VALUE;
5258 }
5259
5260 ALOGD("Updating trace buffer to %d KB", n);
5261 mTracing.setBufferSize(n * 1024);
5262 reply->writeInt32(NO_ERROR);
5263 return NO_ERROR;
5264 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005265 // Is device color managed?
5266 case 1030: {
5267 reply->writeBool(useColorManagement);
5268 return NO_ERROR;
5269 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005270 // Override default composition data space
5271 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5272 // && adb shell stop zygote && adb shell start zygote
5273 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5274 // adb shell stop zygote && adb shell start zygote
5275 case 1031: {
5276 Mutex::Autolock _l(mStateLock);
5277 n = data.readInt32();
5278 if (n) {
5279 n = data.readInt32();
5280 if (n) {
5281 Dataspace dataspace = static_cast<Dataspace>(n);
5282 if (!validateCompositionDataspace(dataspace)) {
5283 return BAD_VALUE;
5284 }
5285 mDefaultCompositionDataspace = dataspace;
5286 }
5287 n = data.readInt32();
5288 if (n) {
5289 Dataspace dataspace = static_cast<Dataspace>(n);
5290 if (!validateCompositionDataspace(dataspace)) {
5291 return BAD_VALUE;
5292 }
5293 mWideColorGamutCompositionDataspace = dataspace;
5294 }
5295 } else {
5296 // restore composition data space.
5297 mDefaultCompositionDataspace = defaultCompositionDataspace;
5298 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5299 }
5300 return NO_ERROR;
5301 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005302 case 1032: {
5303 n = data.readInt32();
5304 mDebugEnableProtectedContent = n;
5305 return NO_ERROR;
5306 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005307 // Set trace flags
5308 case 1033: {
5309 n = data.readUint32();
5310 ALOGD("Updating trace flags to 0x%x", n);
5311 mTracing.setTraceFlags(n);
5312 reply->writeInt32(NO_ERROR);
5313 return NO_ERROR;
5314 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005315 }
5316 }
5317 return err;
5318}
5319
Steven Thomas6d8110b2017-08-31 18:24:21 -07005320void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005321 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005322 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005323}
5324
Ana Krulec7d1d6832018-12-27 11:10:09 -08005325void SurfaceFlinger::repaintEverythingForHWC() {
5326 mRepaintEverything = true;
5327 mEventQueue->invalidateForHWC();
5328}
5329
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5331class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005332public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005333 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5334 ~WindowDisconnector() {
5335 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005336 }
5337
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005338private:
5339 ANativeWindow* mWindow;
5340 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005341};
5342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5345 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005346 uint32_t reqWidth, uint32_t reqHeight,
5347 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005348 ISurfaceComposer::Rotation rotation,
5349 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005350 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005351
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005352 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005353
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005354 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5355
Chia-I Wu20261cb2018-08-23 12:55:44 -07005356 sp<DisplayDevice> display;
5357 {
5358 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 display = getDisplayDeviceLocked(displayToken);
5361 if (!display) return BAD_VALUE;
5362
Chia-I Wucb023152018-08-28 12:57:23 -07005363 // set the requested width/height to the logical display viewport size
5364 // by default
5365 if (reqWidth == 0 || reqHeight == 0) {
5366 reqWidth = uint32_t(display->getViewport().width());
5367 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005368 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005369 }
5370
Peiyong Lin0e003c92018-09-17 11:09:51 -07005371 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005372 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005373
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005374 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5375 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005376 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5377 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005378}
5379
5380status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005381 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5382 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005383 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005384 ATRACE_CALL();
5385
5386 class LayerRenderArea : public RenderArea {
5387 public:
Robert Carr578038f2018-03-09 12:25:24 -08005388 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005389 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5390 bool childrenOnly)
5391 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005392 mLayer(layer),
5393 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005394 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005395 mFlinger(flinger),
5396 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005397 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005398 Rect getBounds() const override {
5399 const Layer::State& layerState(mLayer->getDrawingState());
5400 return mLayer->getBufferSize(layerState);
5401 }
Marissa Wall61c58622018-07-18 10:12:20 -07005402 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005403 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005404 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005405 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005406 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005407 }
chaviwa76b2712017-09-20 12:02:26 -07005408 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005409 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005410 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005411 Rect getSourceCrop() const override {
5412 if (mCrop.isEmpty()) {
5413 return getBounds();
5414 } else {
5415 return mCrop;
5416 }
5417 }
Robert Carr578038f2018-03-09 12:25:24 -08005418 class ReparentForDrawing {
5419 public:
5420 const sp<Layer>& oldParent;
5421 const sp<Layer>& newParent;
5422
Vishnu Nair4351ad52019-02-11 14:13:02 -08005423 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5424 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005425 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005426 // Compute and cache the bounds for the new parent layer.
5427 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005428 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005429 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005430 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005431 };
5432
5433 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005434 const Rect sourceCrop = getSourceCrop();
5435 // no need to check rotation because there is none
5436 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5437 sourceCrop.height() != getReqHeight();
5438
Robert Carr578038f2018-03-09 12:25:24 -08005439 if (!mChildrenOnly) {
5440 mTransform = mLayer->getTransform().inverse();
5441 drawLayers();
5442 } else {
5443 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005444 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005445 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005446 bounds.getWidth(), bounds.getHeight(), 0,
5447 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005448
Vishnu Nair4351ad52019-02-11 14:13:02 -08005449 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005450 drawLayers();
5451 }
5452 }
chaviwa76b2712017-09-20 12:02:26 -07005453
chaviwa76b2712017-09-20 12:02:26 -07005454 private:
chaviw7206d492017-11-10 16:16:12 -08005455 const sp<Layer> mLayer;
5456 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005457
5458 // In the "childrenOnly" case we reparent the children to a screenshot
5459 // layer which has no properties set and which does not draw.
5460 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005461 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005462 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005463
5464 SurfaceFlinger* mFlinger;
5465 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005466 };
5467
5468 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5469 auto parent = layerHandle->owner.promote();
5470
Robert Carr2e102c92018-10-23 12:11:15 -07005471 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005472 ALOGE("captureLayers called with a removed parent");
5473 return NAME_NOT_FOUND;
5474 }
5475
Robert Carr578038f2018-03-09 12:25:24 -08005476 const int uid = IPCThreadState::self()->getCallingUid();
5477 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005479 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5480 return PERMISSION_DENIED;
5481 }
5482
chaviw7206d492017-11-10 16:16:12 -08005483 Rect crop(sourceCrop);
5484 if (sourceCrop.width() <= 0) {
5485 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005486 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005487 }
5488
5489 if (sourceCrop.height() <= 0) {
5490 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005491 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005492 }
5493
5494 int32_t reqWidth = crop.width() * frameScale;
5495 int32_t reqHeight = crop.height() * frameScale;
5496
Chia-I Wu20261cb2018-08-23 12:55:44 -07005497 // really small crop or frameScale
5498 if (reqWidth <= 0) {
5499 reqWidth = 1;
5500 }
5501 if (reqHeight <= 0) {
5502 reqHeight = 1;
5503 }
5504
Peiyong Lin0e003c92018-09-17 11:09:51 -07005505 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005506
Robert Carr578038f2018-03-09 12:25:24 -08005507 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005508 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5509 if (!layer->isVisible()) {
5510 return;
Robert Carr578038f2018-03-09 12:25:24 -08005511 } else if (childrenOnly && layer == parent.get()) {
5512 return;
chaviwa76b2712017-09-20 12:02:26 -07005513 }
5514 visitor(layer);
5515 });
5516 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005517 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005518}
5519
5520status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5521 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005522 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005523 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005524 bool useIdentityTransform) {
5525 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005526
Peiyong Lin0e003c92018-09-17 11:09:51 -07005527 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005528 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5529 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005530 *outBuffer =
5531 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5532 static_cast<android_pixel_format>(reqPixelFormat), 1,
5533 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005534
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005535 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005536}
5537
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005538status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5539 TraverseLayersFunction traverseLayers,
5540 const sp<GraphicBuffer>& buffer,
5541 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005542 // This mutex protects syncFd and captureResult for communication of the return values from the
5543 // main thread back to this Binder thread
5544 std::mutex captureMutex;
5545 std::condition_variable captureCondition;
5546 std::unique_lock<std::mutex> captureLock(captureMutex);
5547 int syncFd = -1;
5548 std::optional<status_t> captureResult;
5549
Robert Carr03480e22018-01-04 16:02:06 -08005550 const int uid = IPCThreadState::self()->getCallingUid();
5551 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5552
Dominik Laskowski8c001672018-05-30 16:52:06 -07005553 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554 // If there is a refresh pending, bug out early and tell the binder thread to try again
5555 // after the refresh.
5556 if (mRefreshPending) {
5557 ATRACE_NAME("Skipping screenshot for now");
5558 std::unique_lock<std::mutex> captureLock(captureMutex);
5559 captureResult = std::make_optional<status_t>(EAGAIN);
5560 captureCondition.notify_one();
5561 return;
5562 }
5563
5564 status_t result = NO_ERROR;
5565 int fd = -1;
5566 {
5567 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005568 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005569 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005570 useIdentityTransform, forSystem, &fd);
5571 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005572 }
5573
5574 {
5575 std::unique_lock<std::mutex> captureLock(captureMutex);
5576 syncFd = fd;
5577 captureResult = std::make_optional<status_t>(result);
5578 captureCondition.notify_one();
5579 }
5580 });
5581
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005582 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005584 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005585 while (*captureResult == EAGAIN) {
5586 captureResult.reset();
5587 result = postMessageAsync(message);
5588 if (result != NO_ERROR) {
5589 return result;
5590 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005591 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005592 }
5593 result = *captureResult;
5594 }
5595
5596 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005597 sync_wait(syncFd, -1);
5598 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005599 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005600
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005602}
5603
chaviwa76b2712017-09-20 12:02:26 -07005604void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005605 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005606 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5607 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005608 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005609
chaviwa76b2712017-09-20 12:02:26 -07005610 const auto reqWidth = renderArea.getReqWidth();
5611 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005612 const auto sourceCrop = renderArea.getSourceCrop();
5613 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005614
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005615 renderengine::DisplaySettings clientCompositionDisplay;
5616 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005617
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005618 // assume that bounds are never offset, and that they are the same as the
5619 // buffer bounds.
5620 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5621 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005622 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005623 mat4 rotMatrix;
5624 // Displacement for repositioning the clipping rectangle after rotating it
5625 // with the rotation hint.
5626 int displacementX = 0;
5627 int displacementY = 0;
5628 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5629 switch (rotation) {
5630 case ui::Transform::ROT_90:
5631 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5632 displacementX = reqWidth;
5633 break;
5634 case ui::Transform::ROT_180:
5635 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5636 displacementX = reqWidth;
5637 displacementY = reqHeight;
5638 break;
5639 case ui::Transform::ROT_270:
5640 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5641 displacementY = reqHeight;
5642 break;
5643 default:
5644 break;
5645 }
5646 // We need to transform the clipping window into the right spot.
5647 // First, rotate the clipping rectangle by the rotation hint to get the
5648 // right orientation
5649 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5650 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5651 const vec4 rotClipTL = rotMatrix * clipTL;
5652 const vec4 rotClipBR = rotMatrix * clipBR;
5653 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5654 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5655 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5656 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5657
5658 // Now reposition the clipping rectangle with the displacement vector
5659 // computed above.
5660 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5661
5662 clientCompositionDisplay.clip =
5663 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5664 newClipRight + displacementX, newClipBottom + displacementY);
5665
5666 // We need to perform the same transformation in layer space, so propagate
5667 // it to the global transform.
5668 mat4 clipTransform = displacementMat * rotMatrix;
5669 clientCompositionDisplay.globalTransform *= clipTransform;
5670 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5671 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672
chaviw50da5042018-04-09 13:49:37 -07005673 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005674
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675 renderengine::LayerSettings fillLayer;
5676 fillLayer.source.buffer.buffer = nullptr;
5677 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5678 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5679 fillLayer.alpha = half(alpha);
5680 clientCompositionLayers.push_back(fillLayer);
5681
5682 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005683 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005684 renderengine::LayerSettings layerSettings;
5685 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005686 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005687 if (prepared) {
5688 clientCompositionLayers.push_back(layerSettings);
5689 }
chaviwa76b2712017-09-20 12:02:26 -07005690 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005691
5692 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005693 // Use an empty fence for the buffer fence, since we just created the buffer so
5694 // there is no need for synchronization with the GPU.
5695 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005696 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005697 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005698 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005699 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005700
5701 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005702}
5703
chaviwa76b2712017-09-20 12:02:26 -07005704status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5705 TraverseLayersFunction traverseLayers,
5706 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005707 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005708 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005709 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005710 ATRACE_CALL();
5711
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005712 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005713
5714 traverseLayers([&](Layer* layer) {
5715 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5716 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005717
Robert Carr03480e22018-01-04 16:02:06 -08005718 // We allow the system server to take screenshots of secure layers for
5719 // use in situations like the Screen-rotation animation and place
5720 // the impetus on WindowManager to not persist them.
5721 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005722 ALOGW("FB is protected: PERMISSION_DENIED");
5723 return PERMISSION_DENIED;
5724 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005725 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005726 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005727}
5728
chaviw95ef3c42019-02-14 10:55:09 -08005729void SurfaceFlinger::setInputWindowsFinished() {
5730 Mutex::Autolock _l(mStateLock);
5731
5732 mPendingSyncInputWindows = false;
5733 mTransactionCV.broadcast();
5734}
chaviw5f21a5e2019-02-14 10:00:34 -08005735
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005736// ---------------------------------------------------------------------------
5737
Dan Stoza412903f2017-04-27 13:42:17 -07005738void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5739 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005740}
5741
Dan Stoza412903f2017-04-27 13:42:17 -07005742void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5743 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005744}
5745
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005746void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005747 const LayerVector::Visitor& visitor) {
5748 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005749 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005750 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005751 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005752 continue;
5753 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005754 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005755 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005756 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005757 return;
5758 }
chaviwa76b2712017-09-20 12:02:26 -07005759 if (!layer->isVisible()) {
5760 return;
5761 }
5762 visitor(layer);
5763 });
5764 }
5765}
5766
Ady Abraham838de062019-02-04 10:24:03 -08005767void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5768 const android::sp<android::IBinder>& displayToken,
5769 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5770 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5771 if (!displayId) {
5772 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5773 return;
5774 }
5775
5776 ALOGV("Updating allowed configs");
5777 {
5778 std::lock_guard lock(mAllowedConfigsLock);
5779 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5780 }
5781
5782 // make sure that the current config is still allowed
5783 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5784 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005785 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
5786 if (isConfigAllowed(*displayId, config.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005787 // TODO: we switch to the first allowed config. In the future
5788 // we may want to enhance this logic to pick a similar config
5789 // to the current one
Ady Abraham1902d072019-03-01 17:18:59 -08005790 ALOGV("Old config is not allowed - switching to config %d", config.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005791 setDesiredActiveConfig(displayToken, config.configId,
5792 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005793 break;
5794 }
5795 }
5796 }
Ady Abraham97d04232019-03-05 19:48:12 -08005797
5798 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5799 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5800 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
5801 const auto performanceRefreshRate =
5802 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
5803 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ady Abraham97d04232019-03-05 19:48:12 -08005804 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5805 }
5806 }
Ady Abraham838de062019-02-04 10:24:03 -08005807}
5808
5809status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5810 const std::vector<int32_t>& allowedConfigs) {
5811 ATRACE_CALL();
5812
5813 if (!displayToken) {
5814 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5815 return BAD_VALUE;
5816 }
5817
5818 if (!allowedConfigs.size()) {
5819 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5820 return BAD_VALUE;
5821 }
5822
5823 {
5824 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5825 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5826 if (!displayId) {
5827 ALOGE("setAllowedDisplayConfigs: display not found");
5828 return NAME_NOT_FOUND;
5829 }
5830 }
5831
5832 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5833 for (int config : allowedConfigs) {
5834 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5835 allowedDisplayConfigsBuilder.addConfig(config);
5836 }
5837 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5838 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5839 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5840 }));
5841 return NO_ERROR;
5842}
5843
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005844status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5845 std::vector<int32_t>* outAllowedConfigs) {
5846 ATRACE_CALL();
5847
5848 if (!displayToken) {
5849 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5850 return BAD_VALUE;
5851 }
5852
5853 if (!outAllowedConfigs) {
5854 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5855 return BAD_VALUE;
5856 }
5857
5858 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5859 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5860 if (!displayId) {
5861 ALOGE("getAllowedDisplayConfigs: display not found");
5862 return NAME_NOT_FOUND;
5863 }
5864
5865 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5866 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5867 if (allowedConfigIterator != mAllowedConfigs.end()) {
5868 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5869 }
5870
5871 return NO_ERROR;
5872}
5873
chaviw291d88a2019-02-14 10:33:58 -08005874// ----------------------------------------------------------------------------
5875
5876void SetInputWindowsListener::onSetInputWindowsFinished() {
5877 mFlinger->setInputWindowsFinished();
5878}
5879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005880}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005881
Lloyd Pique074e8122018-07-26 12:57:23 -07005882
Mathias Agopian3f844832013-08-07 21:24:32 -07005883#if defined(__gl_h_)
5884#error "don't include gl/gl.h in this file"
5885#endif
5886
5887#if defined(__gl2_h_)
5888#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005889#endif