blob: 7061ad61da62dedc4ef9d2a8f6f7d6967a68536c [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"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
113#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900114#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
chaviw1d044282017-09-27 12:19:28 -0700116#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900117#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120
Jaesoo Lee43518572017-01-23 19:03:16 +0900121using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800124
Yiwei Zhang5434a782018-12-05 18:06:32 -0800125using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700126using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700127using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800128using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700129using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700130using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131
Steven Thomasb02664d2017-07-26 18:48:28 -0700132namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700133
134#pragma clang diagnostic push
135#pragma clang diagnostic error "-Wswitch-enum"
136
137bool isWideColorMode(const ColorMode colorMode) {
138 switch (colorMode) {
139 case ColorMode::DISPLAY_P3:
140 case ColorMode::ADOBE_RGB:
141 case ColorMode::DCI_P3:
142 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700143 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700144 case ColorMode::BT2100_PQ:
145 case ColorMode::BT2100_HLG:
146 return true;
147 case ColorMode::NATIVE:
148 case ColorMode::STANDARD_BT601_625:
149 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
150 case ColorMode::STANDARD_BT601_525:
151 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
152 case ColorMode::STANDARD_BT709:
153 case ColorMode::SRGB:
154 return false;
155 }
156 return false;
157}
158
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700159bool isHdrColorMode(const ColorMode colorMode) {
160 switch (colorMode) {
161 case ColorMode::BT2100_PQ:
162 case ColorMode::BT2100_HLG:
163 return true;
164 case ColorMode::DISPLAY_P3:
165 case ColorMode::ADOBE_RGB:
166 case ColorMode::DCI_P3:
167 case ColorMode::BT2020:
168 case ColorMode::DISPLAY_BT2020:
169 case ColorMode::NATIVE:
170 case ColorMode::STANDARD_BT601_625:
171 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
172 case ColorMode::STANDARD_BT601_525:
173 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
174 case ColorMode::STANDARD_BT709:
175 case ColorMode::SRGB:
176 return false;
177 }
178 return false;
179}
180
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700181ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
182 switch (rotation) {
183 case ISurfaceComposer::eRotateNone:
184 return ui::Transform::ROT_0;
185 case ISurfaceComposer::eRotate90:
186 return ui::Transform::ROT_90;
187 case ISurfaceComposer::eRotate180:
188 return ui::Transform::ROT_180;
189 case ISurfaceComposer::eRotate270:
190 return ui::Transform::ROT_270;
191 }
192 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
193 return ui::Transform::ROT_0;
194}
195
Peiyong Linfca547f2018-07-09 13:03:33 -0700196#pragma clang diagnostic pop
197
Steven Thomasb02664d2017-07-26 18:48:28 -0700198class ConditionalLock {
199public:
200 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
201 if (lock) {
202 mMutex.lock();
203 }
204 }
205 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
206private:
207 Mutex& mMutex;
208 bool mLocked;
209};
Peiyong Linfca547f2018-07-09 13:03:33 -0700210
Peiyong Lin9d846a52018-11-05 13:18:20 -0800211// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
212bool validateCompositionDataspace(Dataspace dataspace) {
213 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
214}
215
Steven Thomasb02664d2017-07-26 18:48:28 -0700216} // namespace anonymous
217
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218// ---------------------------------------------------------------------------
219
Mathias Agopian99b49842011-06-27 16:05:52 -0700220const String16 sHardwareTest("android.permission.HARDWARE_TEST");
221const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
222const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
223const String16 sDump("android.permission.DUMP");
224
225// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700226int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700227bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800228uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800229bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800230bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800231int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600232bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700233int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700234bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700235bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700236Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
237ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
238Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
239ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700240
Kalle Raitaa099a242017-01-11 11:17:29 -0800241std::string getHwcServiceName() {
242 char value[PROPERTY_VALUE_MAX] = {};
243 property_get("debug.sf.hwc_service_name", value, "default");
244 ALOGI("Using HWComposer service: '%s'", value);
245 return std::string(value);
246}
247
248bool useTrebleTestingOverride() {
249 char value[PROPERTY_VALUE_MAX] = {};
250 property_get("debug.sf.treble_testing_override", value, "false");
251 ALOGI("Treble testing override: '%s'", value);
252 return std::string(value) == "true";
253}
254
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
256 switch(displayColorSetting) {
257 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Enhanced");
263 default:
264 return std::string("Unknown ") +
265 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800266 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267}
268
David Sodmanbc815282017-11-05 18:57:52 -0800269SurfaceFlingerBE::SurfaceFlingerBE()
270 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800271 mFrameBuckets(),
272 mTotalTime(0),
273 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800274 mComposerSequenceId(0) {
275}
276
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
278 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800279 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700280 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700281 mTransactionPending(false),
282 mAnimTransactionPending(false),
Marissa Wall06255332019-03-27 13:48:27 -0700283 mTraversalNeededMainThread(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
Alec Mouri0a1cc962019-03-14 12:33:02 -0700595 const auto& performanceRefreshRate =
Ady Abraham97d04232019-03-05 19:48:12 -0800596 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
597
Alec Mouri0a1cc962019-03-14 12:33:02 -0700598 if (performanceRefreshRate &&
599 isConfigAllowed(*displayId, performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800600 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800601 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800602 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800603 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800604 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800605}
606
Dan Stoza436ccf32018-06-21 12:10:12 -0700607uint32_t SurfaceFlinger::getNewTexture() {
608 {
609 std::lock_guard lock(mTexturePoolMutex);
610 if (!mTexturePool.empty()) {
611 uint32_t name = mTexturePool.back();
612 mTexturePool.pop_back();
613 ATRACE_INT("TexturePoolSize", mTexturePool.size());
614 return name;
615 }
616
617 // The pool was too small, so increase it for the future
618 ++mTexturePoolSize;
619 }
620
621 // The pool was empty, so we need to get a new texture name directly using a
622 // blocking call to the main thread
623 uint32_t name = 0;
624 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
625 return name;
626}
627
Mathias Agopian3f844832013-08-07 21:24:32 -0700628void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700630}
631
Wei Wangf9b05ee2017-07-19 20:59:39 -0700632// Do not call property_set on main thread which will be blocked by init
633// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700635 ALOGI( "SurfaceFlinger's main thread ready to run. "
636 "Initializing graphics H/W...");
637
Ana Krulec757f63a2019-01-25 10:46:18 -0800638 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900639
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800642 mScheduler =
643 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
644 auto resyncCallback =
645 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800646
Ana Krulecc2870422019-01-29 19:00:58 -0800647 mAppConnectionHandle =
648 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
649 resyncCallback,
650 impl::EventThread::InterceptVSyncsCallback());
651 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
652 resyncCallback, [this](nsecs_t timestamp) {
653 mInterceptor->saveVSyncEvent(timestamp);
654 });
655
656 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
657 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
658 mSfConnectionHandle.get());
659
Kevin DuBois413287f2019-02-25 08:46:47 -0800660 mRegionSamplingThread =
661 new RegionSamplingThread(*this, *mScheduler,
662 RegionSamplingThread::EnvironmentTimingTunables());
663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800672 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800675 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Mathias Agopian92a979a2012-08-02 18:32:23 -0700712 // initialize our drawing state
713 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700714
Andy McFadden13a082e2012-08-24 10:16:42 -0700715 // set initial conditions (e.g. unblank default device)
716 initializeDisplays();
717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700719
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700721
722 const bool presentFenceReliable =
723 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
724 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725
726 if (mStartPropertySetThread->Start() != NO_ERROR) {
727 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729
Ady Abraham97d04232019-03-05 19:48:12 -0800730 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800731 mScheduler->setChangeRefreshRateCallback(
732 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
733 Mutex::Autolock lock(mStateLock);
734 setRefreshRateTo(type, event);
735 });
Kevin DuBois36233132019-02-19 14:08:55 -0800736 }
Ady Abraham1902d072019-03-01 17:18:59 -0800737 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
738 getHwComposer().getConfigs(*display->getId()));
739 mRefreshRateStats =
740 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
741 mTimeStats);
Alec Mouri62c8bd12019-03-22 15:55:23 -0700742 mRefreshRateStats->setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700745}
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 Mutex::Autolock _l(mStateLock);
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750 char value[PROPERTY_VALUE_MAX];
751
752 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700754 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100756
757 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700758 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800759
760 property_get("persist.sys.sf.color_mode", value, "0");
761 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800817status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800823 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 if (!displayId) {
825 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 // TODO: Not sure if display density should handled by SF any longer
829 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700832 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800833 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836 return density;
837 }
838 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("ro.sf.lcd_density"); }
843 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800859 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800895 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800909 info.presentationDeadline =
910 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800915 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulecc2870422019-01-29 19:00:58 -0800931 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Ady Abraham03b02dd2019-03-21 15:40:11 -0700945void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948 // Lock is acquired by setRefreshRateTo.
Ady Abraham03b02dd2019-03-21 15:40:11 -0700949 const auto display = getDisplayDeviceLocked(info.displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950 if (!display) {
Ady Abraham03b02dd2019-03-21 15:40:11 -0700951 ALOGE("Attempt to set active config %d for invalid display token %p", info.configId,
952 info.displayToken.get());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800953 return;
954 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700955 if (display->isVirtual()) {
Ady Abraham03b02dd2019-03-21 15:40:11 -0700956 ALOGW("Attempt to set active config %d for virtual display", info.configId);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800957 return;
958 }
959 int currentDisplayPowerMode = display->getPowerMode();
960 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
961 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700962 return;
963 }
964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800966 // config twice. However event generation config might have changed so we need to update it
967 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700969 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
970 mDesiredActiveConfig = info;
971 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972
973 if (!mDesiredActiveConfigChanged) {
974 // This is the first time we set the desired
975 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
976
977 // This will trigger HWC refresh without resetting the idle timer.
978 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800980 mDesiredActiveConfigChanged = true;
981 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700982
983 if (mRefreshRateOverlay) {
984 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
985 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986}
987
988status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
989 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800990
991 std::vector<int32_t> allowedConfig;
992 allowedConfig.push_back(mode);
993
994 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995}
996
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997void SurfaceFlinger::setActiveConfigInternal() {
998 ATRACE_CALL();
999
1000 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -08001001 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002
1003 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1004 display->setActiveConfig(mUpcomingActiveConfig.configId);
1005
Ana Krulecc2870422019-01-29 19:00:58 -08001006 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001007 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1008 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001009 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001010 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001011 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1012 mUpcomingActiveConfig.configId);
1013 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001014}
1015
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001017 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 if (mCheckPendingFence) {
1019 if (mPreviousPresentFence != Fence::NO_FENCE &&
1020 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1021 // fence has not signaled yet. wait for the next invalidate
1022 repaintEverythingForHWC();
1023 return true;
1024 }
1025
1026 // We received the present fence from the HWC, so we assume it successfully updated
1027 // the config, hence we update SF.
1028 mCheckPendingFence = false;
1029 setActiveConfigInternal();
1030 }
1031
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001032 // Store the local variable to release the lock.
1033 ActiveConfigInfo desiredActiveConfig;
1034 {
1035 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 if (!mDesiredActiveConfigChanged) {
1037 return false;
1038 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 desiredActiveConfig = mDesiredActiveConfig;
1040 }
1041
1042 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1044 // display is not valid or we are already in the requested mode
1045 // on both cases there is nothing left to do
1046 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1047 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
Ady Abrahamde3b67b2019-03-25 16:38:10 -07001048 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 mDesiredActiveConfigChanged = false;
1050 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1051 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001052 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001053
Ady Abraham838de062019-02-04 10:24:03 -08001054 // Desired active config was set, it is different than the config currently in use, however
1055 // allowed configs might have change by the time we process the refresh.
1056 // Make sure the desired config is still allowed
1057 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1058 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1059 mDesiredActiveConfig.configId = display->getActiveConfig();
1060 return false;
1061 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001062 mUpcomingActiveConfig = desiredActiveConfig;
1063 const auto displayId = display->getId();
1064 LOG_ALWAYS_FATAL_IF(!displayId);
1065
1066 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1067 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1068
1069 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001070 mCheckPendingFence = true;
1071
1072 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001073}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1076 Vector<ColorMode>* outColorModes) {
1077 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001078 return BAD_VALUE;
1079 }
1080
Peiyong Lina52f0292018-03-14 17:26:31 -07001081 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001082 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001083 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1084
1085 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1086 if (!displayId) {
1087 return NAME_NOT_FOUND;
1088 }
1089
Dominik Laskowski075d3172018-05-24 15:50:06 -07001090 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001091 }
Michael Wright28f24d02016-07-12 13:30:53 -07001092 outColorModes->clear();
1093 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1094
1095 return NO_ERROR;
1096}
1097
Daniel Solomon42d04562019-01-20 21:03:19 -08001098status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1099 ui::DisplayPrimaries &primaries) {
1100 if (!displayToken) {
1101 return BAD_VALUE;
1102 }
1103
1104 // Currently we only support this API for a single internal display.
1105 if (getInternalDisplayToken() != displayToken) {
1106 return BAD_VALUE;
1107 }
1108
1109 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1110 return NO_ERROR;
1111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1114 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001115 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001116 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001117 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001118}
1119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001121 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 Vector<ColorMode> modes;
1123 getDisplayColorModes(displayToken, &modes);
1124 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1125 if (mode < ColorMode::NATIVE || !exists) {
1126 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1127 decodeColorMode(mode).c_str(), mode, displayToken.get());
1128 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001129 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130 const auto display = getDisplayDevice(displayToken);
1131 if (!display) {
1132 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1133 decodeColorMode(mode).c_str(), mode, displayToken.get());
1134 } else if (display->isVirtual()) {
1135 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1136 decodeColorMode(mode).c_str(), mode);
1137 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001138 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1139 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001140 }
1141 }));
1142
Michael Wright28f24d02016-07-12 13:30:53 -07001143 return NO_ERROR;
1144}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001145
Svetoslavd85084b2014-03-20 10:28:31 -07001146status_t SurfaceFlinger::clearAnimationFrameStats() {
1147 Mutex::Autolock _l(mStateLock);
1148 mAnimFrameTracker.clearStats();
1149 return NO_ERROR;
1150}
1151
1152status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1153 Mutex::Autolock _l(mStateLock);
1154 mAnimFrameTracker.getStats(outStats);
1155 return NO_ERROR;
1156}
1157
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1159 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001160 Mutex::Autolock _l(mStateLock);
1161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001162 const auto display = getDisplayDeviceLocked(displayToken);
1163 if (!display) {
1164 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001165 return BAD_VALUE;
1166 }
1167
Peiyong Linfb069302018-04-25 14:34:31 -07001168 // At this point the DisplayDeivce should already be set up,
1169 // meaning the luminance information is already queried from
1170 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001172 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1173 capabilities.getDesiredMaxLuminance(),
1174 capabilities.getDesiredMaxAverageLuminance(),
1175 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001176
1177 return NO_ERROR;
1178}
1179
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001180status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1181 ui::PixelFormat* outFormat,
1182 ui::Dataspace* outDataspace,
1183 uint8_t* outComponentMask) const {
1184 if (!outFormat || !outDataspace || !outComponentMask) {
1185 return BAD_VALUE;
1186 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001187 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001188 if (!display || !display->getId()) {
1189 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1190 return BAD_VALUE;
1191 }
1192 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1193 outDataspace, outComponentMask);
1194}
1195
Kevin DuBois74e53772018-11-19 10:52:38 -08001196status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1197 bool enable, uint8_t componentMask,
1198 uint64_t maxFrames) const {
1199 const auto display = getDisplayDevice(displayToken);
1200 if (!display || !display->getId()) {
1201 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1202 return BAD_VALUE;
1203 }
1204
1205 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1206 componentMask, maxFrames);
1207}
1208
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001209status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1210 uint64_t maxFrames, uint64_t timestamp,
1211 DisplayedFrameStats* outStats) const {
1212 const auto display = getDisplayDevice(displayToken);
1213 if (!display || !display->getId()) {
1214 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1215 return BAD_VALUE;
1216 }
1217
1218 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1219 outStats);
1220}
1221
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001222status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1223 if (!outSupported) {
1224 return BAD_VALUE;
1225 }
1226 *outSupported = getRenderEngine().supportsProtectedContent();
1227 return NO_ERROR;
1228}
1229
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001230status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1231 bool* outIsWideColorDisplay) const {
1232 if (!displayToken || !outIsWideColorDisplay) {
1233 return BAD_VALUE;
1234 }
1235 Mutex::Autolock _l(mStateLock);
1236 const auto display = getDisplayDeviceLocked(displayToken);
1237 if (!display) {
1238 return BAD_VALUE;
1239 }
1240 *outIsWideColorDisplay = display->hasWideColorGamut();
1241 return NO_ERROR;
1242}
1243
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001245 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001247
Chia-I Wu90f669f2017-10-05 14:24:41 -07001248 if (mInjectVSyncs == enable) {
1249 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001250 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001251
Ana Krulecc2870422019-01-29 19:00:58 -08001252 auto resyncCallback =
1253 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001255 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001256 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257 if (enable) {
1258 ALOGV("VSync Injections enabled");
1259 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001260 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001261 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001263 impl::EventThread::InterceptVSyncsCallback(),
1264 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001266 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001267 } else {
1268 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001269 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1270 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 }
1272
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001274 }));
1275
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001280 Mutex::Autolock _l(mStateLock);
1281
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282 if (!mInjectVSyncs) {
1283 ALOGE("VSync Injections not enabled");
1284 return BAD_VALUE;
1285 }
1286 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1287 ALOGV("Injecting VSync inside SurfaceFlinger");
1288 mVSyncInjector->onInjectSyncEvent(when);
1289 }
1290 return NO_ERROR;
1291}
1292
Lloyd Pique755e3192018-01-31 16:46:15 -08001293status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1294 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001295 // Try to acquire a lock for 1s, fail gracefully
1296 const status_t err = mStateLock.timedLock(s2ns(1));
1297 const bool locked = (err == NO_ERROR);
1298 if (!locked) {
1299 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1300 return TIMED_OUT;
1301 }
1302
1303 outLayers->clear();
1304 mCurrentState.traverseInZOrder([&](Layer* layer) {
1305 outLayers->push_back(layer->getLayerDebugInfo());
1306 });
1307
1308 mStateLock.unlock();
1309 return NO_ERROR;
1310}
1311
Peiyong Linc6780972018-10-28 15:24:08 -07001312status_t SurfaceFlinger::getCompositionPreference(
1313 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1314 Dataspace* outWideColorGamutDataspace,
1315 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001316 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001317 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001318 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001319 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001320 return NO_ERROR;
1321}
1322
Dan Stozaec460082018-12-17 15:35:09 -08001323status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1324 const sp<IBinder>& stopLayerHandle,
1325 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001326 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001327 return BAD_VALUE;
1328 }
1329 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001330 return NO_ERROR;
1331}
1332
Dan Stozaec460082018-12-17 15:35:09 -08001333status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001334 if (!listener) {
1335 return BAD_VALUE;
1336 }
Dan Stozaec460082018-12-17 15:35:09 -08001337 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001338 return NO_ERROR;
1339}
Dan Gittik57e63c52019-01-18 16:37:54 +00001340
1341status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1342 bool* outSupport) const {
1343 if (!displayToken || !outSupport) {
1344 return BAD_VALUE;
1345 }
1346 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1347 if (!displayId) {
1348 return NAME_NOT_FOUND;
1349 }
1350 *outSupport =
1351 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1352 return NO_ERROR;
1353}
1354
1355status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1356 float brightness) const {
1357 if (!displayToken) {
1358 return BAD_VALUE;
1359 }
1360 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1361 if (!displayId) {
1362 return NAME_NOT_FOUND;
1363 }
1364 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1365}
1366
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001367// ----------------------------------------------------------------------------
1368
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001369sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1370 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001371 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001372 Mutex::Autolock lock(mStateLock);
1373 return getVsyncPeriod();
1374 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001375
Ana Krulecc2870422019-01-29 19:00:58 -08001376 const auto& handle =
1377 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001378
Ana Krulecc2870422019-01-29 19:00:58 -08001379 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001380}
1381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001383
1384void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001385 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386}
1387
1388void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001389 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001390}
1391
1392void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001393 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001394}
1395
1396void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001397 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001398 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001399}
1400
1401status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001402 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001403 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001404}
1405
1406status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001407 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001408 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001409 if (res == NO_ERROR) {
1410 msg->wait();
1411 }
1412 return res;
1413}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001414
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001415void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001416 do {
1417 waitForEvent();
1418 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001419}
1420
Dominik Laskowski83b88212018-12-11 13:34:06 -08001421nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001422 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001423 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1424 return 0;
1425 }
1426
1427 const auto config = getHwComposer().getActiveConfig(*displayId);
1428 return config ? config->getVsyncPeriod() : 0;
1429}
1430
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001431void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1432 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001433 ATRACE_NAME("SF onVsync");
1434
Steven Thomas3cfac282017-02-06 12:29:30 -08001435 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001437 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 return;
1439 }
1440
Dominik Laskowski075d3172018-05-24 15:50:06 -07001441 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001442 return;
1443 }
1444
Dominik Laskowski075d3172018-05-24 15:50:06 -07001445 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 // For now, we don't do anything with external display vsyncs.
1447 return;
1448 }
1449
Ana Krulecc2870422019-01-29 19:00:58 -08001450 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001451}
1452
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001453void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001454 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1455 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001456}
1457
Ady Abraham838de062019-02-04 10:24:03 -08001458bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1459 std::lock_guard lock(mAllowedConfigsLock);
1460
1461 // if allowed configs are not set yet for this display, every config is considered allowed
1462 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1463 return true;
1464 }
1465
1466 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1467}
1468
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001469void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001470 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001471 return;
1472 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001473 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001474
Ana Krulec7d1d6832018-12-27 11:10:09 -08001475 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001476 const auto displayId = getInternalDisplayIdLocked();
1477 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001478 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001479
Alec Mouri0a1cc962019-03-14 12:33:02 -07001480 const auto& refreshRateConfig = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate);
1481 if (!refreshRateConfig) {
1482 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001483 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001484 }
Ady Abraham1902d072019-03-01 17:18:59 -08001485
Alec Mouri0a1cc962019-03-14 12:33:02 -07001486 const int desiredConfigId = refreshRateConfig->configId;
1487
Ady Abraham1902d072019-03-01 17:18:59 -08001488 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1489 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1490 return;
1491 }
1492
Alec Mouri0a1cc962019-03-14 12:33:02 -07001493 const auto display = getDisplayDeviceLocked(displayToken);
1494 if (desiredConfigId == display->getActiveConfig()) {
1495 return;
1496 }
1497
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001498 mPhaseOffsets->setRefreshRateType(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001499 setDesiredActiveConfig({refreshRate, desiredConfigId, getInternalDisplayTokenLocked(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001500}
1501
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001502void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001503 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001504 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001505 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001506
Lloyd Piqueba04e622017-12-14 17:11:26 -08001507 // Ignore events that do not have the right sequenceId.
1508 if (sequenceId != getBE().mComposerSequenceId) {
1509 return;
1510 }
1511
Steven Thomasb02664d2017-07-26 18:48:28 -07001512 // Only lock if we're not on the main thread. This function is normally
1513 // called on a hwbinder thread, but for the primary display it's called on
1514 // the main thread with the state lock already held, so don't attempt to
1515 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001516 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001517
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001518 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001519
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001520 if (std::this_thread::get_id() == mMainThreadId) {
1521 // Process all pending hot plug events immediately if we are on the main thread.
1522 processDisplayHotplugEventsLocked();
1523 }
1524
Lloyd Piqueba04e622017-12-14 17:11:26 -08001525 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001526}
1527
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001528void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001529 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001530 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001532 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001533 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001534}
1535
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001536void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001537 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001538 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001539 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001540 getHwComposer().setVsyncEnabled(*displayId,
1541 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1542 }
Mathias Agopian86303202012-07-24 22:46:10 -07001543}
1544
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001546void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001547 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548 // Clear the drawing state so that the logic inside of
1549 // handleTransactionLocked will fire. It will determine the delta between
1550 // mCurrentState and mDrawingState and re-apply all changes when we make the
1551 // transition.
1552 mDrawingState.displays.clear();
1553 mDisplays.clear();
1554}
1555
Steven Thomas050b2c82017-03-06 11:45:16 -08001556void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001557 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001558 if (!mVrFlinger)
1559 return;
1560 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001562 return;
1563 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001564
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 ALOGE("Vr flinger is only supported for remote hardware composer"
1567 " service connections. Ignoring request to transition to vr"
1568 " flinger.");
1569 mVrFlingerRequestsDisplay = false;
1570 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001571 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001573 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574
Steven Thomas0123ac62018-07-12 11:32:34 -07001575 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001576 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001577
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001578 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001579
1580 // Clear out all the output layers from the composition engine for all
1581 // displays before destroying the hardware composer interface. This ensures
1582 // any HWC layers are destroyed through that interface before it becomes
1583 // invalid.
1584 for (const auto& [token, displayDevice] : mDisplays) {
1585 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1586 compositionengine::Output::OutputLayers());
1587 }
1588
Steven Thomas0123ac62018-07-12 11:32:34 -07001589 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1590 // called below. Clear the reference now so we don't accidentally use it
1591 // later.
1592 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593
Steven Thomasb02664d2017-07-26 18:48:28 -07001594 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001596 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597
Steven Thomasb02664d2017-07-26 18:48:28 -07001598 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001599 // Delete the current instance before creating the new one
1600 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1601 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1602 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1603 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001604
Lloyd Pique441d5042018-10-18 16:49:51 -07001605 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001606 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001607
1608 if (vrFlingerRequestsDisplay) {
1609 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001610 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001611
1612 mVisibleRegionsDirty = true;
1613 invalidateHwcGeometry();
1614
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001615 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001616 display = getDefaultDisplayDeviceLocked();
1617 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001618 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001619
Steven Thomasb02664d2017-07-26 18:48:28 -07001620 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001621 const nsecs_t vsyncPeriod = getVsyncPeriod();
1622 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001623
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001624 // The present fences returned from vr_hwc are not an accurate
1625 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001626 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001627
Steven Thomasb02664d2017-07-26 18:48:28 -07001628 // Use phase of 0 since phase is not known.
1629 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001630 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001631 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001632
Ana Krulecc2870422019-01-29 19:00:58 -08001633 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001634
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001635 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001636 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001637}
1638
Mathias Agopian4fec8732012-06-29 14:12:52 -07001639void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001640 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001641 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001642 case MessageQueue::INVALIDATE: {
Alec Mouricc0fc602019-02-26 21:45:19 -08001643 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
1644 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
1645 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1646 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1647 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1648 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1649 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1650 if (frameMissed) {
1651 mFrameMissedCount++;
1652 mTimeStats->incrementMissedFrames();
1653 }
1654
Alec Mouri40189b02019-03-05 15:07:54 -08001655 if (hwcFrameMissed) {
1656 mHwcFrameMissedCount++;
1657 }
1658
1659 if (gpuFrameMissed) {
1660 mGpuFrameMissedCount++;
1661 }
1662
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001663 if (mUseSmart90ForVideo) {
1664 // This call is made each time SF wakes up and creates a new frame. It is part
1665 // of video detection feature.
1666 mScheduler->updateFpsBasedOnNativeWindowApi();
1667 }
1668
Ady Abrahamb838aed2019-02-12 15:30:16 -08001669 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001670 break;
1671 }
1672
Alec Mourife3dc942019-02-12 14:19:18 -08001673 // For now, only propagate backpressure when missing a hwc frame.
1674 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001675 if (mPropagateBackpressure) {
1676 signalLayerUpdate();
1677 break;
1678 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001679 }
Dan Stoza50182882016-07-08 12:02:20 -07001680
Steven Thomas050b2c82017-03-06 11:45:16 -08001681 // Now that we're going to make it to the handleMessageTransaction()
1682 // call below it's safe to call updateVrFlinger(), which will
1683 // potentially trigger a display handoff.
1684 updateVrFlinger();
1685
Dan Stoza6b9454d2014-11-07 16:00:59 -08001686 bool refreshNeeded = handleMessageTransaction();
1687 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001688
1689 updateCursorAsync();
1690 updateInputFlinger();
1691
Dan Stoza58784442014-12-02 16:58:17 -08001692 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001693 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001694 // Signal a refresh if a transaction modified the window state,
1695 // a new buffer was latched, or if HWC has requested a full
1696 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001697 signalRefresh();
1698 }
1699 break;
1700 }
1701 case MessageQueue::REFRESH: {
1702 handleMessageRefresh();
1703 break;
1704 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001705 }
1706}
1707
Dan Stoza6b9454d2014-11-07 16:00:59 -08001708bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001709 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001710 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001711
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001712 bool flushedATransaction = flushTransactionQueues();
1713
1714 bool runHandleTransaction = transactionFlags &&
1715 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1716
1717 if (runHandleTransaction) {
1718 handleTransaction(eTransactionMask);
1719 } else {
1720 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001721 }
1722
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001723 if (transactionFlushNeeded()) {
1724 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001726
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001727 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001728}
1729
Mathias Agopian4fec8732012-06-29 14:12:52 -07001730void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001732
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001733 mRefreshPending = false;
1734
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001735 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001736 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001737 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001738 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001739 for (const auto& [token, display] : mDisplays) {
1740 beginFrame(display);
1741 prepareFrame(display);
1742 doDebugFlashRegions(display, repaintEverything);
1743 doComposition(display, repaintEverything);
1744 }
1745
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001746 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001747
1748 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001749 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001750
Dan Stozabfbffeb2016-07-21 14:49:33 -07001751 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001752 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001753 for (const auto& [token, displayDevice] : mDisplays) {
1754 auto display = displayDevice->getCompositionDisplay();
1755 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001756 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001757 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001758 mHadDeviceComposition =
1759 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001760 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001761
Jorim Jaggi90535212018-05-23 23:44:06 +02001762 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001763
David Sodman7e4ae112018-02-09 15:02:28 -08001764 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001766
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767
1768bool SurfaceFlinger::handleMessageInvalidate() {
1769 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001770 bool refreshNeeded = handlePageFlip();
1771
Vishnu Nair4351ad52019-02-11 14:13:02 -08001772 if (mVisibleRegionsDirty) {
1773 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001774 if (mTracingEnabled) {
1775 mTracing.notify("visibleRegionsDirty");
1776 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001777 }
1778
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001779 for (auto& layer : mLayersPendingRefresh) {
1780 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001781 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001782 invalidateLayerStack(layer, visibleReg);
1783 }
1784 mLayersPendingRefresh.clear();
1785 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001786}
1787
David Sodman79bba0e2018-08-05 18:07:49 -07001788void SurfaceFlinger::calculateWorkingSet() {
1789 ATRACE_CALL();
1790 ALOGV(__FUNCTION__);
1791
David Sodman79bba0e2018-08-05 18:07:49 -07001792 // build the h/w work list
1793 if (CC_UNLIKELY(mGeometryInvalid)) {
1794 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 for (const auto& [token, displayDevice] : mDisplays) {
1796 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001797
Lloyd Piquea83776c2019-01-29 18:42:32 -08001798 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001799
Lloyd Piquea83776c2019-01-29 18:42:32 -08001800 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1801 auto& compositionState = layer->editState();
1802 compositionState.forceClientComposition = false;
1803 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1804 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001805 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001806
Lloyd Piquea83776c2019-01-29 18:42:32 -08001807 // The output Z order is set here based on a simple counter.
1808 compositionState.z = zOrder++;
1809
1810 // Update the display independent composition state. This goes
1811 // to the general composition layer state structure.
1812 // TODO: Do this once per compositionengine::CompositionLayer.
1813 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1814 true);
1815
1816 // Recalculate the geometry state of the output layer.
1817 layer->updateCompositionState(true);
1818
1819 // Write the updated geometry state to the HWC
1820 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001821 }
1822 }
1823 }
1824
1825 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001826 for (const auto& [token, displayDevice] : mDisplays) {
1827 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001828 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001829 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001830 continue;
1831 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001832 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001833
1834 if (mDrawingState.colorMatrixChanged) {
1835 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001836 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001837 Dataspace targetDataspace = Dataspace::UNKNOWN;
1838 if (useColorManagement) {
1839 ColorMode colorMode;
1840 RenderIntent renderIntent;
1841 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1842 display->setColorMode(colorMode, targetDataspace, renderIntent);
1843 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001845 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001846 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001847 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1848 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001849 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001850 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001851 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1852 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001853 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001854 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001855 }
1856
Peiyong Lind3788632018-09-18 16:01:31 -07001857 // TODO(b/111562338) remove when composer 2.3 is shipped.
1858 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001859 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001860 }
1861
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001862 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001863 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001864 }
1865
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001866 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001867 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001868 layer->setCompositionType(displayDevice,
1869 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001870 continue;
1871 }
1872
Lloyd Pique32cbe282018-10-19 13:09:22 -07001873 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001874 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001875 displayDevice->getSupportedPerFrameMetadata(),
1876 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1877 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001878 }
1879 }
1880
1881 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001882
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001883 for (const auto& [token, displayDevice] : mDisplays) {
1884 auto display = displayDevice->getCompositionDisplay();
1885 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001886 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1887 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1888 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001889 }
1890 }
David Sodman79bba0e2018-08-05 18:07:49 -07001891}
1892
Lloyd Pique32cbe282018-10-19 13:09:22 -07001893void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1894 bool repaintEverything) {
1895 auto display = displayDevice->getCompositionDisplay();
1896 const auto& displayState = display->getState();
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 // is debugging enabled
1899 if (CC_LIKELY(!mDebugRegion))
1900 return;
1901
Lloyd Pique32cbe282018-10-19 13:09:22 -07001902 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001903 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001904 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001905 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001906 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001907 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001908 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001910 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001911 }
1912 }
1913
Lloyd Pique32cbe282018-10-19 13:09:22 -07001914 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915
1916 if (mDebugRegion > 1) {
1917 usleep(mDebugRegion * 1000);
1918 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001919
Lloyd Pique32cbe282018-10-19 13:09:22 -07001920 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921}
1922
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001923void SurfaceFlinger::logLayerStats() {
1924 ATRACE_CALL();
1925 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001926 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001927 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001928 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001929 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001930 }
1931 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001932
1933 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001934 }
1935}
1936
David Sodman2b406362017-12-15 13:33:47 -08001937void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 ATRACE_CALL();
1940 ALOGV("preComposition");
1941
David Sodman2b406362017-12-15 13:33:47 -08001942 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001945 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001946 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947 needExtraInvalidate = true;
1948 }
Robert Carr2047fae2016-11-28 14:09:09 -08001949 });
1950
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951 if (needExtraInvalidate) {
1952 signalLayerUpdate();
1953 }
1954}
1955
Ana Krulece588e312018-09-18 12:32:24 -07001956void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1957 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 // Update queue of past composite+present times and determine the
1959 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001960 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001962 while (!getBE().mCompositePresentTimes.empty()) {
1963 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964 // Cached values should have been updated before calling this method,
1965 // which helps avoid duplicate syscalls.
1966 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1967 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1968 break;
1969 }
1970 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001971 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 }
1973
1974 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001975 while (getBE().mCompositePresentTimes.size() > 16) {
1976 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 }
1978
Ana Krulece588e312018-09-18 12:32:24 -07001979 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001980}
1981
Ana Krulece588e312018-09-18 12:32:24 -07001982void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1983 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001984 // Integer division and modulo round toward 0 not -inf, so we need to
1985 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001986 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1987 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1988 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989
Ana Krulec757f63a2019-01-25 10:46:18 -08001990 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001991 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001992 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001993 }
1994
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995 // Snap the latency to a value that removes scheduling jitter from the
1996 // composition and present times, which often have >1ms of jitter.
1997 // Reducing jitter is important if an app attempts to extrapolate
1998 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001999 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002000 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002001 nsecs_t bias = stats.vsyncPeriod / 2;
2002 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2003 nsecs_t snappedCompositeToPresentLatency =
2004 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002005
David Sodman99974d22017-11-28 12:04:33 -08002006 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002007 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2008 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002009 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002010}
2011
David Sodman2b406362017-12-15 13:33:47 -08002012void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 ATRACE_CALL();
2015 ALOGV("postComposition");
2016
Brian Anderson3546a3f2016-07-14 11:51:14 -07002017 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002018 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002020 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002021 }
2022
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002023 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025
David Sodman73beded2017-11-15 11:56:06 -08002026 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002028 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002030 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2031 ->getRenderSurface()
2032 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 } else {
2035 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2036 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037
David Sodman73beded2017-11-15 11:56:06 -08002038 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002039 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2040 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002041 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043
Ana Krulece588e312018-09-18 12:32:24 -07002044 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002045 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046
David Sodman2b406362017-12-15 13:33:47 -08002047 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 // when we started doing work for this frame, but that should be okay
2049 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002050 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002051 CompositorTiming compositorTiming;
2052 {
David Sodman99974d22017-11-28 12:04:33 -08002053 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2054 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002055 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002056
Robert Carr2047fae2016-11-28 14:09:09 -08002057 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002058 bool frameLatched =
2059 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2060 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002061 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002062 recordBufferingStats(layer->getName().string(),
2063 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002064 }
Robert Carr2047fae2016-11-28 14:09:09 -08002065 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002066
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002067 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002068 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002069 }
2070
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002071 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002072 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2073 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002074 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002075 }
2076 }
2077
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002078 if (mAnimCompositionPending) {
2079 mAnimCompositionPending = false;
2080
Brian Anderson4e606e32017-03-16 15:34:57 -07002081 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002082 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002083 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002085 // The HWC doesn't support present fences, so use the refresh
2086 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 const nsecs_t presentTime =
2088 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002089 mAnimFrameTracker.setActualPresentTime(presentTime);
2090 }
2091 mAnimFrameTracker.advanceFrame();
2092 }
Dan Stozab90cf072015-03-05 11:05:59 -08002093
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002094 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002095 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002096 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002097 }
2098
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002099 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002100
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2102 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002103 return;
2104 }
2105
2106 nsecs_t currentTime = systemTime();
2107 if (mHasPoweredOff) {
2108 mHasPoweredOff = false;
2109 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002110 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002111 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002112 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2113 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002114 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002115 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002116 }
David Sodman4a36e932017-11-07 14:29:47 -08002117 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002118 }
David Sodman4a36e932017-11-07 14:29:47 -08002119 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002120
2121 {
2122 std::lock_guard lock(mTexturePoolMutex);
2123 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2124 if (refillCount > 0) {
2125 const size_t offset = mTexturePool.size();
2126 mTexturePool.resize(mTexturePoolSize);
2127 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2128 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2129 }
2130 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002131
Marissa Wallfda30bb2018-10-12 11:34:28 -07002132 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002133 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002134
Kevin DuBois413287f2019-02-25 08:46:47 -08002135 if (mLumaSampling && mRegionSamplingThread) {
2136 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002137 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002138}
2139
Vishnu Nair4351ad52019-02-11 14:13:02 -08002140void SurfaceFlinger::computeLayerBounds() {
2141 for (const auto& pair : mDisplays) {
2142 const auto& displayDevice = pair.second;
2143 const auto display = displayDevice->getCompositionDisplay();
2144 for (const auto& layer : mDrawingState.layersSortedByZ) {
2145 // only consider the layers on the given layer stack
2146 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002147 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002148 }
2149
2150 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2151 }
2152 }
2153}
2154
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 ATRACE_CALL();
2157 ALOGV("rebuildLayerStacks");
2158
Mathias Agopiancd60f992012-08-16 16:28:27 -07002159 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002160 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002161 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002162 mVisibleRegionsDirty = false;
2163 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002164
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002165 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002166 const auto& displayDevice = pair.second;
2167 auto display = displayDevice->getCompositionDisplay();
2168 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002169 Region opaqueRegion;
2170 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002171 compositionengine::Output::OutputLayers layersSortedByZ;
2172 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002173 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002174 const ui::Transform& tr = displayState.transform;
2175 const Rect bounds = displayState.bounds;
2176 if (displayState.isEnabled) {
2177 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002178
Jeff Sharkey76488112017-02-27 14:15:18 -07002179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002180 auto compositionLayer = layer->getCompositionLayer();
2181 if (compositionLayer == nullptr) {
2182 return;
2183 }
2184
Lloyd Pique32cbe282018-10-19 13:09:22 -07002185 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002186 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2187 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2188
Lloyd Pique07e33212018-12-18 16:33:37 -08002189 bool needsOutputLayer = false;
2190
Lloyd Piqueef36b002019-01-23 17:52:04 -08002191 if (display->belongsInOutput(layer->getLayerStack(),
2192 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002193 Region drawRegion(tr.transform(
2194 layer->visibleNonTransparentRegion));
2195 drawRegion.andSelf(bounds);
2196 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002197 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002198 }
Chia-I Wu83806892017-11-16 10:50:20 -08002199 }
2200
Lloyd Pique07e33212018-12-18 16:33:37 -08002201 if (needsOutputLayer) {
2202 layersSortedByZ.emplace_back(
2203 display->getOrCreateOutputLayer(displayId, compositionLayer,
2204 layerFE));
2205 deprecated_layersSortedByZ.add(layer);
2206
2207 auto& outputLayerState = layersSortedByZ.back()->editState();
2208 outputLayerState.visibleRegion =
2209 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2210 } else if (displayId) {
2211 // For layers that are being removed from a HWC display,
2212 // and that have queued frames, add them to a a list of
2213 // released layers so we can properly set a fence.
2214 bool hasExistingOutputLayer =
2215 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2216 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2217 mLayersWithQueuedFrames.cend(),
2218 layer) != mLayersWithQueuedFrames.cend();
2219
2220 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002221 layersNeedingFences.add(layer);
2222 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002223 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 });
2225 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002226
2227 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2228
2229 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002230 displayDevice->setLayersNeedingFences(layersNeedingFences);
2231
2232 Region undefinedRegion{bounds};
2233 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2234
2235 display->editState().undefinedRegion = undefinedRegion;
2236 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002237 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002238 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002239}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002240
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002241// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002242// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002243// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002244// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002245// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246// The returned HDR data space is one of
2247// - Dataspace::UNKNOWN
2248// - Dataspace::BT2020_HLG
2249// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002250Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2251 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002252 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002253 *outHdrDataSpace = Dataspace::UNKNOWN;
2254
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002255 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002256 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 case Dataspace::V0_SCRGB:
2258 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002259 case Dataspace::BT2020:
2260 case Dataspace::BT2020_ITU:
2261 case Dataspace::BT2020_LINEAR:
2262 case Dataspace::DISPLAY_BT2020:
2263 bestDataSpace = Dataspace::DISPLAY_BT2020;
2264 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002265 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002266 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002267 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 case Dataspace::BT2020_PQ:
2269 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002270 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002271 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002273 case Dataspace::BT2020_HLG:
2274 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002275 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276 // When there's mixed PQ content and HLG content, we set the HDR
2277 // data space to be BT2020_PQ and convert HLG to PQ.
2278 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2279 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002280 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002281 break;
2282 default:
2283 break;
2284 }
Romain Guy54f154a2017-10-24 21:40:32 +01002285 }
2286
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002288}
2289
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002290// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2292 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2294 *outMode = ColorMode::NATIVE;
2295 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002298 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002299
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002301 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002303 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2304
Peiyong Lina3ea5592019-02-10 14:45:00 -08002305 switch (mForceColorMode) {
2306 case ColorMode::SRGB:
2307 bestDataSpace = Dataspace::V0_SRGB;
2308 break;
2309 case ColorMode::DISPLAY_P3:
2310 bestDataSpace = Dataspace::DISPLAY_P3;
2311 break;
2312 default:
2313 break;
2314 }
2315
Peiyong Lindfde5112018-06-05 10:58:41 -07002316 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002317 const bool isHdr =
2318 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002319 if (isHdr) {
2320 bestDataSpace = hdrDataSpace;
2321 }
2322
Chia-I Wu0d711262018-05-21 15:19:35 -07002323 RenderIntent intent;
2324 switch (mDisplayColorSetting) {
2325 case DisplayColorSetting::MANAGED:
2326 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002327 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002328 break;
2329 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002330 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002331 break;
2332 default: // vendor display color setting
2333 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2334 break;
2335 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002336
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002337 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002338}
2339
Lloyd Pique32cbe282018-10-19 13:09:22 -07002340void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2341 auto display = displayDevice->getCompositionDisplay();
2342 const auto& displayState = display->getState();
2343
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002344 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002345 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2346 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002347
David Sodmanfa9b2af2017-12-24 13:28:59 -08002348 // If nothing has changed (!dirty), don't recompose.
2349 // If something changed, but we don't currently have any visible layers,
2350 // and didn't when we last did a composition, then skip it this time.
2351 // The second rule does two things:
2352 // - When all layers are removed from a display, we'll emit one black
2353 // frame, then nothing more until we get new layers.
2354 // - When a display is created with a private layer stack, we won't
2355 // emit any black frames until a layer is added to the layer stack.
2356 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002357
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 const char flagPrefix[] = {'-', '+'};
2359 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002360 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2361 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2362 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2363 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002364
Lloyd Pique31cb2942018-10-19 17:23:03 -07002365 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002366
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002368 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002369 }
2370}
2371
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2373 auto display = displayDevice->getCompositionDisplay();
2374 const auto& displayState = display->getState();
2375
2376 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002377 return;
David Sodman2b406362017-12-15 13:33:47 -08002378 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002379
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002380 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002382 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002383}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002384
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002386 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 ALOGV("doComposition");
2388
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 auto display = displayDevice->getCompositionDisplay();
2390 const auto& displayState = display->getState();
2391
2392 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002393 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002394 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002395
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002398
Lloyd Pique32cbe282018-10-19 13:09:22 -07002399 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002400 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002401 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403}
2404
David Sodmanfa9b2af2017-12-24 13:28:59 -08002405void SurfaceFlinger::postFrame()
2406{
2407 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 const auto display = getDefaultDisplayDeviceLocked();
2409 if (display && getHwComposer().isConnected(*display->getId())) {
2410 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2412 logFrameStats();
2413 }
2414 }
2415}
2416
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002418 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 auto display = displayDevice->getCompositionDisplay();
2422 const auto& displayState = display->getState();
2423 const auto displayId = display->getId();
2424
David Sodmanfa9b2af2017-12-24 13:28:59 -08002425 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002426
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 if (displayId) {
2429 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002430 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002431 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002432 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002433 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002434 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002435
Chia-I Wu7b549592017-11-15 09:14:57 -08002436 // The layer buffer from the previous frame (if any) is released
2437 // by HWC only when the release fence from this frame (if any) is
2438 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002439 if (layer->getState().hwc) {
2440 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002441 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002442 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2443 usedClientComposition =
2444 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002445 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002446
2447 // If the layer was client composited in the previous frame, we
2448 // need to merge with the previous client target acquire fence.
2449 // Since we do not track that, always merge with the current
2450 // client target acquire fence when it is available, even though
2451 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002452 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 releaseFence =
2454 Fence::merge("LayerRelease", releaseFence,
2455 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002456 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002457
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002458 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 }
Chia-I Wu83806892017-11-16 10:50:20 -08002460
2461 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002463 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002466 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002468 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002469 }
2470 }
2471
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 if (displayId) {
2473 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002474 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476}
2477
Mathias Agopian87baae12012-07-31 12:38:26 -07002478void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479{
Mathias Agopian841cde52012-03-01 15:44:37 -08002480 ATRACE_CALL();
2481
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002482 // here we keep a copy of the drawing state (that is the state that's
2483 // going to be overwritten by handleTransactionLocked()) outside of
2484 // mStateLock so that the side-effects of the State assignment
2485 // don't happen with mStateLock held (which can cause deadlocks).
2486 State drawingState(mDrawingState);
2487
Mathias Agopianca4d3602011-05-19 15:38:14 -07002488 Mutex::Autolock _l(mStateLock);
2489 const nsecs_t now = systemTime();
2490 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491
Mathias Agopianca4d3602011-05-19 15:38:14 -07002492 // Here we're guaranteed that some transaction flags are set
2493 // so we can call handleTransactionLocked() unconditionally.
2494 // We call getTransactionFlags(), which will also clear the flags,
2495 // with mStateLock held to guarantee that mCurrentState won't change
2496 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002497
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002498 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002500 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002501
Mathias Agopianca4d3602011-05-19 15:38:14 -07002502 mLastTransactionTime = systemTime() - now;
2503 mDebugInTransaction = 0;
2504 invalidateHwcGeometry();
2505 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002506}
2507
Lloyd Piqueba04e622017-12-14 17:11:26 -08002508void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2509 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 const std::optional<DisplayIdentificationInfo> info =
2511 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 continue;
2515 }
2516
Lloyd Piqueba04e622017-12-14 17:11:26 -08002517 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002519 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 mPhysicalDisplayTokens[info->id] = new BBinder();
2521 DisplayDeviceState state;
2522 state.displayId = info->id;
2523 state.isSecure = true; // All physical displays are currently considered secure.
2524 state.displayName = info->name;
2525 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2526 mInterceptor->saveDisplayCreation(state);
Arthur Hungf8b7d1f2019-03-22 16:10:56 +08002527 // TODO(b/123715322): Removes the per-display state that was added to the scheduler.
2528 mRefreshRateConfigs[info->id] = std::make_shared<scheduler::RefreshRateConfigs>(
2529 getHwComposer().getConfigs(info->id));
Steven Thomaseb6d2052018-03-20 15:40:48 -07002530 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002532 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2535 if (index >= 0) {
2536 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2537 mInterceptor->saveDisplayDeletion(state.sequenceId);
2538 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002539 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 mPhysicalDisplayTokens.erase(info->id);
Arthur Hungf8b7d1f2019-03-22 16:10:56 +08002541 mRefreshRateConfigs.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002542 }
2543
2544 processDisplayChangesLocked();
2545 }
2546
2547 mPendingHotplugEvents.clear();
2548}
2549
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002550void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002551 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2552 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002553}
2554
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002557 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const sp<IGraphicBufferProducer>& producer) {
2559 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002560 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.isSecure = state.isSecure;
2563 creationArgs.displaySurface = dispSurface;
2564 creationArgs.hasWideColorGamut = false;
2565 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002566
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002567 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 creationArgs.isPrimary = isInternalDisplay;
2569
2570 if (useColorManagement && displayId) {
2571 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002573 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002574 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002576
Dominik Laskowski7e045462018-05-30 13:02:02 -07002577 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002579 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580 }
tangrobin6753a022018-08-10 10:58:54 +08002581 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 if (displayId) {
2584 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002587 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588
Lloyd Pique90c115d2018-09-18 21:39:42 -07002589 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002591 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593 // Make sure that composition can never be stalled by a virtual display
2594 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002595 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002596 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2598 }
2599
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 creationArgs.displayInstallOrientation =
2601 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002602
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002604 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Lloyd Pique90c115d2018-09-18 21:39:42 -07002606 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607
2608 if (maxFrameBufferAcquiredBuffers >= 3) {
2609 nativeWindowSurface->preallocateBuffers();
2610 }
2611
2612 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002613 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002616 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002618 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2619 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 if (!state.isVirtual()) {
2621 LOG_ALWAYS_FATAL_IF(!displayId);
2622 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002623 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002625 display->setLayerStack(state.layerStack);
2626 display->setProjection(state.orientation, state.viewport, state.frame);
2627 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002629 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630}
2631
Lloyd Pique347200f2017-12-14 17:00:15 -08002632void SurfaceFlinger::processDisplayChangesLocked() {
2633 // here we take advantage of Vector's copy-on-write semantics to
2634 // improve performance by skipping the transaction entirely when
2635 // know that the lists are identical
2636 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2637 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2638 if (!curr.isIdenticalTo(draw)) {
2639 mVisibleRegionsDirty = true;
2640 const size_t cc = curr.size();
2641 size_t dc = draw.size();
2642
2643 // find the displays that were removed
2644 // (ie: in drawing state but not in current state)
2645 // also handle displays that changed
2646 // (ie: displays that are in both lists)
2647 for (size_t i = 0; i < dc;) {
2648 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2649 if (j < 0) {
2650 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002651 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002652 // Save display ID before disconnecting.
2653 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002654 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002655
2656 if (!display->isVirtual()) {
2657 LOG_ALWAYS_FATAL_IF(!displayId);
2658 dispatchDisplayHotplugEvent(displayId->value, false);
2659 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002661
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 } else {
2664 // this display is in both lists. see if something changed.
2665 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002667 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2668 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2669 if (state_binder != draw_binder) {
2670 // changing the surface is like destroying and
2671 // recreating the DisplayDevice, so we just remove it
2672 // from the drawing state, so that it get re-added
2673 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002675 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002677 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002678 mDrawingState.displays.removeItemsAt(i);
2679 dc--;
2680 // at this point we must loop to the next item
2681 continue;
2682 }
2683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 }
2688 if ((state.orientation != draw[i].orientation) ||
2689 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 }
2692 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 }
2695 }
2696 }
2697 ++i;
2698 }
2699
2700 // find displays that were added
2701 // (ie: in current state but not in drawing state)
2702 for (size_t i = 0; i < cc; i++) {
2703 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2704 const DisplayDeviceState& state(curr[i]);
2705
Lloyd Pique542307f2018-10-19 13:24:08 -07002706 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 sp<IGraphicBufferProducer> producer;
2708 sp<IGraphicBufferProducer> bqProducer;
2709 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002710 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711
Dominik Laskowski075d3172018-05-24 15:50:06 -07002712 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002713 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 // Virtual displays without a surface are dormant:
2715 // they have external state (layer stack, projection,
2716 // etc.) but no internal state (i.e. a DisplayDevice).
2717 if (state.surface != nullptr) {
2718 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 int width = 0;
2721 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2722 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2723 int height = 0;
2724 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2725 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2726 int intFormat = 0;
2727 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2728 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002729 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 displayId =
2732 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 }
2734
2735 // TODO: Plumb requested format back up to consumer
2736
2737 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002738 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 bqProducer, bqConsumer,
2740 state.displayName);
2741
2742 dispSurface = vds;
2743 producer = vds;
2744 }
2745 } else {
2746 ALOGE_IF(state.surface != nullptr,
2747 "adding a supported display, but rendering "
2748 "surface is provided (%p), ignoring it",
2749 state.surface.get());
2750
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 displayId = state.displayId;
2752 LOG_ALWAYS_FATAL_IF(!displayId);
2753 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 producer = bqProducer;
2755 }
2756
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002759 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002760 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002762 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002763 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002764 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 }
2767 }
2768 }
2769 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002770
2771 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002772}
2773
Mathias Agopian87baae12012-07-31 12:38:26 -07002774void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002775{
Dan Stoza7dde5992015-05-22 09:51:44 -07002776 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002777 mCurrentState.traverseInZOrder([](Layer* layer) {
2778 layer->notifyAvailableFrames();
2779 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 /*
2782 * Traversal of the children
2783 * (perform the transaction for each of them if needed)
2784 */
2785
Marissa Wall06255332019-03-27 13:48:27 -07002786 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002787 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002789 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790
2791 const uint32_t flags = layer->doTransaction(0);
2792 if (flags & Layer::eVisibleRegion)
2793 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002794
2795 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002796 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002797 }
Robert Carr2047fae2016-11-28 14:09:09 -08002798 });
Marissa Wall06255332019-03-27 13:48:27 -07002799 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 }
2801
2802 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002803 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 */
2805
Mathias Agopiane57f2922012-08-09 16:29:12 -07002806 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002808 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002809 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002811 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002812 // The transform hint might have changed for some layers
2813 // (either because a display has changed, or because a layer
2814 // as changed).
2815 //
2816 // Walk through all the layers in currentLayers,
2817 // and update their transform hint.
2818 //
2819 // If a layer is visible only on a single display, then that
2820 // display is used to calculate the hint, otherwise we use the
2821 // default display.
2822 //
2823 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2824 // the hint is set before we acquire a buffer from the surface texture.
2825 //
2826 // NOTE: layer transactions have taken place already, so we use their
2827 // drawing state. However, SurfaceFlinger's own transaction has not
2828 // happened yet, so we must use the current state layer list
2829 // (soon to become the drawing state list).
2830 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002832 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002833 bool first = true;
2834 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002835 // NOTE: we rely on the fact that layers are sorted by
2836 // layerStack first (so we don't have to traverse the list
2837 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002839 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002840 currentlayerStack = layerStack;
2841 // figure out if this layerstack is mirrored
2842 // (more than one display) if so, pick the default display,
2843 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002844 hintDisplay = nullptr;
2845 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002846 if (display->getCompositionDisplay()
2847 ->belongsInOutput(layer->getLayerStack(),
2848 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 if (hintDisplay) {
2850 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002851 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002854 }
2855 }
2856 }
2857 }
Chet Haase91d25932013-04-11 15:24:55 -07002858
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002860 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2861 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002862
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002863 // could be null when this layer is using a layerStack
2864 // that is not visible on any display. Also can occur at
2865 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002867 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002868
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002870 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 if (hintDisplay) {
2872 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002873 }
Robert Carr2047fae2016-11-28 14:09:09 -08002874
2875 first = false;
2876 });
Mathias Agopian84300952012-11-21 16:02:13 -08002877 }
2878
2879
Mathias Agopian3559b072012-08-15 13:46:03 -07002880 /*
2881 * Perform our own transaction if needed
2882 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883
2884 if (mLayersAdded) {
2885 mLayersAdded = false;
2886 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002887 mVisibleRegionsDirty = true;
2888 }
2889
2890 // some layers might have been removed, so
2891 // we need to update the regions they're exposing.
2892 if (mLayersRemoved) {
2893 mLayersRemoved = false;
2894 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002895 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002897 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002899 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002900 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002901 }
Robert Carr2047fae2016-11-28 14:09:09 -08002902 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903 }
2904
Vishnu Nairec0ab382019-02-13 15:32:56 -08002905 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002907}
2908
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002909void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002910 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002911 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002912 return;
2913 }
2914
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002915 if (mVisibleRegionsDirty || mInputInfoChanged) {
2916 mInputInfoChanged = false;
2917 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002918 } else if (mInputWindowCommands.syncInputWindows) {
2919 // If the caller requested to sync input windows, but there are no
2920 // changes to input windows, notify immediately.
2921 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002922 }
2923
2924 executeInputWindowCommands();
2925}
2926
2927void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002928 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002929
2930 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2931 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002932 // When calculating the screen bounds we ignore the transparent region since it may
2933 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002934 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002935 }
2936 });
chaviw291d88a2019-02-14 10:33:58 -08002937
2938 mInputFlinger->setInputWindows(inputHandles,
2939 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2940 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002941}
2942
Vishnu Nairec0ab382019-02-13 15:32:56 -08002943void SurfaceFlinger::commitInputWindowCommands() {
2944 mInputWindowCommands.merge(mPendingInputWindowCommands);
2945 mPendingInputWindowCommands.clear();
2946}
2947
chaviwfbe5d9c2018-12-26 12:23:37 -08002948void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002949 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2950 if (transferTouchFocusCommand.fromToken != nullptr &&
2951 transferTouchFocusCommand.toToken != nullptr &&
2952 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2953 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2954 transferTouchFocusCommand.toToken);
2955 }
2956 }
2957
2958 mInputWindowCommands.clear();
2959}
2960
Riley Andrews03414a12014-07-01 14:22:59 -07002961void SurfaceFlinger::updateCursorAsync()
2962{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002963 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002964 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002965 continue;
2966 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002968 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2969 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002970 }
2971 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002972}
2973
chaviw61626f22018-11-15 16:26:27 -08002974void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2975 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002976 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002977 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002978 }
2979 layer->releasePendingBuffer(systemTime());
2980}
2981
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982void SurfaceFlinger::commitTransaction()
2983{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002984 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002985 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002986 for (const auto& l : mLayersPendingRemoval) {
2987 recordBufferingStats(l->getName().string(),
2988 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002989
Lloyd Pique07e33212018-12-18 16:33:37 -08002990 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002991 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002992 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002993 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994 }
2995 mLayersPendingRemoval.clear();
2996 }
2997
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002998 // If this transaction is part of a window animation then the next frame
2999 // we composite should be considered an animation as well.
3000 mAnimCompositionPending = mAnimTransactionPending;
3001
Nataniel Borges2b796da2019-02-15 13:32:18 -08003002 withTracingLock([&]() {
3003 mDrawingState = mCurrentState;
3004 // clear the "changed" flags in current state
3005 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003006
Nataniel Borges2b796da2019-02-15 13:32:18 -08003007 mDrawingState.traverseInZOrder([](Layer* layer) { layer->commitChildList(); });
Robert Carr1f0a16a2016-10-24 16:27:39 -07003008 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003009
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003010 mTransactionPending = false;
3011 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013}
3014
Nataniel Borges2b796da2019-02-15 13:32:18 -08003015void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3016 if (mTracingEnabledChanged) {
3017 mTracingEnabled = mTracing.isEnabled();
3018 mTracingEnabledChanged = false;
3019 }
3020
3021 // Synchronize with Tracing thread
3022 std::unique_lock<std::mutex> lock;
3023 if (mTracingEnabled) {
3024 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3025 }
3026
3027 lockedOperation();
3028
3029 // Synchronize with Tracing thread
3030 if (mTracingEnabled) {
3031 lock.unlock();
3032 }
3033}
3034
Lloyd Pique32cbe282018-10-19 13:09:22 -07003035void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003039
Lloyd Pique32cbe282018-10-19 13:09:22 -07003040 auto display = displayDevice->getCompositionDisplay();
3041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 Region aboveOpaqueLayers;
3043 Region aboveCoveredLayers;
3044 Region dirty;
3045
Mathias Agopian87baae12012-07-31 12:38:26 -07003046 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Robert Carr2047fae2016-11-28 14:09:09 -08003048 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003049 // start with the whole surface at its current location
3050 const Layer::State& s(layer->getDrawingState());
3051
Jesse Hall01e29052013-02-19 16:13:35 -08003052 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003053 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003054 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003056
Mathias Agopianab028732010-03-16 16:41:46 -07003057 /*
3058 * opaqueRegion: area of a surface that is fully opaque.
3059 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003061
3062 /*
3063 * visibleRegion: area of a surface that is visible on screen
3064 * and not fully transparent. This is essentially the layer's
3065 * footprint minus the opaque regions above it.
3066 * Areas covered by a translucent surface are considered visible.
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 /*
3071 * coveredRegion: area of a surface that is covered by all
3072 * visible regions above it (which includes the translucent areas).
3073 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075
Jesse Halla8026d22012-09-25 13:25:04 -07003076 /*
3077 * transparentRegion: area of a surface that is hinted to be completely
3078 * transparent. This is only used to tell when the layer has no visible
3079 * non-transparent regions and can be removed from the layer list. It
3080 * does not affect the visibleRegion of this layer or any layers
3081 * beneath it. The hint may not be correct if apps don't respect the
3082 * SurfaceView restrictions (which, sadly, some don't).
3083 */
3084 Region transparentRegion;
3085
Mathias Agopianab028732010-03-16 16:41:46 -07003086
3087 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003088 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003090 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003093 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003094 if (!visibleRegion.isEmpty()) {
3095 // Remove the transparent area from the visible region
3096 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003097 if (tr.preserveRects()) {
3098 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003099 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003101 // transformation too complex, can't do the
3102 // transparent region optimization.
3103 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003104 }
Mathias Agopianab028732010-03-16 16:41:46 -07003105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
Mathias Agopianab028732010-03-16 16:41:46 -07003107 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003109 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003110 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003111 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003112 // the opaque region is the layer's footprint
3113 opaqueRegion = visibleRegion;
3114 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 }
3116 }
3117
Robert Carre5f4f692018-01-12 13:12:28 -08003118 if (visibleRegion.isEmpty()) {
3119 layer->clearVisibilityRegions();
3120 return;
3121 }
3122
Mathias Agopianab028732010-03-16 16:41:46 -07003123 // Clip the covered region to the visible region
3124 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3125
3126 // Update aboveCoveredLayers for next (lower) layer
3127 aboveCoveredLayers.orSelf(visibleRegion);
3128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 // subtract the opaque region covered by the layers above us
3130 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131
3132 // compute this layer's dirty region
3133 if (layer->contentDirty) {
3134 // we need to invalidate the whole region
3135 dirty = visibleRegion;
3136 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 layer->contentDirty = false;
3139 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003140 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003141 * the exposed region consists of two components:
3142 * 1) what's VISIBLE now and was COVERED before
3143 * 2) what's EXPOSED now less what was EXPOSED before
3144 *
3145 * note that (1) is conservative, we start with the whole
3146 * visible region but only keep what used to be covered by
3147 * something -- which mean it may have been exposed.
3148 *
3149 * (2) handles areas that were not covered by anything but got
3150 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003151 */
Mathias Agopianab028732010-03-16 16:41:46 -07003152 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 const Region oldVisibleRegion = layer->visibleRegion;
3154 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003155 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3156 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 dirty.subtractSelf(aboveOpaqueLayers);
3159
3160 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003161 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopianab028732010-03-16 16:41:46 -07003163 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003165
Jesse Halla8026d22012-09-25 13:25:04 -07003166 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 layer->setVisibleRegion(visibleRegion);
3168 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003169 layer->setVisibleNonTransparentRegion(
3170 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003171 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian87baae12012-07-31 12:38:26 -07003173 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174}
3175
Chia-I Wuab0c3192017-08-01 11:29:00 -07003176void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003177 for (const auto& [token, displayDevice] : mDisplays) {
3178 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003179 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003180 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003181 }
3182 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003183}
3184
Dan Stoza6b9454d2014-11-07 16:00:59 -08003185bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003187 ALOGV("handlePageFlip");
3188
Brian Andersond6927fb2016-07-23 23:37:30 -07003189 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190
Mathias Agopian4fec8732012-06-29 14:12:52 -07003191 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003192 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003193 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003194
3195 // Store the set of layers that need updates. This set must not change as
3196 // buffers are being latched, as this could result in a deadlock.
3197 // Example: Two producers share the same command stream and:
3198 // 1.) Layer 0 is latched
3199 // 2.) Layer 0 gets a new frame
3200 // 2.) Layer 1 gets a new frame
3201 // 3.) Layer 1 is latched.
3202 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3203 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003204 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003205 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003206 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003207 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003208 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003209 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003211 } else {
3212 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003213 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003214 } else {
3215 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003216 }
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
3218
Lloyd Piquef2c79392018-12-20 16:23:33 -08003219 if (!mLayersWithQueuedFrames.empty()) {
3220 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3221 // writes to Layer current state. See also b/119481871
3222 Mutex::Autolock lock(mStateLock);
3223
3224 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003225 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003226 mLayersPendingRefresh.push_back(layer);
3227 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003228 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003229 if (layer->isBufferLatched()) {
3230 newDataLatched = true;
3231 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003232 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003233 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003234
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003235 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003236
3237 // If we will need to wake up at some time in the future to deal with a
3238 // queued frame that shouldn't be displayed during this vsync period, wake
3239 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003240 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003241 signalLayerUpdate();
3242 }
3243
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003244 // enter boot animation on first buffer latch
3245 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3246 ALOGI("Enter boot animation");
3247 mBootStage = BootStage::BOOTANIMATION;
3248 }
3249
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003251 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Mathias Agopianad456f92011-01-13 17:53:01 -08003254void SurfaceFlinger::invalidateHwcGeometry()
3255{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003256 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003257}
3258
Lloyd Pique32cbe282018-10-19 13:09:22 -07003259void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003260 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003261 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003262 // We only need to actually compose the display if:
3263 // 1) It is being handled by hardware composer, which may need this to
3264 // keep its virtual display state machine in sync, or
3265 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003266 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003268 return;
3269 }
3270
Dan Stoza9e56aa02015-11-02 13:00:03 -08003271 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003272 base::unique_fd readyFence;
3273 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003274
3275 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003276 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277}
3278
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003279bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3280 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003281 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003283
Lloyd Pique32cbe282018-10-19 13:09:22 -07003284 auto display = displayDevice->getCompositionDisplay();
3285 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003286 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003287 auto& renderEngine = getRenderEngine();
3288 const bool supportProtectedContent =
3289 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003290
3291 const Region bounds(displayState.bounds);
3292 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003293 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003294 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003295
Peiyong Lind3788632018-09-18 16:01:31 -07003296 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003297 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003298
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003299 renderengine::DisplaySettings clientCompositionDisplay;
3300 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3301 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003302 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003303
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 if (hasClientComposition) {
3305 ALOGV("hasClientComposition");
3306
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003307 if (displayDevice->isPrimary() && supportProtectedContent) {
3308 bool needsProtected = false;
3309 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3310 // If the layer is a protected layer, mark protected context is needed.
3311 if (layer->isProtected()) {
3312 needsProtected = true;
3313 break;
3314 }
3315 }
3316 if (needsProtected != renderEngine.isProtected() &&
3317 renderEngine.useProtectedContext(needsProtected)) {
3318 display->getRenderSurface()->setProtected(needsProtected);
3319 }
3320 }
3321
Alec Mouri6338c9d2019-02-07 16:57:51 -08003322 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003323
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003324 if (buf == nullptr) {
3325 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3326 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003327 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003328 return false;
3329 }
3330
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003331 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3332 clientCompositionDisplay.clip = displayState.scissor;
3333 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003334 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003335
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003336 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003337 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003338 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003340 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003341 clientCompositionDisplay.outputDataspace = outputDataspace;
3342 clientCompositionDisplay.maxLuminance =
3343 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003344
Lloyd Pique441d5042018-10-18 16:49:51 -07003345 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003346 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003347 getHwComposer()
3348 .hasDisplayCapability(displayId,
3349 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003350
Peiyong Lind3788632018-09-18 16:01:31 -07003351 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003352 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3353 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003354 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003355 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003356 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003357
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 /*
3359 * and then, render the layers targeted at the framebuffer
3360 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003361
Dan Stoza9e56aa02015-11-02 13:00:03 -08003362 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003363 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003364 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003366 const Region viewportRegion(displayState.viewport);
3367 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003368 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003369 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003370 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003371 switch (layer->getCompositionType(displayDevice)) {
3372 case Hwc2::IComposerClient::Composition::CURSOR:
3373 case Hwc2::IComposerClient::Composition::DEVICE:
3374 case Hwc2::IComposerClient::Composition::SIDEBAND:
3375 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003376 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003377 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003378 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003380 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003381 // never clear the very first layer since we're
3382 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 renderengine::LayerSettings layerSettings;
3384 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003385 bool prepared =
3386 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3387 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003388
3389 if (prepared) {
3390 layerSettings.source.buffer.buffer = nullptr;
3391 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3392 layerSettings.alpha = half(0.0);
3393 layerSettings.disableBlending = true;
3394 clientCompositionLayers.push_back(layerSettings);
3395 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003396 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003397 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003398 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003399 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003400 renderengine::LayerSettings layerSettings;
3401 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003402 layer->prepareClientLayer(renderArea, clip, clearRegion,
3403 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 if (prepared) {
3405 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003406 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 break;
3408 }
3409 default:
3410 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003411 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 } else {
3413 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003417
Alec Mouri820c7402019-01-23 13:02:39 -08003418 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003419 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003420 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003421
3422 // We boost GPU frequency here because there will be color spaces conversion
3423 // and it's expensive. We boost the GPU frequency so that GPU composition can
3424 // finish in time. We must reset GPU frequency afterwards, because high frequency
3425 // consumes extra battery.
3426 const bool expensiveRenderingExpected =
3427 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3428 if (expensiveRenderingExpected && displayId) {
3429 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3430 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003431 if (!debugRegion.isEmpty()) {
3432 Region::const_iterator it = debugRegion.begin();
3433 Region::const_iterator end = debugRegion.end();
3434 while (it != end) {
3435 const Rect& rect = *it++;
3436 renderengine::LayerSettings layerSettings;
3437 layerSettings.source.buffer.buffer = nullptr;
3438 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3439 layerSettings.geometry.boundaries = rect.toFloatRect();
3440 layerSettings.alpha = half(1.0);
3441 clientCompositionLayers.push_back(layerSettings);
3442 }
3443 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003444 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3445 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003446 if (expensiveRenderingExpected && displayId) {
3447 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3448 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003449 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003450 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003451}
3452
Chia-I Wu28e3a252018-09-07 12:05:02 -07003453void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003454 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003455 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456}
3457
Dan Stoza7d89d062015-04-30 13:29:25 -07003458status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003459 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003460 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003461 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 const sp<Layer>& parent,
3463 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003464{
Dan Stoza7d89d062015-04-30 13:29:25 -07003465 // add this layer to the current state list
3466 {
3467 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003468 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003469 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3470 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003471 return NO_MEMORY;
3472 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003473 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003475 } else if (parent == nullptr) {
3476 lbc->onRemovedFromCurrentState();
3477 } else if (parent->isRemovedFromCurrentState()) {
3478 parent->addChild(lbc);
3479 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003480 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003481 parent->addChild(lbc);
3482 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003483
Yiwei Zhang243b3782018-05-15 17:40:04 -07003484 if (gbc != nullptr) {
3485 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3486 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3487 mMaxGraphicBufferProducerListSize,
3488 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3489 mGraphicBufferProducerList.size(),
3490 mMaxGraphicBufferProducerListSize, mNumLayers);
3491 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003492 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003493 }
3494
Mathias Agopian96f08192010-06-02 23:28:45 -07003495 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003496 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003497
Dan Stoza7d89d062015-04-30 13:29:25 -07003498 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003499}
3500
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003501uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003502 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003503}
3504
Mathias Agopian3f844832013-08-07 21:24:32 -07003505uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003506 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507}
3508
Mathias Agopian3f844832013-08-07 21:24:32 -07003509uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003510 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003511}
3512
3513uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003514 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003515 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003516 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003518 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
3520 return old;
3521}
3522
Marissa Wall713b63f2018-10-17 15:42:43 -07003523bool SurfaceFlinger::flushTransactionQueues() {
3524 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003525 bool flushedATransaction = false;
3526
Marissa Wall713b63f2018-10-17 15:42:43 -07003527 auto it = mTransactionQueues.begin();
3528 while (it != mTransactionQueues.end()) {
3529 auto& [applyToken, transactionQueue] = *it;
3530
3531 while (!transactionQueue.empty()) {
Marissa Wall78b72202019-03-15 14:58:34 -07003532 const auto&
Marissa Wall3dad52d2019-03-22 14:03:19 -07003533 [states, displays, flags, desiredPresentTime, uncacheBuffer, listenerCallbacks,
3534 postTime, privileged] = transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003535 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003536 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003537 break;
3538 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003539 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003540 desiredPresentTime, uncacheBuffer, listenerCallbacks, postTime,
3541 privileged, /*isMainThread*/ true);
Marissa Wall713b63f2018-10-17 15:42:43 -07003542 transactionQueue.pop();
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003543 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003544 }
3545
3546 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3547 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003548 return flushedATransaction;
3549}
3550
3551bool SurfaceFlinger::transactionFlushNeeded() {
3552 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003553}
3554
chaviwca27f252018-02-06 16:46:39 -08003555bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3556 for (const ComposerState& state : states) {
3557 // Here we need to check that the interface we're given is indeed
3558 // one of our own. A malicious client could give us a nullptr
3559 // IInterface, or one of its own or even one of our own but a
3560 // different type. All these situations would cause us to crash.
3561 if (state.client == nullptr) {
3562 return true;
3563 }
3564
3565 sp<IBinder> binder = IInterface::asBinder(state.client);
3566 if (binder == nullptr) {
3567 return true;
3568 }
3569
3570 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3571 return true;
3572 }
3573 }
3574 return false;
3575}
3576
Marissa Wall17b4e452018-12-26 16:32:34 -08003577bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3578 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003579 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003580 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3581 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3582 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3583 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3584 return false;
3585 }
3586
Marissa Wall713b63f2018-10-17 15:42:43 -07003587 for (const ComposerState& state : states) {
3588 const layer_state_t& s = state.state;
3589 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3590 continue;
3591 }
3592 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003593 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 }
3595 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003596 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003597}
3598
3599void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3600 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003601 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003602 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003603 int64_t desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003604 const cached_buffer_t& uncacheBuffer,
3605 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003606 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003607
Valerie Haubc6ddb12019-03-08 11:10:15 -08003608 const int64_t postTime = systemTime();
3609
Robert Carr14167e02019-02-13 13:50:55 -08003610 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3611
Mathias Agopian698c0872011-06-28 19:09:31 -07003612 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003613
chaviwca27f252018-02-06 16:46:39 -08003614 if (containsAnyInvalidClientState(states)) {
3615 return;
3616 }
3617
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 // If its TransactionQueue already has a pending TransactionState or if it is pending
3619 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003621 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003622 uncacheBuffer, listenerCallbacks, postTime,
3623 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003624 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003625 return;
3626 }
3627
Valerie Haubc6ddb12019-03-08 11:10:15 -08003628 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003629 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003630}
3631
3632void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003633 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003634 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003635 const int64_t desiredPresentTime,
3636 const cached_buffer_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003637 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003638 const int64_t postTime, bool privileged,
3639 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003640 uint32_t transactionFlags = 0;
3641
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003642 if (flags & eAnimation) {
3643 // For window updates that are part of an animation we must wait for
3644 // previous animation "frames" to be handled.
3645 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003646 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003647 if (CC_UNLIKELY(err != NO_ERROR)) {
3648 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003649 // caller after a few seconds.
3650 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3651 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003652 mAnimTransactionPending = false;
3653 break;
3654 }
3655 }
3656 }
3657
chaviwca27f252018-02-06 16:46:39 -08003658 for (const DisplayState& display : displays) {
3659 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003660 }
3661
Marissa Walle2ffb422018-10-12 11:33:52 -07003662 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003663 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003664 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3665 postTime, privileged);
3666 }
3667
3668 // In case the client has sent a Transaction that should receive callbacks but without any
3669 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3670 // to the callback thread so it can send an empty callback
3671 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3672 mTransactionCompletedThread.addCallback(listener, callbackIds);
chaviwca27f252018-02-06 16:46:39 -08003673 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003674 // If the state doesn't require a traversal and there are callbacks, send them now
3675 if (!(clientStateFlags & eTraversalNeeded)) {
3676 mTransactionCompletedThread.sendCallbacks();
3677 }
3678 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003679
chaviw273171b2018-12-26 11:46:30 -08003680 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3681
Marissa Wall78b72202019-03-15 14:58:34 -07003682 if (uncacheBuffer.token) {
3683 BufferStateLayerCache::getInstance().erase(uncacheBuffer.token, uncacheBuffer.cacheId);
3684 }
3685
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003686 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3687 // anyway. This can be used as a flush mechanism for previous async transactions.
3688 // Empty animation transaction can be used to simulate back-pressure, so also force a
3689 // transaction for empty animation transactions.
3690 if (transactionFlags == 0 &&
3691 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003692 transactionFlags = eTransactionNeeded;
3693 }
3694
Marissa Wall06255332019-03-27 13:48:27 -07003695 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3696 // so we don't have to wake up again next frame to preform an uneeded traversal.
3697 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3698 transactionFlags = transactionFlags & (~eTraversalNeeded);
3699 mTraversalNeededMainThread = true;
3700 }
3701
Mathias Agopian386aa982011-11-07 21:58:03 -08003702 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003703 if (mInterceptor->isEnabled()) {
3704 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003705 }
Irvel468051e2016-06-13 16:44:44 -07003706
Mathias Agopian386aa982011-11-07 21:58:03 -08003707 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003708 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3709 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003710 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003711
3712 // if this is a synchronous transaction, wait for it to take effect
3713 // before returning.
3714 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003715 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003716 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003717 if (flags & eAnimation) {
3718 mAnimTransactionPending = true;
3719 }
chaviw95ef3c42019-02-14 10:55:09 -08003720
3721 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
Valerie Hau0779ded2019-03-19 12:43:04 -07003722
3723 // applyTransactionState can be called by either the main SF thread or by
3724 // another process through setTransactionState. While a given process may wish
3725 // to wait on synchronous transactions, the main SF thread should never
3726 // be blocked. Therefore, we only wait if isMainThread is false.
3727 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003728 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3729 if (CC_UNLIKELY(err != NO_ERROR)) {
3730 // just in case something goes wrong in SF, return to the
3731 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003732 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3733 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003734 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003735 break;
3736 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 }
3739}
3740
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003741uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3742 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3743 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003744
Mathias Agopiane57f2922012-08-09 16:29:12 -07003745 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003746 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3747
3748 const uint32_t what = s.what;
3749 if (what & DisplayState::eSurfaceChanged) {
3750 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3751 state.surface = s.surface;
3752 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003753 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003754 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003755 if (what & DisplayState::eLayerStackChanged) {
3756 if (state.layerStack != s.layerStack) {
3757 state.layerStack = s.layerStack;
3758 flags |= eDisplayTransactionNeeded;
3759 }
3760 }
3761 if (what & DisplayState::eDisplayProjectionChanged) {
3762 if (state.orientation != s.orientation) {
3763 state.orientation = s.orientation;
3764 flags |= eDisplayTransactionNeeded;
3765 }
3766 if (state.frame != s.frame) {
3767 state.frame = s.frame;
3768 flags |= eDisplayTransactionNeeded;
3769 }
3770 if (state.viewport != s.viewport) {
3771 state.viewport = s.viewport;
3772 flags |= eDisplayTransactionNeeded;
3773 }
3774 }
3775 if (what & DisplayState::eDisplaySizeChanged) {
3776 if (state.width != s.width) {
3777 state.width = s.width;
3778 flags |= eDisplayTransactionNeeded;
3779 }
3780 if (state.height != s.height) {
3781 state.height = s.height;
3782 flags |= eDisplayTransactionNeeded;
3783 }
3784 }
3785
Mathias Agopiane57f2922012-08-09 16:29:12 -07003786 return flags;
3787}
3788
Robert Carr14167e02019-02-13 13:50:55 -08003789bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003790 IPCThreadState* ipc = IPCThreadState::self();
3791 const int pid = ipc->getCallingPid();
3792 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003793 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003794 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003795 return false;
3796 }
3797 return true;
3798}
3799
Marissa Wall3dad52d2019-03-22 14:03:19 -07003800uint32_t SurfaceFlinger::setClientStateLocked(
3801 const ComposerState& composerState, int64_t desiredPresentTime,
3802 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3803 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003804 const layer_state_t& s = composerState.state;
3805 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3806
Mathias Agopian13127d82013-03-05 17:47:11 -08003807 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003808 if (layer == nullptr) {
3809 return 0;
3810 }
3811
chaviw8b3871a2017-11-01 17:41:01 -07003812 uint32_t flags = 0;
3813
Garfield Tan8a3083e2018-12-03 13:21:07 -08003814 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003815 bool geometryAppliesWithResize =
3816 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003817
3818 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3819 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003820 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003821 layer->pushPendingState();
3822 }
3823
chaviw8b3871a2017-11-01 17:41:01 -07003824 if (what & layer_state_t::ePositionChanged) {
3825 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3826 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003827 }
chaviw8b3871a2017-11-01 17:41:01 -07003828 }
3829 if (what & layer_state_t::eLayerChanged) {
3830 // NOTE: index needs to be calculated before we update the state
3831 const auto& p = layer->getParent();
3832 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003833 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003834 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003835 mCurrentState.layersSortedByZ.removeAt(idx);
3836 mCurrentState.layersSortedByZ.add(layer);
3837 // we need traversal (state changed)
3838 // AND transaction (list changed)
3839 flags |= eTransactionNeeded|eTraversalNeeded;
3840 }
chaviw8b3871a2017-11-01 17:41:01 -07003841 } else {
3842 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003843 flags |= eTransactionNeeded|eTraversalNeeded;
3844 }
3845 }
chaviw8b3871a2017-11-01 17:41:01 -07003846 }
3847 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003848 // NOTE: index needs to be calculated before we update the state
3849 const auto& p = layer->getParent();
3850 if (p == nullptr) {
3851 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3852 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3853 mCurrentState.layersSortedByZ.removeAt(idx);
3854 mCurrentState.layersSortedByZ.add(layer);
3855 // we need traversal (state changed)
3856 // AND transaction (list changed)
3857 flags |= eTransactionNeeded|eTraversalNeeded;
3858 }
3859 } else {
3860 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3861 flags |= eTransactionNeeded|eTraversalNeeded;
3862 }
chaviw8b3871a2017-11-01 17:41:01 -07003863 }
3864 }
3865 if (what & layer_state_t::eSizeChanged) {
3866 if (layer->setSize(s.w, s.h)) {
3867 flags |= eTraversalNeeded;
3868 }
3869 }
3870 if (what & layer_state_t::eAlphaChanged) {
3871 if (layer->setAlpha(s.alpha))
3872 flags |= eTraversalNeeded;
3873 }
3874 if (what & layer_state_t::eColorChanged) {
3875 if (layer->setColor(s.color))
3876 flags |= eTraversalNeeded;
3877 }
Peiyong Lind3788632018-09-18 16:01:31 -07003878 if (what & layer_state_t::eColorTransformChanged) {
3879 if (layer->setColorTransform(s.colorTransform)) {
3880 flags |= eTraversalNeeded;
3881 }
3882 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003883 if (what & layer_state_t::eBackgroundColorChanged) {
3884 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3885 flags |= eTraversalNeeded;
3886 }
3887 }
chaviw8b3871a2017-11-01 17:41:01 -07003888 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003889 // TODO: b/109894387
3890 //
3891 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3892 // rotation. To see the problem observe that if we have a square parent, and a child
3893 // of the same size, then we rotate the child 45 degrees around it's center, the child
3894 // must now be cropped to a non rectangular 8 sided region.
3895 //
3896 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3897 // private API, and the WindowManager only uses rotation in one case, which is on a top
3898 // level layer in which cropping is not an issue.
3899 //
3900 // However given that abuse of rotation matrices could lead to surfaces extending outside
3901 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3902 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3903 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003904 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003905 flags |= eTraversalNeeded;
3906 }
3907 if (what & layer_state_t::eTransparentRegionChanged) {
3908 if (layer->setTransparentRegionHint(s.transparentRegion))
3909 flags |= eTraversalNeeded;
3910 }
3911 if (what & layer_state_t::eFlagsChanged) {
3912 if (layer->setFlags(s.flags, s.mask))
3913 flags |= eTraversalNeeded;
3914 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003915 if (what & layer_state_t::eCropChanged_legacy) {
3916 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003917 flags |= eTraversalNeeded;
3918 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003919 if (what & layer_state_t::eCornerRadiusChanged) {
3920 if (layer->setCornerRadius(s.cornerRadius))
3921 flags |= eTraversalNeeded;
3922 }
chaviw8b3871a2017-11-01 17:41:01 -07003923 if (what & layer_state_t::eLayerStackChanged) {
3924 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3925 // We only allow setting layer stacks for top level layers,
3926 // everything else inherits layer stack from its parent.
3927 if (layer->hasParent()) {
3928 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3929 layer->getName().string());
3930 } else if (idx < 0) {
3931 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3932 "that also does not appear in the top level layer list. Something"
3933 " has gone wrong.", layer->getName().string());
3934 } else if (layer->setLayerStack(s.layerStack)) {
3935 mCurrentState.layersSortedByZ.removeAt(idx);
3936 mCurrentState.layersSortedByZ.add(layer);
3937 // we need traversal (state changed)
3938 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003939 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003940 }
3941 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003942 if (what & layer_state_t::eDeferTransaction_legacy) {
3943 if (s.barrierHandle_legacy != nullptr) {
3944 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3945 } else if (s.barrierGbp_legacy != nullptr) {
3946 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003947 if (authenticateSurfaceTextureLocked(gbp)) {
3948 const auto& otherLayer =
3949 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003950 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003951 } else {
3952 ALOGE("Attempt to defer transaction to to an"
3953 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003954 }
3955 }
chaviw8b3871a2017-11-01 17:41:01 -07003956 // We don't trigger a traversal here because if no other state is
3957 // changed, we don't want this to cause any more work
3958 }
3959 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003960 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003961 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003962 if (!hadParent) {
3963 mCurrentState.layersSortedByZ.remove(layer);
3964 }
chaviw8b3871a2017-11-01 17:41:01 -07003965 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003966 }
chaviw8b3871a2017-11-01 17:41:01 -07003967 }
3968 if (what & layer_state_t::eReparentChildren) {
3969 if (layer->reparentChildren(s.reparentHandle)) {
3970 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003971 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003972 }
chaviw8b3871a2017-11-01 17:41:01 -07003973 if (what & layer_state_t::eDetachChildren) {
3974 layer->detachChildren();
3975 }
3976 if (what & layer_state_t::eOverrideScalingModeChanged) {
3977 layer->setOverrideScalingMode(s.overrideScalingMode);
3978 // We don't trigger a traversal here because if no other state is
3979 // changed, we don't want this to cause any more work
3980 }
Marissa Wall61c58622018-07-18 10:12:20 -07003981 if (what & layer_state_t::eTransformChanged) {
3982 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3983 }
3984 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3985 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3986 flags |= eTraversalNeeded;
3987 }
3988 if (what & layer_state_t::eCropChanged) {
3989 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3990 }
Marissa Wall861616d2018-10-22 12:52:23 -07003991 if (what & layer_state_t::eFrameChanged) {
3992 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3993 }
Marissa Wall61c58622018-07-18 10:12:20 -07003994 if (what & layer_state_t::eAcquireFenceChanged) {
3995 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3996 }
3997 if (what & layer_state_t::eDataspaceChanged) {
3998 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eHdrMetadataChanged) {
4001 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4004 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4005 }
4006 if (what & layer_state_t::eApiChanged) {
4007 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eSidebandStreamChanged) {
4010 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4011 }
Robert Carr720e5062018-07-30 17:45:14 -07004012 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004013 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004014 layer->setInputInfo(s.inputInfo);
4015 flags |= eTraversalNeeded;
4016 } else {
4017 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4018 }
Robert Carr720e5062018-07-30 17:45:14 -07004019 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004020 if (what & layer_state_t::eMetadataChanged) {
4021 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4022 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004023 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4024 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4025 flags |= eTraversalNeeded;
4026 }
4027 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004028 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004029 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004030 mTransactionCompletedThread.run();
Marissa Wall3dad52d2019-03-22 14:03:19 -07004031 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004032 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4033 }
4034 }
Marissa Wall78b72202019-03-15 14:58:34 -07004035 bool bufferChanged = what & layer_state_t::eBufferChanged;
4036 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4037 sp<GraphicBuffer> buffer;
4038 if (bufferChanged && cacheIdChanged) {
4039 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.cacheId,
Marissa Wall73411622019-01-25 10:45:41 -08004040 s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004041 buffer = s.buffer;
4042 } else if (cacheIdChanged) {
4043 buffer = BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4044 s.cachedBuffer.cacheId);
4045 } else if (bufferChanged) {
4046 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004047 }
Marissa Wall78b72202019-03-15 14:58:34 -07004048 if (buffer) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004049 if (layer->setBuffer(buffer)) {
4050 flags |= eTraversalNeeded;
4051 layer->setPostTime(postTime);
4052 layer->setDesiredPresentTime(desiredPresentTime);
4053 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004054 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004055 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4056 // Do not put anything that updates layer state or modifies flags after
4057 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004058 return flags;
4059}
4060
chaviw273171b2018-12-26 11:46:30 -08004061uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4062 uint32_t flags = 0;
4063 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4064 flags |= eTraversalNeeded;
4065 }
4066
chaviwa911b102019-02-14 10:18:33 -08004067 if (inputWindowCommands.syncInputWindows) {
4068 flags |= eTraversalNeeded;
4069 }
4070
Vishnu Nairec0ab382019-02-13 15:32:56 -08004071 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004072 return flags;
4073}
4074
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004075status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4076 uint32_t h, PixelFormat format, uint32_t flags,
4077 LayerMetadata metadata, sp<IBinder>* handle,
4078 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004079 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004080 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004081 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004082 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004083 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004084
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004085 status_t result = NO_ERROR;
4086
4087 sp<Layer> layer;
4088
Cody Northropbc755282017-03-31 12:00:08 -06004089 String8 uniqueName = getUniqueLayerName(name);
4090
Evan Roskya1f1e152019-01-24 16:17:46 -08004091 bool primaryDisplayOnly = false;
4092
4093 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4094 // TODO b/64227542
4095 if (metadata.has(METADATA_WINDOW_TYPE)) {
4096 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4097 if (windowType == 441731) {
4098 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4099 primaryDisplayOnly = true;
4100 }
4101 }
4102
Mathias Agopian3165cc22012-08-08 19:42:09 -07004103 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004104 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004105 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4106 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004108 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004109 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004110 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4111 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004112 break;
chaviw13fdc492017-06-27 12:40:18 -07004113 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004114 // check if buffer size is set for color layer.
4115 if (w > 0 || h > 0) {
4116 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4117 int(w), int(h));
4118 return BAD_VALUE;
4119 }
4120
Evan Roskya1f1e152019-01-24 16:17:46 -08004121 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4122 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004123 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004124 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004125 // check if buffer size is set for container layer.
4126 if (w > 0 || h > 0) {
4127 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4128 int(w), int(h));
4129 return BAD_VALUE;
4130 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004131 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4132 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004133 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 default:
4135 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 break;
4137 }
4138
Dan Stoza7d89d062015-04-30 13:29:25 -07004139 if (result != NO_ERROR) {
4140 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004141 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004142
Evan Roskya1f1e152019-01-24 16:17:46 -08004143 if (primaryDisplayOnly) {
4144 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004145 }
4146
Robert Carrb89ea9d2018-12-10 13:01:14 -08004147 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4148 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4149 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004150 if (result != NO_ERROR) {
4151 return result;
4152 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004153 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004154
4155 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157}
4158
Cody Northropbc755282017-03-31 12:00:08 -06004159String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4160{
4161 bool matchFound = true;
4162 uint32_t dupeCounter = 0;
4163
4164 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4165 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4166
Dan Stoza436ccf32018-06-21 12:10:12 -07004167 // Grab the state lock since we're accessing mCurrentState
4168 Mutex::Autolock lock(mStateLock);
4169
Cody Northropbc755282017-03-31 12:00:08 -06004170 // Loop over layers until we're sure there is no matching name
4171 while (matchFound) {
4172 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004173 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004174 if (layer->getName() == uniqueName) {
4175 matchFound = true;
4176 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4177 }
4178 });
4179 }
4180
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004181 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4182 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004183
4184 return uniqueName;
4185}
4186
Marissa Wallfd668622018-05-10 10:21:13 -07004187status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4188 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004189 LayerMetadata metadata, PixelFormat& format,
4190 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004191 sp<IGraphicBufferProducer>* gbp,
4192 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004194 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 case PIXEL_FORMAT_TRANSPARENT:
4196 case PIXEL_FORMAT_TRANSLUCENT:
4197 format = PIXEL_FORMAT_RGBA_8888;
4198 break;
4199 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004200 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201 break;
4202 }
4203
Evan Roskya1f1e152019-01-24 16:17:46 -08004204 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4205 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004206 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004207 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004208 *handle = layer->getHandle();
4209 *gbp = layer->getProducer();
4210 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004211 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004212
Marissa Wallfd668622018-05-10 10:21:13 -07004213 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004214 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004215}
4216
Marissa Wall61c58622018-07-18 10:12:20 -07004217status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4218 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004219 LayerMetadata metadata, sp<IBinder>* handle,
4220 sp<Layer>* outLayer) {
4221 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4222 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004223 *handle = layer->getHandle();
4224 *outLayer = layer;
4225
4226 return NO_ERROR;
4227}
4228
Evan Roskya1f1e152019-01-24 16:17:46 -08004229status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4230 uint32_t h, uint32_t flags, LayerMetadata metadata,
4231 sp<IBinder>* handle, sp<Layer>* outLayer) {
4232 *outLayer = getFactory().createColorLayer(
4233 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004234 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004235 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004236}
4237
Evan Roskya1f1e152019-01-24 16:17:46 -08004238status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4239 uint32_t w, uint32_t h, uint32_t flags,
4240 LayerMetadata metadata, sp<IBinder>* handle,
4241 sp<Layer>* outLayer) {
4242 *outLayer = getFactory().createContainerLayer(
4243 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004244 *handle = (*outLayer)->getHandle();
4245 return NO_ERROR;
4246}
4247
4248
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004249void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004250 mLayersPendingRemoval.add(layer);
4251 mLayersRemoved = true;
4252 setTransactionFlags(eTransactionNeeded);
4253}
4254
Robert Carr695d5282018-12-18 15:27:58 -08004255void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004256{
Robert Carr2e102c92018-10-23 12:11:15 -07004257 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004258 // If a layer has a parent, we allow it to out-live it's handle
4259 // with the idea that the parent holds a reference and will eventually
4260 // be cleaned up. However no one cleans up the top-level so we do so
4261 // here.
4262 if (layer->getParent() == nullptr) {
4263 mCurrentState.layersSortedByZ.remove(layer);
4264 }
4265 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004266 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004267}
4268
Mathias Agopianb60314a2012-04-10 22:09:54 -07004269// ---------------------------------------------------------------------------
4270
Andy McFadden13a082e2012-08-24 10:16:42 -07004271void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004272 const auto display = getDefaultDisplayDeviceLocked();
4273 if (!display) return;
4274
4275 const sp<IBinder> token = display->getDisplayToken().promote();
4276 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004277
Jesse Hall01e29052013-02-19 16:13:35 -08004278 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004279 Vector<ComposerState> state;
4280 Vector<DisplayState> displays;
4281 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004282 d.what = DisplayState::eDisplayProjectionChanged |
4283 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004284 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004285 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004286 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004287 d.frame.makeInvalid();
4288 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004289 d.width = 0;
4290 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004291 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004292 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004293
Dominik Laskowskie9774092018-12-11 10:04:24 -08004294 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004295
Dominik Laskowski83b88212018-12-11 13:34:06 -08004296 const nsecs_t vsyncPeriod = getVsyncPeriod();
4297 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004298
Brian Andersond0010582017-03-07 13:20:31 -08004299 // Use phase of 0 since phase is not known.
4300 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004301 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004302 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004303}
4304
4305void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004306 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004307 postMessageAsync(
4308 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004309}
4310
Dominik Laskowskie9774092018-12-11 10:04:24 -08004311void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004312 if (display->isVirtual()) {
4313 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314 return;
4315 }
4316
Dominik Laskowski075d3172018-05-24 15:50:06 -07004317 const auto displayId = display->getId();
4318 LOG_ALWAYS_FATAL_IF(!displayId);
4319
Dominik Laskowski34157762018-10-31 13:07:19 -07004320 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321
4322 int currentMode = display->getPowerMode();
4323 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004324 return;
4325 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 display->setPowerMode(mode);
4328
Lloyd Pique4dccc412018-01-22 17:21:36 -08004329 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004330 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004331 }
4332
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004333 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004334 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004335 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004336 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004337 mScheduler->onScreenAcquired(mAppConnectionHandle);
4338 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004339 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004340
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004341 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004342 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004343 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004344
4345 struct sched_param param = {0};
4346 param.sched_priority = 1;
4347 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4348 ALOGW("Couldn't set SCHED_FIFO on display on");
4349 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004350 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004351 // Turn off the display
4352 struct sched_param param = {0};
4353 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4354 ALOGW("Couldn't set SCHED_OTHER on display off");
4355 }
4356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004358 mScheduler->disableHardwareVsync(true);
4359 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004360 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004361
Dominik Laskowski075d3172018-05-24 15:50:06 -07004362 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004363 mVisibleRegionsDirty = true;
4364 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004365 } else if (mode == HWC_POWER_MODE_DOZE ||
4366 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004367 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004368 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004370 mScheduler->onScreenAcquired(mAppConnectionHandle);
4371 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004372 }
4373 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4374 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004375 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004376 mScheduler->disableHardwareVsync(true);
4377 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004378 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004379 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004380 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004381 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004382 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004383 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004385 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004386 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004387 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004388 // Update refresh rate stats.
4389 mRefreshRateStats->setPowerMode(mode);
4390 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004391 }
4392
Dominik Laskowski34157762018-10-31 13:07:19 -07004393 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004394}
4395
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004396void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004397 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004398 const auto display = getDisplayDevice(displayToken);
4399 if (!display) {
4400 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4401 displayToken.get());
4402 } else if (display->isVirtual()) {
4403 ALOGW("Attempt to set power mode %d for virtual display", mode);
4404 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004405 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004406 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004408}
4409
4410// ---------------------------------------------------------------------------
4411
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4413 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004415
Mathias Agopianbd115332013-04-18 16:41:04 -07004416 IPCThreadState* ipc = IPCThreadState::self();
4417 const int pid = ipc->getCallingPid();
4418 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004419
Mathias Agopianbd115332013-04-18 16:41:04 -07004420 if ((uid != AID_SHELL) &&
4421 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4423 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004425 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004426 // (this would indicate SF is stuck, but we want to be able to
4427 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004428 status_t err = mStateLock.timedLock(s2ns(1));
4429 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004430 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result,
4432 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4433 "(no locks held)\n",
4434 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004435 }
4436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004438
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439 static const std::unordered_map<std::string, Dumper> dumpers = {
4440 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4441 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4442 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004443 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004444 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004445 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004446 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4447 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4449 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4450 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4451 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4452 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4453 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4456 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004459
Dominik Laskowskic2867142019-01-21 11:33:38 -08004460 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4461 (it->second)(args, asProto, result);
4462 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004463 if (asProto) {
4464 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4465 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4466 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004468 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004469 }
4470
Mathias Agopian9795c422009-08-26 16:36:26 -07004471 if (locked) {
4472 mStateLock.unlock();
4473 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 return NO_ERROR;
4477}
4478
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004479status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4480 if (asProto && mTracing.isEnabled()) {
4481 mTracing.writeToFileAsync();
4482 }
4483
4484 return doDump(fd, DumpArgs(), asProto);
4485}
4486
Dominik Laskowskic2867142019-01-21 11:33:38 -08004487void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 mCurrentState.traverseInZOrder(
4489 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004490}
4491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004493 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004494
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495 if (args.size() > 1) {
4496 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004497 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004498 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004499 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004500 }
Robert Carr2047fae2016-11-28 14:09:09 -08004501 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004502 } else {
4503 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504 }
4505}
4506
Dominik Laskowskic2867142019-01-21 11:33:38 -08004507void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004508 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004509 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004510 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004511 }
Robert Carr2047fae2016-11-28 14:09:09 -08004512 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004513
Svetoslavd85084b2014-03-20 10:28:31 -07004514 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004515}
4516
Dominik Laskowskic2867142019-01-21 11:33:38 -08004517void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4518 mTimeStats->parseArgs(asProto, args, result);
4519}
4520
Jamie Gennis6547ff42013-07-16 20:12:42 -07004521// This should only be called from the main thread. Otherwise it would need
4522// the lock and should use mCurrentState rather than mDrawingState.
4523void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004524 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004525 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004526 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004527
4528 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4529}
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004532 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004533
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004534 if (isLayerTripleBufferingDisabled())
4535 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4538 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4539 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4540 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4541 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4542 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004543 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004544}
4545
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004546void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004547 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004548 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004549 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004550 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551
Ady Abraham97d04232019-03-05 19:48:12 -08004552 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004553 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4554 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004555 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004556}
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4559 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004560 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4561 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004562 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004563 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004565 }
David Sodman4a36e932017-11-07 14:29:47 -08004566 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004567 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004568 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4570 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004571}
4572
Dan Stozae77c7662016-05-13 11:37:28 -07004573void SurfaceFlinger::recordBufferingStats(const char* layerName,
4574 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004575 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4576 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004577 for (const auto& segment : history) {
4578 if (!segment.usedThirdBuffer) {
4579 stats.twoBufferTime += segment.totalTime;
4580 }
4581 if (segment.occupancyAverage < 1.0f) {
4582 stats.doubleBufferedTime += segment.totalTime;
4583 } else if (segment.occupancyAverage < 2.0f) {
4584 stats.tripleBufferedTime += segment.totalTime;
4585 }
4586 ++stats.numSegments;
4587 stats.totalTime += segment.totalTime;
4588 }
4589}
4590
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4592 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004593
4594 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4595 const size_t count = currentLayers.size();
4596 for (size_t i=0 ; i<count ; i++) {
4597 currentLayers[i]->dumpFrameEvents(result);
4598 }
4599}
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004602 result.append("Buffering stats:\n");
4603 result.append(" [Layer name] <Active time> <Two buffer> "
4604 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004605 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004606 typedef std::tuple<std::string, float, float, float> BufferTuple;
4607 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004608 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004609 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004610 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004611 if (stats.numSegments == 0) {
4612 continue;
4613 }
4614 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4615 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4616 stats.totalTime;
4617 float doubleBufferRatio = static_cast<float>(
4618 stats.doubleBufferedTime) / stats.totalTime;
4619 float tripleBufferRatio = static_cast<float>(
4620 stats.tripleBufferedTime) / stats.totalTime;
4621 sorted.insert({activeTime, {name, twoBufferRatio,
4622 doubleBufferRatio, tripleBufferRatio}});
4623 }
4624 for (const auto& sortedPair : sorted) {
4625 float activeTime = sortedPair.first;
4626 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4628 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004629 }
4630 result.append("\n");
4631}
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004634 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004635 const auto displayId = display->getId();
4636 if (!displayId) {
4637 continue;
4638 }
4639 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result,
4645 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4646 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 uint8_t port;
4648 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004649 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 result.append("no identification data\n");
4651 continue;
4652 }
4653
4654 if (!isEdid(data)) {
4655 result.append("unknown identification data: ");
4656 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 }
4659 result.append("\n");
4660 continue;
4661 }
4662
4663 const auto edid = parseEdid(data);
4664 if (!edid) {
4665 result.append("invalid EDID: ");
4666 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004668 }
4669 result.append("\n");
4670 continue;
4671 }
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 result.append(edid->displayName.data(), edid->displayName.length());
4675 result.append("\"\n");
4676 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004677}
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4680 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4681 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4682 StringAppendF(&result, "DisplayColorSetting: %s\n",
4683 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684
4685 // TODO: print out if wide-color mode is active or not
4686
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004687 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 const auto displayId = display->getId();
4689 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004690 continue;
4691 }
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004695 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004697 }
4698
Lloyd Pique32cbe282018-10-19 13:09:22 -07004699 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, " Current color mode: %s (%d)\n",
4701 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004702 }
4703 result.append("\n");
4704}
4705
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004706LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4707 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004708 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004709 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4710 const State& state = useDrawing ? mDrawingState : mCurrentState;
4711 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004712 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004713 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004714 });
4715
4716 return layersProto;
4717}
4718
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004719LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4720 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004721 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004722
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004723 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004724 resolution->set_w(displayDevice->getWidth());
4725 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004726
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004727 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004728 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004729
Lloyd Pique32cbe282018-10-19 13:09:22 -07004730 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4731 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4732 layersProto.set_global_transform(displayState.orientation);
4733
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004734 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004735 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004736 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004737 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004738 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004739 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004740 }
4741 });
4742
4743 return layersProto;
4744}
4745
Dominik Laskowskic2867142019-01-21 11:33:38 -08004746void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4747 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 Colorizer colorizer(colorize);
4749
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750 // figure out if we're stuck somewhere
4751 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004753 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4754
4755 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004756 * Dump library configuration.
4757 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004758
4759 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004760 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004761 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004762 appendSfConfigString(result);
4763 appendUiConfigString(result);
4764 appendGuiConfigString(result);
4765 result.append("\n");
4766
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004767 result.append("\nDisplay identification data:\n");
4768 dumpDisplayIdentificationData(result);
4769
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004770 result.append("\nWide-Color information:\n");
4771 dumpWideColorInfo(result);
4772
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004774 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004776 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004777 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004778
Andy McFadden41d67d72014-04-25 16:58:34 -07004779 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004780 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004781 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004782 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004783 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004784
Dan Stozab90cf072015-03-05 11:05:59 -08004785 dumpStaticScreenStats(result);
4786 result.append("\n");
4787
Alec Mouri40189b02019-03-05 15:07:54 -08004788 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4789 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4790 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004791
Dan Stozae77c7662016-05-13 11:37:28 -07004792 dumpBufferingStats(result);
4793
Andy McFadden4803b742012-09-24 19:07:20 -07004794 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004795 * Dump the visible layer list
4796 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004797 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4799 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4800 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004801 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004802
Chia-I Wu2f884132018-09-13 15:17:58 -07004803 {
4804 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4805 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004807 result.append("\n");
4808 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004809
Lloyd Pique207def92019-02-28 16:09:52 -08004810 {
4811 StringAppendF(&result, "Composition layers\n");
4812 mDrawingState.traverseInZOrder([&](Layer* layer) {
4813 auto compositionLayer = layer->getCompositionLayer();
4814 if (compositionLayer) compositionLayer->dump(result);
4815 });
4816 }
4817
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004818 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004819 * Dump Display state
4820 */
4821
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004824 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004825 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004827 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004828 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004829
4830 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004831 * Dump SurfaceFlinger global state
4832 */
4833
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004835 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004836 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004838 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839
Dominik Laskowski075d3172018-05-24 15:50:06 -07004840 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004841 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4842 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004843 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4844 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004845 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result,
4847 " transaction-flags : %08x\n"
4848 " gpu_to_cpu_unsupported : %d\n",
4849 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004850
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004851 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004852 displayId && getHwComposer().isConnected(*displayId)) {
4853 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004854 StringAppendF(&result,
4855 " refresh-rate : %f fps\n"
4856 " x-dpi : %f\n"
4857 " y-dpi : %f\n",
4858 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4859 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004860 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861
Yiwei Zhang5434a782018-12-05 18:06:32 -08004862 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004863
Dan Stozae22aec72016-08-01 13:20:59 -07004864 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004865 * Tracing state
4866 */
4867 mTracing.dump(result);
4868 result.append("\n");
4869
4870 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004871 * HWC layer minidump
4872 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004873 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 const auto displayId = display->getId();
4875 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004876 continue;
4877 }
4878
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004880 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004881 const sp<DisplayDevice> displayDevice = display;
4882 mCurrentState.traverseInZOrder(
4883 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004884 result.append("\n");
4885 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004886
4887 /*
4888 * Dump HWComposer state
4889 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004890 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004891 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004892 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004893 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004895 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004896
4897 /*
4898 * Dump gralloc state
4899 */
4900 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4901 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004902
4903 /*
4904 * Dump VrFlinger state if in use.
4905 */
4906 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4907 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004908 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004909 result.append("\n");
4910 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004911
4912 /**
4913 * Scheduler dump state.
4914 */
Ana Krulecc2870422019-01-29 19:00:58 -08004915 result.append("\nScheduler state:\n");
4916 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004917 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004918 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004919}
4920
Dominik Laskowski075d3172018-05-24 15:50:06 -07004921const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004922 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004923 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004924 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004925 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004926 }
4927 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004928
Dominik Laskowski34157762018-10-31 13:07:19 -07004929 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004930 static const Vector<sp<Layer>> empty;
4931 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004932}
4933
Chia-I Wu28f320b2018-05-03 11:02:56 -07004934void SurfaceFlinger::updateColorMatrixLocked() {
4935 mat4 colorMatrix;
4936 if (mGlobalSaturationFactor != 1.0f) {
4937 // Rec.709 luma coefficients
4938 float3 luminance{0.213f, 0.715f, 0.072f};
4939 luminance *= 1.0f - mGlobalSaturationFactor;
4940 mat4 saturationMatrix = mat4(
4941 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4942 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4943 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4944 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4945 );
4946 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4947 } else {
4948 colorMatrix = mClientColorMatrix * mDaltonizer();
4949 }
4950
4951 if (mCurrentState.colorMatrix != colorMatrix) {
4952 mCurrentState.colorMatrix = colorMatrix;
4953 mCurrentState.colorMatrixChanged = true;
4954 setTransactionFlags(eTransactionNeeded);
4955 }
4956}
4957
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004958status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959#pragma clang diagnostic push
4960#pragma clang diagnostic error "-Wswitch-enum"
4961 switch (static_cast<ISurfaceComposerTag>(code)) {
4962 // These methods should at minimum make sure that the client requested
4963 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004964 case BOOT_FINISHED:
4965 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966 case CREATE_DISPLAY:
4967 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004968 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 case GET_ANIMATION_FRAME_STATS:
4970 case GET_HDR_CAPABILITIES:
4971 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004972 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004973 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004975 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004976 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004977 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004978 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4979 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004980 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4981 IPCThreadState* ipc = IPCThreadState::self();
4982 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4983 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004984 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 }
Robert Carr1db73f62016-12-21 12:58:51 -08004986 return OK;
4987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004989 IPCThreadState* ipc = IPCThreadState::self();
4990 const int pid = ipc->getCallingPid();
4991 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4993 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004994 return PERMISSION_DENIED;
4995 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004996 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 // Used by apps to hook Choreographer to SurfaceFlinger.
4999 case CREATE_DISPLAY_EVENT_CONNECTION:
5000 // The following calls are currently used by clients that do not
5001 // request necessary permissions. However, they do not expose any secret
5002 // information, so it is OK to pass them.
5003 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005004 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005005 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005006 case GET_PHYSICAL_DISPLAY_IDS:
5007 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005009 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010 case GET_DISPLAY_CONFIGS:
5011 case GET_DISPLAY_STATS:
5012 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5013 // Calling setTransactionState is safe, because you need to have been
5014 // granted a reference to Client* and Handle* to do anything with it.
5015 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005016 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005017 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005018 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005019 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005020 case IS_WIDE_COLOR_DISPLAY:
5021 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5022 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 return OK;
5024 }
5025 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005026 case CAPTURE_SCREEN:
5027 case ADD_REGION_SAMPLING_LISTENER:
5028 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005030 IPCThreadState* ipc = IPCThreadState::self();
5031 const int pid = ipc->getCallingPid();
5032 const int uid = ipc->getCallingUid();
5033 if ((uid != AID_GRAPHICS) &&
5034 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5035 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5036 return PERMISSION_DENIED;
5037 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005038 return OK;
5039 }
5040 // The following codes are deprecated and should never be allowed to access SF.
5041 case CONNECT_DISPLAY_UNUSED:
5042 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5043 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5044 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005047
5048 // These codes are used for the IBinder protocol to either interrogate the recipient
5049 // side of the transaction for its canonical interface descriptor or to dump its state.
5050 // We let them pass by default.
5051 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5052 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5053 code == IBinder::SYSPROPS_TRANSACTION) {
5054 return OK;
5055 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005056 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005057 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham03b02dd2019-03-21 15:40:11 -07005058 if (code >= 1000 && code <= 1034) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5060 return OK;
5061 }
5062 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5063 return PERMISSION_DENIED;
5064#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005065}
5066
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5068 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005069 status_t credentialCheck = CheckTransactCodeCredentials(code);
5070 if (credentialCheck != OK) {
5071 return credentialCheck;
5072 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005074 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5075 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005076 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005077 IPCThreadState* ipc = IPCThreadState::self();
5078 const int uid = ipc->getCallingUid();
5079 if (CC_UNLIKELY(uid != AID_SYSTEM
5080 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005081 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005082 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005083 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 return PERMISSION_DENIED;
5085 }
5086 int n;
5087 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005088 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005089 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 return NO_ERROR;
5091 case 1002: // SHOW_UPDATES
5092 n = data.readInt32();
5093 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005094 invalidateHwcGeometry();
5095 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005098 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005101 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005102 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005103 setTransactionFlags(
5104 eTransactionNeeded|
5105 eDisplayTransactionNeeded|
5106 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005107 return NO_ERROR;
5108 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005109 case 1006:{ // send empty update
5110 signalRefresh();
5111 return NO_ERROR;
5112 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005113 case 1008: // toggle use of hw composer
5114 n = data.readInt32();
5115 mDebugDisableHWC = n ? 1 : 0;
5116 invalidateHwcGeometry();
5117 repaintEverything();
5118 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005119 case 1009: // toggle use of transform hint
5120 n = data.readInt32();
5121 mDebugDisableTransformHint = n ? 1 : 0;
5122 invalidateHwcGeometry();
5123 repaintEverything();
5124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005126 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005127 reply->writeInt32(0);
5128 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005129 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005130 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005131 return NO_ERROR;
5132 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005133 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005134 if (!display) {
5135 return NAME_NOT_FOUND;
5136 }
5137
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005138 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005139 return NO_ERROR;
5140 }
5141 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005142 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005143 // daltonize
5144 n = data.readInt32();
5145 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005146 case 1:
5147 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5148 break;
5149 case 2:
5150 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5151 break;
5152 case 3:
5153 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5154 break;
5155 default:
5156 mDaltonizer.setType(ColorBlindnessType::None);
5157 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005158 }
5159 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005160 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005161 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005162 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005163 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164
5165 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005166 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005167 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005168 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 // apply a color matrix
5171 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005173 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005174 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005175 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005176 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005177 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005179 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005181 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005182
5183 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5184 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005186 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5187 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5188 }
5189
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 return NO_ERROR;
5192 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005193 // This is an experimental interface
5194 // Needs to be shifted to proper binder interface when we productize
5195 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005196 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005197 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005198 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005199 return NO_ERROR;
5200 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005201 case 1017: {
5202 n = data.readInt32();
5203 mForceFullDamage = static_cast<bool>(n);
5204 return NO_ERROR;
5205 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005206 case 1018: { // Modify Choreographer's phase offset
5207 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005208 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005209 return NO_ERROR;
5210 }
5211 case 1019: { // Modify SurfaceFlinger's phase offset
5212 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005213 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005214 return NO_ERROR;
5215 }
Irvel468051e2016-06-13 16:44:44 -07005216 case 1020: { // Layer updates interceptor
5217 n = data.readInt32();
5218 if (n) {
5219 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005220 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005221 }
5222 else{
5223 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005224 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005225 }
5226 return NO_ERROR;
5227 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005228 case 1021: { // Disable HWC virtual displays
5229 n = data.readInt32();
5230 mUseHwcVirtualDisplays = !n;
5231 return NO_ERROR;
5232 }
Romain Guy0147a172017-06-01 13:53:56 -07005233 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005234 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005235 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005236
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005238 return NO_ERROR;
5239 }
Romain Guy54f154a2017-10-24 21:40:32 +01005240 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005241 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005242 invalidateHwcGeometry();
5243 repaintEverything();
5244 return NO_ERROR;
5245 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005246 // Deprecate, use 1030 to check whether the device is color managed.
5247 case 1024: {
5248 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005249 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005250 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005251 n = data.readInt32();
5252 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005253 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005254 Mutex::Autolock lock(mStateLock);
5255 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005256 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005257 reply->writeInt32(NO_ERROR);
5258 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005259 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005260 bool writeFile = false;
5261 {
5262 Mutex::Autolock lock(mStateLock);
5263 mTracingEnabledChanged = true;
5264 writeFile = mTracing.disable();
5265 }
5266
5267 if (writeFile) {
5268 reply->writeInt32(mTracing.writeToFile());
5269 } else {
5270 reply->writeInt32(NO_ERROR);
5271 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005272 }
5273 return NO_ERROR;
5274 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005275 case 1026: { // Get layer tracing status
5276 reply->writeBool(mTracing.isEnabled());
5277 return NO_ERROR;
5278 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005279 // Is a DisplayColorSetting supported?
5280 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005281 const auto display = getDefaultDisplayDevice();
5282 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005283 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005284 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005285
5286 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5287 switch (setting) {
5288 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005289 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 break;
5291 case DisplayColorSetting::UNMANAGED:
5292 reply->writeBool(true);
5293 break;
5294 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005295 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005296 break;
5297 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005298 reply->writeBool(
5299 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005300 break;
5301 }
5302 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005303 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005304 // Is VrFlinger active?
5305 case 1028: {
5306 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005307 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005308 return NO_ERROR;
5309 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005310 // Set buffer size for SF tracing (value in KB)
5311 case 1029: {
5312 n = data.readInt32();
5313 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5314 ALOGW("Invalid buffer size: %d KB", n);
5315 reply->writeInt32(BAD_VALUE);
5316 return BAD_VALUE;
5317 }
5318
5319 ALOGD("Updating trace buffer to %d KB", n);
5320 mTracing.setBufferSize(n * 1024);
5321 reply->writeInt32(NO_ERROR);
5322 return NO_ERROR;
5323 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005324 // Is device color managed?
5325 case 1030: {
5326 reply->writeBool(useColorManagement);
5327 return NO_ERROR;
5328 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005329 // Override default composition data space
5330 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5331 // && adb shell stop zygote && adb shell start zygote
5332 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5333 // adb shell stop zygote && adb shell start zygote
5334 case 1031: {
5335 Mutex::Autolock _l(mStateLock);
5336 n = data.readInt32();
5337 if (n) {
5338 n = data.readInt32();
5339 if (n) {
5340 Dataspace dataspace = static_cast<Dataspace>(n);
5341 if (!validateCompositionDataspace(dataspace)) {
5342 return BAD_VALUE;
5343 }
5344 mDefaultCompositionDataspace = dataspace;
5345 }
5346 n = data.readInt32();
5347 if (n) {
5348 Dataspace dataspace = static_cast<Dataspace>(n);
5349 if (!validateCompositionDataspace(dataspace)) {
5350 return BAD_VALUE;
5351 }
5352 mWideColorGamutCompositionDataspace = dataspace;
5353 }
5354 } else {
5355 // restore composition data space.
5356 mDefaultCompositionDataspace = defaultCompositionDataspace;
5357 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5358 }
5359 return NO_ERROR;
5360 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005361 case 1032: {
5362 n = data.readInt32();
5363 mDebugEnableProtectedContent = n;
5364 return NO_ERROR;
5365 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005366 // Set trace flags
5367 case 1033: {
5368 n = data.readUint32();
5369 ALOGD("Updating trace flags to 0x%x", n);
5370 mTracing.setTraceFlags(n);
5371 reply->writeInt32(NO_ERROR);
5372 return NO_ERROR;
5373 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005374 case 1034: {
5375 // TODO(b/129297325): expose this via developer menu option
5376 n = data.readInt32();
5377 if (n && !mRefreshRateOverlay) {
5378 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5379 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
5380 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
5381 } else if (!n) {
5382 mRefreshRateOverlay.reset();
5383 }
5384 return NO_ERROR;
5385 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005386 }
5387 }
5388 return err;
5389}
5390
Steven Thomas6d8110b2017-08-31 18:24:21 -07005391void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005392 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005393 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005394}
5395
Ana Krulec7d1d6832018-12-27 11:10:09 -08005396void SurfaceFlinger::repaintEverythingForHWC() {
5397 mRepaintEverything = true;
5398 mEventQueue->invalidateForHWC();
5399}
5400
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005401// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5402class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005403public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5405 ~WindowDisconnector() {
5406 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005407 }
5408
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409private:
5410 ANativeWindow* mWindow;
5411 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005412};
5413
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005414status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005415 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5416 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005417 uint32_t reqWidth, uint32_t reqHeight,
5418 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005419 ISurfaceComposer::Rotation rotation,
5420 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005421 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005422
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005423 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005424
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005425 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5426
Chia-I Wu20261cb2018-08-23 12:55:44 -07005427 sp<DisplayDevice> display;
5428 {
5429 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005430
Chia-I Wu20261cb2018-08-23 12:55:44 -07005431 display = getDisplayDeviceLocked(displayToken);
5432 if (!display) return BAD_VALUE;
5433
Chia-I Wucb023152018-08-28 12:57:23 -07005434 // set the requested width/height to the logical display viewport size
5435 // by default
5436 if (reqWidth == 0 || reqHeight == 0) {
5437 reqWidth = uint32_t(display->getViewport().width());
5438 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005439 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005440 }
5441
Peiyong Lin0e003c92018-09-17 11:09:51 -07005442 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005443 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005444
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005445 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5446 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005447 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5448 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005449}
5450
5451status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005452 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5453 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005454 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005455 ATRACE_CALL();
5456
5457 class LayerRenderArea : public RenderArea {
5458 public:
Robert Carr578038f2018-03-09 12:25:24 -08005459 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005460 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5461 bool childrenOnly)
5462 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005463 mLayer(layer),
5464 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005465 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005466 mFlinger(flinger),
5467 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005468 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005469 Rect getBounds() const override {
5470 const Layer::State& layerState(mLayer->getDrawingState());
5471 return mLayer->getBufferSize(layerState);
5472 }
Marissa Wall61c58622018-07-18 10:12:20 -07005473 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005474 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005475 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005476 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005477 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005478 }
chaviwa76b2712017-09-20 12:02:26 -07005479 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005480 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005481 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005482 Rect getSourceCrop() const override {
5483 if (mCrop.isEmpty()) {
5484 return getBounds();
5485 } else {
5486 return mCrop;
5487 }
5488 }
Robert Carr578038f2018-03-09 12:25:24 -08005489 class ReparentForDrawing {
5490 public:
5491 const sp<Layer>& oldParent;
5492 const sp<Layer>& newParent;
5493
Vishnu Nair4351ad52019-02-11 14:13:02 -08005494 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5495 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005496 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005497 // Compute and cache the bounds for the new parent layer.
5498 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005499 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005500 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005501 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005502 };
5503
5504 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005505 const Rect sourceCrop = getSourceCrop();
5506 // no need to check rotation because there is none
5507 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5508 sourceCrop.height() != getReqHeight();
5509
Robert Carr578038f2018-03-09 12:25:24 -08005510 if (!mChildrenOnly) {
5511 mTransform = mLayer->getTransform().inverse();
5512 drawLayers();
5513 } else {
5514 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005515 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005516 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005517 bounds.getWidth(), bounds.getHeight(), 0,
5518 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005519
Vishnu Nair4351ad52019-02-11 14:13:02 -08005520 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005521 drawLayers();
5522 }
5523 }
chaviwa76b2712017-09-20 12:02:26 -07005524
chaviwa76b2712017-09-20 12:02:26 -07005525 private:
chaviw7206d492017-11-10 16:16:12 -08005526 const sp<Layer> mLayer;
5527 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005528
5529 // In the "childrenOnly" case we reparent the children to a screenshot
5530 // layer which has no properties set and which does not draw.
5531 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005532 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005533 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005534
5535 SurfaceFlinger* mFlinger;
5536 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005537 };
5538
5539 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5540 auto parent = layerHandle->owner.promote();
5541
Robert Carr2e102c92018-10-23 12:11:15 -07005542 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005543 ALOGE("captureLayers called with a removed parent");
5544 return NAME_NOT_FOUND;
5545 }
5546
Robert Carr578038f2018-03-09 12:25:24 -08005547 const int uid = IPCThreadState::self()->getCallingUid();
5548 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005549 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005550 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5551 return PERMISSION_DENIED;
5552 }
5553
chaviw7206d492017-11-10 16:16:12 -08005554 Rect crop(sourceCrop);
5555 if (sourceCrop.width() <= 0) {
5556 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005557 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005558 }
5559
5560 if (sourceCrop.height() <= 0) {
5561 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005562 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005563 }
5564
5565 int32_t reqWidth = crop.width() * frameScale;
5566 int32_t reqHeight = crop.height() * frameScale;
5567
Chia-I Wu20261cb2018-08-23 12:55:44 -07005568 // really small crop or frameScale
5569 if (reqWidth <= 0) {
5570 reqWidth = 1;
5571 }
5572 if (reqHeight <= 0) {
5573 reqHeight = 1;
5574 }
5575
Peiyong Lin0e003c92018-09-17 11:09:51 -07005576 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005577
Robert Carr578038f2018-03-09 12:25:24 -08005578 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005579 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5580 if (!layer->isVisible()) {
5581 return;
Robert Carr578038f2018-03-09 12:25:24 -08005582 } else if (childrenOnly && layer == parent.get()) {
5583 return;
chaviwa76b2712017-09-20 12:02:26 -07005584 }
5585 visitor(layer);
5586 });
5587 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005588 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005589}
5590
5591status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5592 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005593 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005594 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005595 bool useIdentityTransform) {
5596 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005597
Peiyong Lin0e003c92018-09-17 11:09:51 -07005598 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005599 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5600 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005601 *outBuffer =
5602 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5603 static_cast<android_pixel_format>(reqPixelFormat), 1,
5604 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005606 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005607}
5608
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005609status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5610 TraverseLayersFunction traverseLayers,
5611 const sp<GraphicBuffer>& buffer,
5612 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613 // This mutex protects syncFd and captureResult for communication of the return values from the
5614 // main thread back to this Binder thread
5615 std::mutex captureMutex;
5616 std::condition_variable captureCondition;
5617 std::unique_lock<std::mutex> captureLock(captureMutex);
5618 int syncFd = -1;
5619 std::optional<status_t> captureResult;
5620
Robert Carr03480e22018-01-04 16:02:06 -08005621 const int uid = IPCThreadState::self()->getCallingUid();
5622 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5623
Dominik Laskowski8c001672018-05-30 16:52:06 -07005624 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005625 // If there is a refresh pending, bug out early and tell the binder thread to try again
5626 // after the refresh.
5627 if (mRefreshPending) {
5628 ATRACE_NAME("Skipping screenshot for now");
5629 std::unique_lock<std::mutex> captureLock(captureMutex);
5630 captureResult = std::make_optional<status_t>(EAGAIN);
5631 captureCondition.notify_one();
5632 return;
5633 }
5634
5635 status_t result = NO_ERROR;
5636 int fd = -1;
5637 {
5638 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005639 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005640 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005641 useIdentityTransform, forSystem, &fd);
5642 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643 }
5644
5645 {
5646 std::unique_lock<std::mutex> captureLock(captureMutex);
5647 syncFd = fd;
5648 captureResult = std::make_optional<status_t>(result);
5649 captureCondition.notify_one();
5650 }
5651 });
5652
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005653 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005654 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005655 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 while (*captureResult == EAGAIN) {
5657 captureResult.reset();
5658 result = postMessageAsync(message);
5659 if (result != NO_ERROR) {
5660 return result;
5661 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005662 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005663 }
5664 result = *captureResult;
5665 }
5666
5667 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005668 sync_wait(syncFd, -1);
5669 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005670 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005671
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005672 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005673}
5674
chaviwa76b2712017-09-20 12:02:26 -07005675void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005676 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005677 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5678 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005679 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005680
chaviwa76b2712017-09-20 12:02:26 -07005681 const auto reqWidth = renderArea.getReqWidth();
5682 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005683 const auto sourceCrop = renderArea.getSourceCrop();
5684 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005685
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005686 renderengine::DisplaySettings clientCompositionDisplay;
5687 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005688
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005689 // assume that bounds are never offset, and that they are the same as the
5690 // buffer bounds.
5691 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5692 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005693 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694 mat4 rotMatrix;
5695 // Displacement for repositioning the clipping rectangle after rotating it
5696 // with the rotation hint.
5697 int displacementX = 0;
5698 int displacementY = 0;
5699 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5700 switch (rotation) {
5701 case ui::Transform::ROT_90:
5702 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5703 displacementX = reqWidth;
5704 break;
5705 case ui::Transform::ROT_180:
5706 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5707 displacementX = reqWidth;
5708 displacementY = reqHeight;
5709 break;
5710 case ui::Transform::ROT_270:
5711 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5712 displacementY = reqHeight;
5713 break;
5714 default:
5715 break;
5716 }
5717 // We need to transform the clipping window into the right spot.
5718 // First, rotate the clipping rectangle by the rotation hint to get the
5719 // right orientation
5720 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5721 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5722 const vec4 rotClipTL = rotMatrix * clipTL;
5723 const vec4 rotClipBR = rotMatrix * clipBR;
5724 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5725 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5726 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5727 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5728
5729 // Now reposition the clipping rectangle with the displacement vector
5730 // computed above.
5731 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5732
5733 clientCompositionDisplay.clip =
5734 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5735 newClipRight + displacementX, newClipBottom + displacementY);
5736
5737 // We need to perform the same transformation in layer space, so propagate
5738 // it to the global transform.
5739 mat4 clipTransform = displacementMat * rotMatrix;
5740 clientCompositionDisplay.globalTransform *= clipTransform;
5741 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5742 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005743
chaviw50da5042018-04-09 13:49:37 -07005744 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005745
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005746 renderengine::LayerSettings fillLayer;
5747 fillLayer.source.buffer.buffer = nullptr;
5748 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5749 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5750 fillLayer.alpha = half(alpha);
5751 clientCompositionLayers.push_back(fillLayer);
5752
5753 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005754 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005755 renderengine::LayerSettings layerSettings;
5756 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005757 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005758 if (prepared) {
5759 clientCompositionLayers.push_back(layerSettings);
5760 }
chaviwa76b2712017-09-20 12:02:26 -07005761 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005762
5763 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005764 // Use an empty fence for the buffer fence, since we just created the buffer so
5765 // there is no need for synchronization with the GPU.
5766 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005768 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005769 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005770 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005771
5772 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005773}
5774
chaviwa76b2712017-09-20 12:02:26 -07005775status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5776 TraverseLayersFunction traverseLayers,
5777 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005778 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005779 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005780 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005781 ATRACE_CALL();
5782
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005783 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005784
5785 traverseLayers([&](Layer* layer) {
5786 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5787 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005788
Robert Carr03480e22018-01-04 16:02:06 -08005789 // We allow the system server to take screenshots of secure layers for
5790 // use in situations like the Screen-rotation animation and place
5791 // the impetus on WindowManager to not persist them.
5792 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005793 ALOGW("FB is protected: PERMISSION_DENIED");
5794 return PERMISSION_DENIED;
5795 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005796 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005797 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005798}
5799
chaviw95ef3c42019-02-14 10:55:09 -08005800void SurfaceFlinger::setInputWindowsFinished() {
5801 Mutex::Autolock _l(mStateLock);
5802
5803 mPendingSyncInputWindows = false;
5804 mTransactionCV.broadcast();
5805}
chaviw5f21a5e2019-02-14 10:00:34 -08005806
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005807// ---------------------------------------------------------------------------
5808
Dan Stoza412903f2017-04-27 13:42:17 -07005809void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5810 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005811}
5812
Dan Stoza412903f2017-04-27 13:42:17 -07005813void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5814 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005815}
5816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005817void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005818 const LayerVector::Visitor& visitor) {
5819 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005820 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005821 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005822 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005823 continue;
5824 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005825 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005826 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005827 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005828 return;
5829 }
chaviwa76b2712017-09-20 12:02:26 -07005830 if (!layer->isVisible()) {
5831 return;
5832 }
5833 visitor(layer);
5834 });
5835 }
5836}
5837
Ady Abraham838de062019-02-04 10:24:03 -08005838void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5839 const android::sp<android::IBinder>& displayToken,
5840 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5841 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5842 if (!displayId) {
5843 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5844 return;
5845 }
5846
5847 ALOGV("Updating allowed configs");
5848 {
5849 std::lock_guard lock(mAllowedConfigsLock);
5850 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5851 }
5852
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005853 // Set the highest allowed config by iterating backwards on available refresh rates
5854 const auto& refreshRates = mRefreshRateConfigs[*displayId]->getRefreshRates();
5855 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5856 if (iter->second && isConfigAllowed(*displayId, iter->second->configId)) {
5857 ALOGV("switching to config %d", iter->second->configId);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005858 setDesiredActiveConfig({iter->first, iter->second->configId, displayToken,
5859 Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005860 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005861 }
5862 }
Ady Abraham838de062019-02-04 10:24:03 -08005863}
5864
5865status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5866 const std::vector<int32_t>& allowedConfigs) {
5867 ATRACE_CALL();
5868
5869 if (!displayToken) {
5870 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5871 return BAD_VALUE;
5872 }
5873
5874 if (!allowedConfigs.size()) {
5875 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5876 return BAD_VALUE;
5877 }
5878
5879 {
5880 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5881 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5882 if (!displayId) {
5883 ALOGE("setAllowedDisplayConfigs: display not found");
5884 return NAME_NOT_FOUND;
5885 }
5886 }
5887
5888 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5889 for (int config : allowedConfigs) {
5890 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5891 allowedDisplayConfigsBuilder.addConfig(config);
5892 }
5893 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5894 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5895 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5896 }));
5897 return NO_ERROR;
5898}
5899
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005900status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5901 std::vector<int32_t>* outAllowedConfigs) {
5902 ATRACE_CALL();
5903
5904 if (!displayToken) {
5905 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5906 return BAD_VALUE;
5907 }
5908
5909 if (!outAllowedConfigs) {
5910 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5911 return BAD_VALUE;
5912 }
5913
5914 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5915 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5916 if (!displayId) {
5917 ALOGE("getAllowedDisplayConfigs: display not found");
5918 return NAME_NOT_FOUND;
5919 }
5920
5921 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5922 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5923 if (allowedConfigIterator != mAllowedConfigs.end()) {
5924 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5925 }
5926
5927 return NO_ERROR;
5928}
5929
chaviw291d88a2019-02-14 10:33:58 -08005930// ----------------------------------------------------------------------------
5931
5932void SetInputWindowsListener::onSetInputWindowsFinished() {
5933 mFlinger->setInputWindowsFinished();
5934}
5935
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005936}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005937
Lloyd Pique074e8122018-07-26 12:57:23 -07005938
Mathias Agopian3f844832013-08-07 21:24:32 -07005939#if defined(__gl_h_)
5940#error "don't include gl/gl.h in this file"
5941#endif
5942
5943#if defined(__gl2_h_)
5944#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005945#endif