blob: 1d840105efad48b24455b5ca74a7e1b8331f4cda [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070035#include <binder/IPCThreadState.h>
36#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Lloyd Pique70d91362018-10-18 16:02:55 -070039#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070040#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070041#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080044#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080048#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070051#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070052#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070053#include <ui/ColorSpace.h>
54#include <ui/DebugUtils.h>
55#include <ui/DisplayInfo.h>
56#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070057#include <ui/GraphicBufferAllocator.h>
58#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070059#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080060#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <utils/String16.h>
63#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070064#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080065#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067
Mathias Agopian921e6ac2012-07-23 23:11:29 -070068#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070069#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Robert Carr578038f2018-03-09 12:25:24 -080071#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070072#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070073#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020074#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080075#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020076#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080077#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080078#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070081#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080082#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070083#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070084#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087
Steven Thomasb02664d2017-07-26 18:48:28 -070088#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070089#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070090#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070091#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070092#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070094#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070095#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/EventControlThread.h"
97#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070098#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070099#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700100#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800101#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102
Mathias Agopianff2ed702013-09-01 21:36:12 -0700103#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700104
David Sodman7e4ae112018-02-09 15:02:28 -0800105#include "android-base/stringprintf.h"
106
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800108#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700109#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900111#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112
chaviw1d044282017-09-27 12:19:28 -0700113#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900114#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800116namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700117
Jaesoo Lee43518572017-01-23 19:03:16 +0900118using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800121using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700122using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700123using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700124using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700125using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126
Steven Thomasb02664d2017-07-26 18:48:28 -0700127namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700128
129#pragma clang diagnostic push
130#pragma clang diagnostic error "-Wswitch-enum"
131
132bool isWideColorMode(const ColorMode colorMode) {
133 switch (colorMode) {
134 case ColorMode::DISPLAY_P3:
135 case ColorMode::ADOBE_RGB:
136 case ColorMode::DCI_P3:
137 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700138 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700139 case ColorMode::BT2100_PQ:
140 case ColorMode::BT2100_HLG:
141 return true;
142 case ColorMode::NATIVE:
143 case ColorMode::STANDARD_BT601_625:
144 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
145 case ColorMode::STANDARD_BT601_525:
146 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
147 case ColorMode::STANDARD_BT709:
148 case ColorMode::SRGB:
149 return false;
150 }
151 return false;
152}
153
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700154ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
155 switch (rotation) {
156 case ISurfaceComposer::eRotateNone:
157 return ui::Transform::ROT_0;
158 case ISurfaceComposer::eRotate90:
159 return ui::Transform::ROT_90;
160 case ISurfaceComposer::eRotate180:
161 return ui::Transform::ROT_180;
162 case ISurfaceComposer::eRotate270:
163 return ui::Transform::ROT_270;
164 }
165 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
166 return ui::Transform::ROT_0;
167}
168
Peiyong Linfca547f2018-07-09 13:03:33 -0700169#pragma clang diagnostic pop
170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171class ConditionalLock {
172public:
173 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
174 if (lock) {
175 mMutex.lock();
176 }
177 }
178 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
179private:
180 Mutex& mMutex;
181 bool mLocked;
182};
Peiyong Linfca547f2018-07-09 13:03:33 -0700183
Peiyong Lin9d846a52018-11-05 13:18:20 -0800184// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
185bool validateCompositionDataspace(Dataspace dataspace) {
186 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
187}
188
Steven Thomasb02664d2017-07-26 18:48:28 -0700189} // namespace anonymous
190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191// ---------------------------------------------------------------------------
192
Mathias Agopian99b49842011-06-27 16:05:52 -0700193const String16 sHardwareTest("android.permission.HARDWARE_TEST");
194const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
195const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
196const String16 sDump("android.permission.DUMP");
197
198// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
200int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700201int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700202bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800203uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800205bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800206int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600207bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700208int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700209bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700210bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700211Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
212ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
213Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
214ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700215
Kalle Raitaa099a242017-01-11 11:17:29 -0800216std::string getHwcServiceName() {
217 char value[PROPERTY_VALUE_MAX] = {};
218 property_get("debug.sf.hwc_service_name", value, "default");
219 ALOGI("Using HWComposer service: '%s'", value);
220 return std::string(value);
221}
222
223bool useTrebleTestingOverride() {
224 char value[PROPERTY_VALUE_MAX] = {};
225 property_get("debug.sf.treble_testing_override", value, "false");
226 ALOGI("Treble testing override: '%s'", value);
227 return std::string(value) == "true";
228}
229
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
231 switch(displayColorSetting) {
232 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700233 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700235 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800236 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700237 return std::string("Enhanced");
238 default:
239 return std::string("Unknown ") +
240 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242}
243
David Sodmanbc815282017-11-05 18:57:52 -0800244SurfaceFlingerBE::SurfaceFlingerBE()
245 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800246 mFrameBuckets(),
247 mTotalTime(0),
248 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800249 mComposerSequenceId(0) {
250}
251
Lloyd Pique90c115d2018-09-18 21:39:42 -0700252SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
253 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800254 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700255 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700256 mTransactionPending(false),
257 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700258 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700259 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800262 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800263 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800264 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700266 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700267 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700268 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700269 mDebugInTransaction(0),
270 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700271 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800272 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700273 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700274 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800275 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800276 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700278 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700279 mMainThreadId(std::this_thread::get_id()),
280 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800281
Lloyd Pique90c115d2018-09-18 21:39:42 -0700282SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
283 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 vsyncPhaseOffsetNs = vsync_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 sfVsyncPhaseOffsetNs = vsync_sf_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 mDefaultCompositionDataspace =
308 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
309 mWideColorGamutCompositionDataspace =
310 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
311 defaultCompositionDataspace = mDefaultCompositionDataspace;
312 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
313 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
314 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
315 wideColorGamutCompositionPixelFormat =
316 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
321 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
322 switch (tmpPrimaryDisplayOrientation) {
323 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900326 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Lloyd Pique90c115d2018-09-18 21:39:42 -0700338 mPrimaryDispSync =
339 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
340 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 // debugging stuff...
343 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700346 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 property_get("debug.sf.showupdates", value, "0");
349 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351 property_get("debug.sf.ddms", value, "0");
352 mDebugDDMS = atoi(value);
353 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700354 if (!startDdmConnection()) {
355 // start failed, and DDMS debugging not enabled
356 mDebugDDMS = 0;
357 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700358 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700359 ALOGI_IF(mDebugRegion, "showupdates enabled");
360 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800370 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
377
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200378 property_get("debug.sf.early_phase_offset_ns", value, "-1");
379 const int earlySfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
382 const int earlyGlSfOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
385 const int earlyAppOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
388 const int earlyGlAppOffsetNs = atoi(value);
389
Ana Krulec98b5b242018-08-10 15:03:23 -0700390 property_get("debug.sf.use_scheduler", value, "0");
391 mUseScheduler = atoi(value);
392
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200393 const VSyncModulator::Offsets earlyOffsets =
394 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
396 const VSyncModulator::Offsets earlyGlOffsets =
397 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
398 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
399 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
400 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700401
Romain Guy11d63f42017-07-20 12:47:14 -0700402 // We should be reading 'persist.sys.sf.color_saturation' here
403 // but since /data may be encrypted, we need to wait until after vold
404 // comes online to attempt to read the property. The property is
405 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800406
407 if (useTrebleTestingOverride()) {
408 // Without the override SurfaceFlinger cannot connect to HIDL
409 // services that are not listed in the manifests. Considered
410 // deriving the setting from the set service name, but it
411 // would be brittle if the name that's not 'default' is used
412 // for production purposes later on.
413 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422SurfaceFlinger::~SurfaceFlinger()
423{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Dan Stozac7014012014-02-14 15:03:43 -0800426void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427{
428 // the window manager died on us. prepare its eulogy.
429
Andy McFadden13a082e2012-08-24 10:16:42 -0700430 // restore initial conditions (default device unblank, etc)
431 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432
433 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
Robert Carr1db73f62016-12-21 12:58:51 -0800437static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700438 status_t err = client->initCheck();
439 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return nullptr;
443}
444
445sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
446 return initClient(new Client(this));
447}
448
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700449sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
450 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451{
452 class DisplayToken : public BBinder {
453 sp<SurfaceFlinger> flinger;
454 virtual ~DisplayToken() {
455 // no more references, this display must be terminated
456 Mutex::Autolock _l(flinger->mStateLock);
457 flinger->mCurrentState.displays.removeItem(this);
458 flinger->setTransactionFlags(eDisplayTransactionNeeded);
459 }
460 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700461 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462 : flinger(flinger) {
463 }
464 };
465
466 sp<BBinder> token = new DisplayToken(this);
467
468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 // Display ID is assigned when virtual display is allocated by HWC.
470 DisplayDeviceState state;
471 state.isSecure = secure;
472 state.displayName = displayName;
473 mCurrentState.displays.add(token, state);
474 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 return token;
476}
477
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700478void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 Mutex::Autolock _l(mStateLock);
480
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
482 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 return;
485 }
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
488 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 ALOGE("destroyDisplay called for non-virtual display");
490 return;
491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 mInterceptor->saveDisplayDeletion(state.sequenceId);
493 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 setTransactionFlags(eDisplayTransactionNeeded);
495}
496
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 std::optional<DisplayId> displayId;
499
500 if (id == HWC_DISPLAY_PRIMARY) {
501 displayId = getInternalDisplayId();
502 } else if (id == HWC_DISPLAY_EXTERNAL) {
503 displayId = getExternalDisplayId();
504 }
505
506 if (!displayId) {
507 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800508 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510
511 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512}
513
Ady Abraham37965d42018-11-01 13:43:32 -0700514status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
515 if (!outGetColorManagement) {
516 return BAD_VALUE;
517 }
518 *outGetColorManagement = useColorManagement;
519 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700520}
521
Lloyd Pique441d5042018-10-18 16:49:51 -0700522HWComposer& SurfaceFlinger::getHwComposer() const {
523 return mCompositionEngine->getHwComposer();
524}
525
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700526renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
527 return mCompositionEngine->getRenderEngine();
528}
529
Lloyd Pique70d91362018-10-18 16:02:55 -0700530compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
531 return *mCompositionEngine.get();
532}
533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534void SurfaceFlinger::bootFinished()
535{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700536 if (mStartPropertySetThread->join() != NO_ERROR) {
537 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 const nsecs_t now = systemTime();
540 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000541 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700542
543 // wait patiently for the window manager death
544 const String16 name("window");
545 sp<IBinder> window(defaultServiceManager()->getService(name));
546 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700547 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548 }
Robert Carr720e5062018-07-30 17:45:14 -0700549 sp<IBinder> input(defaultServiceManager()->getService(
550 String16("inputflinger")));
551 if (input == nullptr) {
552 ALOGE("Failed to link to input service");
553 } else {
554 mInputFlinger = interface_cast<IInputFlinger>(input);
555 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
Steven Thomas050b2c82017-03-06 11:45:16 -0800557 if (mVrFlinger) {
558 mVrFlinger->OnBootFinished();
559 }
560
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700562 // formerly we would just kill the process, but we now ask it to exit so it
563 // can choose where to stop the animation.
564 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700565
566 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
567 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
568 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700569
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 postMessageAsync(new LambdaMessage([this] {
571 readPersistentProperties();
572 mBootStage = BootStage::FINISHED;
573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700598 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700599}
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Dominik Laskowski83b88212018-12-11 13:34:06 -0800611 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700614 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700615 mScheduler = getFactory().createScheduler([this](bool enabled) {
616 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
617 });
618
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700620 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800621 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700622 impl::EventThread::InterceptVSyncsCallback());
623 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700624 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800625 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mInterceptor->saveVSyncEvent(timestamp);
627 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800628
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700630 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
631 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 } else {
633 mEventThreadSource =
634 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
635 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
636 mEventThread =
637 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 [this](nsecs_t timestamp) {
647 mInterceptor->saveVSyncEvent(timestamp);
648 },
649 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800650 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
652 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653
Steven Thomasb02664d2017-07-26 18:48:28 -0700654 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700655 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700656 renderEngineFeature |= (useColorManagement ?
657 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700658 renderEngineFeature |= (useContextPriority ?
659 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700660
661 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700662 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700663 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700665
666 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
667 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700668 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
669 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800670 // Process any initial hotplug and resulting display changes.
671 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 const auto display = getDefaultDisplayDeviceLocked();
673 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700674 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800676
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700679 // This callback is called from the vr flinger dispatch thread. We
680 // need to call signalTransaction(), which requires holding
681 // mStateLock when we're not on the main thread. Acquiring
682 // mStateLock from the vr flinger dispatch thread might trigger a
683 // deadlock in surface flinger (see b/66916578), so post a message
684 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
687 mVrFlingerRequestsDisplay = requestDisplay;
688 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
692 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 .value_or(0),
695 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (!mVrFlinger) {
697 ALOGE("Failed to start vrflinger");
698 }
699 }
700
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700702 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700703
Mathias Agopian92a979a2012-08-02 18:32:23 -0700704 // initialize our drawing state
705 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700706
Andy McFadden13a082e2012-08-24 10:16:42 -0700707 // set initial conditions (e.g. unblank default device)
708 initializeDisplays();
709
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700710 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700713
714 const bool presentFenceReliable =
715 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
716 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717
718 if (mStartPropertySetThread->Start() != NO_ERROR) {
719 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Ana Krulec7d1d6832018-12-27 11:10:09 -0800722 if (mUseScheduler) {
723 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
724 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
725 }
726
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700728}
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 Mutex::Autolock _l(mStateLock);
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733 char value[PROPERTY_VALUE_MAX];
734
735 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800736 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100739
740 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700741 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700742}
743
Mathias Agopiana67e4182012-06-19 17:26:12 -0700744void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Start boot animation service by setting a property mailbox
746 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700747 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800748 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700749 if (mStartPropertySetThread->join() != NO_ERROR) {
750 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800751 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700755 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
Mathias Agopian875d8e12013-06-07 15:35:48 -0700758size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700759 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700760}
761
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800763
Jamie Gennis582270d2011-08-17 18:19:00 -0700764bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800766 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800767 return authenticateSurfaceTextureLocked(bufferProducer);
768}
769
770bool SurfaceFlinger::authenticateSurfaceTextureLocked(
771 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800772 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800773 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800774}
775
Brian Anderson6b376712017-04-04 10:51:39 -0700776status_t SurfaceFlinger::getSupportedFrameTimestamps(
777 std::vector<FrameEvent>* outSupported) const {
778 *outSupported = {
779 FrameEvent::REQUESTED_PRESENT,
780 FrameEvent::ACQUIRE,
781 FrameEvent::LATCH,
782 FrameEvent::FIRST_REFRESH_START,
783 FrameEvent::LAST_REFRESH_START,
784 FrameEvent::GPU_COMPOSITION_DONE,
785 FrameEvent::DEQUEUE_READY,
786 FrameEvent::RELEASE,
787 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700788 ConditionalLock _l(mStateLock,
789 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700790 if (!getHwComposer().hasCapability(
791 HWC2::Capability::PresentFenceIsNotReliable)) {
792 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
793 }
794 return NO_ERROR;
795}
796
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700797status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
798 Vector<DisplayInfo>* configs) {
799 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 return BAD_VALUE;
801 }
802
Dominik Laskowski075d3172018-05-24 15:50:06 -0700803 const auto displayId = getPhysicalDisplayId(displayToken);
804 if (!displayId) {
805 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700806 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 // TODO: Not sure if display density should handled by SF any longer
809 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700810 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700812 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800813 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700814 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 }
816 return density;
817 }
818 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700819 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 return getDensityFromProperty("ro.sf.lcd_density"); }
823 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700824
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Steven Thomas6d8110b2017-08-31 18:24:21 -0700827 ConditionalLock _l(mStateLock,
828 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700829 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 DisplayInfo info = DisplayInfo();
831
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 float xdpi = hwConfig->getDpiX();
833 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700835 info.w = hwConfig->getWidth();
836 info.h = hwConfig->getHeight();
837 // Default display viewport to display width and height
838 info.viewportW = info.w;
839 info.viewportH = info.h;
840
Dominik Laskowski075d3172018-05-24 15:50:06 -0700841 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700858 const auto display = getDefaultDisplayDeviceLocked();
859 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700860
861 // This is for screenrecord
862 const Rect viewport = display->getViewport();
863 if (viewport.isValid()) {
864 info.viewportW = uint32_t(viewport.getWidth());
865 info.viewportH = uint32_t(viewport.getHeight());
866 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 } else {
868 // TODO: where should this value come from?
869 static const int TV_DENSITY = 213;
870 info.density = TV_DENSITY / 160.0f;
871 info.orientation = 0;
872 }
873
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 info.xdpi = xdpi;
875 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900877 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878
Andy McFadden91b2ca82014-06-13 14:04:23 -0700879 // This is how far in advance a buffer must be queued for
880 // presentation at a given time. If you want a buffer to appear
881 // on the screen at time N, you must submit the buffer before
882 // (N - presentationDeadline).
883 //
884 // Normally it's one full refresh period (to give SF a chance to
885 // latch the buffer), but this can be reduced by configuring a
886 // DispSync offset. Any additional delays introduced by the hardware
887 // composer or panel must be accounted for here.
888 //
889 // We add an additional 1ms to allow for processing time and
890 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800892 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893
894 // All non-virtual displays are currently considered secure.
895 info.secure = true;
896
Dominik Laskowski075d3172018-05-24 15:50:06 -0700897 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700898 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800899 std::swap(info.w, info.h);
900 }
901
Michael Wright28f24d02016-07-12 13:30:53 -0700902 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700903 }
904
Dan Stoza7f7da322014-05-02 15:26:25 -0700905 return NO_ERROR;
906}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700907
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700908status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
909 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700910 return BAD_VALUE;
911 }
912
Ana Krulece588e312018-09-18 12:32:24 -0700913 if (mUseScheduler) {
914 mScheduler->getDisplayStatInfo(stats);
915 } else {
916 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
917 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
918 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Ana Krulec7d1d6832018-12-27 11:10:09 -0800932status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
933 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800934 postMessageAsync(new LambdaMessage(
935 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800936 return NO_ERROR;
937}
938
939status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
940 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800941 postMessageSync(new LambdaMessage(
942 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943 return NO_ERROR;
944}
945
946void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
947 Vector<DisplayInfo> configs;
948 getDisplayConfigs(displayToken, &configs);
949 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
950 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
951 return;
952 }
953
954 const auto display = getDisplayDevice(displayToken);
955 if (!display) {
956 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
957 displayToken.get());
958 return;
959 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700960 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 return;
963 }
964 int currentDisplayPowerMode = display->getPowerMode();
965 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
966 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700967 return;
968 }
969
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700970 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700971 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800972 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700973 return;
974 }
975
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 const auto displayId = display->getId();
977 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700980 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981
Ana Krulec7d1d6832018-12-27 11:10:09 -0800982 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800983 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -0700984}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
987 Vector<ColorMode>* outColorModes) {
988 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 return BAD_VALUE;
990 }
991
Dominik Laskowski075d3172018-05-24 15:50:06 -0700992 const auto displayId = getPhysicalDisplayId(displayToken);
993 if (!displayId) {
994 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700995 }
996
Peiyong Lina52f0292018-03-14 17:26:31 -0700997 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700998 {
999 ConditionalLock _l(mStateLock,
1000 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 }
Michael Wright28f24d02016-07-12 13:30:53 -07001003 outColorModes->clear();
1004 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1005
1006 return NO_ERROR;
1007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1010 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001011 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001012 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001014}
1015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001017 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018 Vector<ColorMode> modes;
1019 getDisplayColorModes(displayToken, &modes);
1020 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1021 if (mode < ColorMode::NATIVE || !exists) {
1022 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1023 decodeColorMode(mode).c_str(), mode, displayToken.get());
1024 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026 const auto display = getDisplayDevice(displayToken);
1027 if (!display) {
1028 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1029 decodeColorMode(mode).c_str(), mode, displayToken.get());
1030 } else if (display->isVirtual()) {
1031 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1032 decodeColorMode(mode).c_str(), mode);
1033 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001034 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1035 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 }
1037 }));
1038
Michael Wright28f24d02016-07-12 13:30:53 -07001039 return NO_ERROR;
1040}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001041
Svetoslavd85084b2014-03-20 10:28:31 -07001042status_t SurfaceFlinger::clearAnimationFrameStats() {
1043 Mutex::Autolock _l(mStateLock);
1044 mAnimFrameTracker.clearStats();
1045 return NO_ERROR;
1046}
1047
1048status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1049 Mutex::Autolock _l(mStateLock);
1050 mAnimFrameTracker.getStats(outStats);
1051 return NO_ERROR;
1052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1055 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001056 Mutex::Autolock _l(mStateLock);
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 const auto display = getDisplayDeviceLocked(displayToken);
1059 if (!display) {
1060 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001061 return BAD_VALUE;
1062 }
1063
Peiyong Linfb069302018-04-25 14:34:31 -07001064 // At this point the DisplayDeivce should already be set up,
1065 // meaning the luminance information is already queried from
1066 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001068 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1069 capabilities.getDesiredMaxLuminance(),
1070 capabilities.getDesiredMaxAverageLuminance(),
1071 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001072
1073 return NO_ERROR;
1074}
1075
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001076status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1077 ui::PixelFormat* outFormat,
1078 ui::Dataspace* outDataspace,
1079 uint8_t* outComponentMask) const {
1080 if (!outFormat || !outDataspace || !outComponentMask) {
1081 return BAD_VALUE;
1082 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001083 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001084 if (!display || !display->getId()) {
1085 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1086 return BAD_VALUE;
1087 }
1088 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1089 outDataspace, outComponentMask);
1090}
1091
Kevin DuBois74e53772018-11-19 10:52:38 -08001092status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1093 bool enable, uint8_t componentMask,
1094 uint64_t maxFrames) const {
1095 const auto display = getDisplayDevice(displayToken);
1096 if (!display || !display->getId()) {
1097 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1098 return BAD_VALUE;
1099 }
1100
1101 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1102 componentMask, maxFrames);
1103}
1104
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001105status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1106 uint64_t maxFrames, uint64_t timestamp,
1107 DisplayedFrameStats* outStats) const {
1108 const auto display = getDisplayDevice(displayToken);
1109 if (!display || !display->getId()) {
1110 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1111 return BAD_VALUE;
1112 }
1113
1114 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1115 outStats);
1116}
1117
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001118status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1119 if (!outSupported) {
1120 return BAD_VALUE;
1121 }
1122 *outSupported = getRenderEngine().supportsProtectedContent();
1123 return NO_ERROR;
1124}
1125
Marissa Wallebc2c052019-01-16 19:16:55 -08001126status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1127 int32_t* outBufferId) {
1128 if (!outBufferId) {
1129 return BAD_VALUE;
1130 }
1131 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1132 return NO_ERROR;
1133}
1134
1135status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1136 mBufferStateLayerCache.release(token, bufferId);
1137 return NO_ERROR;
1138}
1139
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001140status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001141 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001142 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 if (mInjectVSyncs == enable) {
1145 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147
Dominik Laskowski83b88212018-12-11 13:34:06 -08001148 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001149
Ana Krulec98b5b242018-08-10 15:03:23 -07001150 // TODO(akrulec): Part of the Injector should be refactored, so that it
1151 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001156 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001157 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001158 impl::EventThread::InterceptVSyncsCallback(),
1159 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001161 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 } else {
1163 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001164 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 }
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001168 }));
1169
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001170 return NO_ERROR;
1171}
1172
1173status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
1175
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 if (!mInjectVSyncs) {
1177 ALOGE("VSync Injections not enabled");
1178 return BAD_VALUE;
1179 }
1180 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1181 ALOGV("Injecting VSync inside SurfaceFlinger");
1182 mVSyncInjector->onInjectSyncEvent(when);
1183 }
1184 return NO_ERROR;
1185}
1186
Lloyd Pique755e3192018-01-31 16:46:15 -08001187status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1188 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001189 // Try to acquire a lock for 1s, fail gracefully
1190 const status_t err = mStateLock.timedLock(s2ns(1));
1191 const bool locked = (err == NO_ERROR);
1192 if (!locked) {
1193 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1194 return TIMED_OUT;
1195 }
1196
1197 outLayers->clear();
1198 mCurrentState.traverseInZOrder([&](Layer* layer) {
1199 outLayers->push_back(layer->getLayerDebugInfo());
1200 });
1201
1202 mStateLock.unlock();
1203 return NO_ERROR;
1204}
1205
Peiyong Linc6780972018-10-28 15:24:08 -07001206status_t SurfaceFlinger::getCompositionPreference(
1207 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1208 Dataspace* outWideColorGamutDataspace,
1209 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001210 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001211 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001212 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001213 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001214 return NO_ERROR;
1215}
1216
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001217// ----------------------------------------------------------------------------
1218
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001219sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1220 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001221 auto resyncCallback = makeResyncCallback([this] {
1222 Mutex::Autolock lock(mStateLock);
1223 return getVsyncPeriod();
1224 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001225
Ana Krulec98b5b242018-08-10 15:03:23 -07001226 if (mUseScheduler) {
1227 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001228 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001229 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001230 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001231 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001232 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001233 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001234 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001235 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001236 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001237 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001238 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001239}
1240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242
1243void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001244 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245}
1246
1247void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001248 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001252 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253}
1254
1255void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001256 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001261 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001266 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268 if (res == NO_ERROR) {
1269 msg->wait();
1270 }
1271 return res;
1272}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001273
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001274void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001275 do {
1276 waitForEvent();
1277 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001278}
1279
Dominik Laskowski83b88212018-12-11 13:34:06 -08001280nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1281 const auto displayId = getInternalDisplayId();
1282 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1283 return 0;
1284 }
1285
1286 const auto config = getHwComposer().getActiveConfig(*displayId);
1287 return config ? config->getVsyncPeriod() : 0;
1288}
1289
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290void SurfaceFlinger::enableHardwareVsync() {
1291 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001292 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001293 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001296 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297}
1298
Dominik Laskowski83b88212018-12-11 13:34:06 -08001299void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 Mutex::Autolock _l(mHWVsyncLock);
1301
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302 if (makeAvailable) {
1303 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001304 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1305 if (mUseScheduler) {
1306 mScheduler->makeHWSyncAvailable(true);
1307 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 // Hardware vsync is not currently available, so abort the resync
1310 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 return;
1312 }
1313
Dominik Laskowski83b88212018-12-11 13:34:06 -08001314 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001315 return;
1316 }
1317
Ana Krulece588e312018-09-18 12:32:24 -07001318 if (mUseScheduler) {
1319 mScheduler->setVsyncPeriod(period);
1320 } else {
1321 mPrimaryDispSync->reset();
1322 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001323
Ana Krulece588e312018-09-18 12:32:24 -07001324 if (!mPrimaryHWVsyncEnabled) {
1325 mPrimaryDispSync->beginResync();
1326 mEventControlThread->setVsyncEnabled(true);
1327 mPrimaryHWVsyncEnabled = true;
1328 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 }
1330}
1331
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 Mutex::Autolock _l(mHWVsyncLock);
1334 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001336 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337 mPrimaryHWVsyncEnabled = false;
1338 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeUnavailable) {
1340 mHWVsyncAvailable = false;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Dominik Laskowski83b88212018-12-11 13:34:06 -08001344void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001345 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001346
Dan Stoza57164302017-05-08 14:03:54 -07001347 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001348 const nsecs_t last = lastResyncTime.exchange(now);
1349
1350 if (now - last > kIgnoreDelay) {
1351 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001352 }
1353}
1354
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001355void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1356 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001357 ATRACE_NAME("SF onVsync");
1358
Steven Thomas3cfac282017-02-06 12:29:30 -08001359 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
1363 }
1364
Dominik Laskowski075d3172018-05-24 15:50:06 -07001365 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 return;
1367 }
1368
Dominik Laskowski075d3172018-05-24 15:50:06 -07001369 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001370 // For now, we don't do anything with external display vsyncs.
1371 return;
1372 }
1373
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (mUseScheduler) {
1375 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001376 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001377 bool needsHwVsync = false;
1378 { // Scope for the lock
1379 Mutex::Autolock _l(mHWVsyncLock);
1380 if (mPrimaryHWVsyncEnabled) {
1381 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1382 }
1383 }
1384
1385 if (needsHwVsync) {
1386 enableHardwareVsync();
1387 } else {
1388 disableHardwareVsync(false);
1389 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001390 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001391}
1392
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001393void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001394 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1395 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396}
1397
Ana Krulec7d1d6832018-12-27 11:10:09 -08001398void SurfaceFlinger::setRefreshRateTo(float newFps) {
1399 const auto displayId = getInternalDisplayId();
1400 if (!displayId || mBootStage != BootStage::FINISHED) {
1401 return;
1402 }
1403 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1404 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1405 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1406 // refresh cycle.
1407
1408 // Don't do any updating if the current fps is the same as the new one.
1409 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1410 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1411 if (currentVsyncPeriod == 0) {
1412 return;
1413 }
1414 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1415 // floating numbers.
1416 const float currentFps = 1e9 / currentVsyncPeriod;
1417 if (std::abs(currentFps - newFps) <= 1) {
1418 return;
1419 }
1420
1421 auto configs = getHwComposer().getConfigs(*displayId);
1422 for (int i = 0; i < configs.size(); i++) {
1423 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1424 if (vsyncPeriod == 0) {
1425 continue;
1426 }
1427 const float fps = 1e9 / vsyncPeriod;
1428 // TODO(b/113612090): There should be a better way at determining which config
1429 // has the right refresh rate.
1430 if (std::abs(fps - newFps) <= 1) {
1431 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1432 if (!display) return;
1433 // This is posted in async function to avoid deadlock when getDisplayDevice
1434 // requires mStateLock.
1435 setActiveConfigAsync(display, i);
1436 ATRACE_INT("FPS", newFps);
1437 }
1438 }
1439}
1440
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001441void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001442 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001443 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001444 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445
Lloyd Piqueba04e622017-12-14 17:11:26 -08001446 // Ignore events that do not have the right sequenceId.
1447 if (sequenceId != getBE().mComposerSequenceId) {
1448 return;
1449 }
1450
Steven Thomasb02664d2017-07-26 18:48:28 -07001451 // Only lock if we're not on the main thread. This function is normally
1452 // called on a hwbinder thread, but for the primary display it's called on
1453 // the main thread with the state lock already held, so don't attempt to
1454 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001455 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001456
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001457 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001458
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001459 if (std::this_thread::get_id() == mMainThreadId) {
1460 // Process all pending hot plug events immediately if we are on the main thread.
1461 processDisplayHotplugEventsLocked();
1462 }
1463
Lloyd Piqueba04e622017-12-14 17:11:26 -08001464 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001465}
1466
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001467void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001468 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001469 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001471 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001472 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001473}
1474
Dominik Laskowski075d3172018-05-24 15:50:06 -07001475void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001476 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478 if (const auto displayId = getInternalDisplayId()) {
1479 getHwComposer().setVsyncEnabled(*displayId,
1480 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1481 }
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001485void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001486 if (mUseScheduler) {
1487 mScheduler->disableHardwareVsync(true);
1488 } else {
1489 disableHardwareVsync(true);
1490 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491 // Clear the drawing state so that the logic inside of
1492 // handleTransactionLocked will fire. It will determine the delta between
1493 // mCurrentState and mDrawingState and re-apply all changes when we make the
1494 // transition.
1495 mDrawingState.displays.clear();
1496 mDisplays.clear();
1497}
1498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499void SurfaceFlinger::updateVrFlinger() {
1500 if (!mVrFlinger)
1501 return;
1502 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001503 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001504 return;
1505 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001506
Lloyd Pique441d5042018-10-18 16:49:51 -07001507 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 ALOGE("Vr flinger is only supported for remote hardware composer"
1509 " service connections. Ignoring request to transition to vr"
1510 " flinger.");
1511 mVrFlingerRequestsDisplay = false;
1512 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001513 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001514
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001515 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001516
Steven Thomas0123ac62018-07-12 11:32:34 -07001517 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001518 LOG_ALWAYS_FATAL_IF(!display);
1519 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001520 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1521 // called below. Clear the reference now so we don't accidentally use it
1522 // later.
1523 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001526 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001527 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001530 // Delete the current instance before creating the new one
1531 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1532 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1533 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1534 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001535
Lloyd Pique441d5042018-10-18 16:49:51 -07001536 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001537 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001538
1539 if (vrFlingerRequestsDisplay) {
1540 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001541 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
1543 mVisibleRegionsDirty = true;
1544 invalidateHwcGeometry();
1545
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001546 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001547 display = getDefaultDisplayDeviceLocked();
1548 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001549 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001550
Steven Thomasb02664d2017-07-26 18:48:28 -07001551 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001552 const nsecs_t vsyncPeriod = getVsyncPeriod();
1553 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001554
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001555 // The present fences returned from vr_hwc are not an accurate
1556 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001557 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001558 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1559 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001560 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001562 !hasSyncFramework);
1563 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 // Use phase of 0 since phase is not known.
1566 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001567 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001568 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001569
Dominik Laskowski83b88212018-12-11 13:34:06 -08001570 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001571
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001572 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001573 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001574}
1575
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001577 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001578 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001579 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001580 if (mUseScheduler) {
1581 // This call is made each time SF wakes up and creates a new frame.
1582 mScheduler->incrementFrameCounter();
1583 }
Dan Stoza50182882016-07-08 12:02:20 -07001584 bool frameMissed = !mHadClientComposition &&
1585 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001586 (mPreviousPresentFence->getSignalTime() ==
1587 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001588 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001589 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001590 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001591 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001592 if (mPropagateBackpressure) {
1593 signalLayerUpdate();
1594 break;
1595 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001596 }
Dan Stoza50182882016-07-08 12:02:20 -07001597
Steven Thomas050b2c82017-03-06 11:45:16 -08001598 // Now that we're going to make it to the handleMessageTransaction()
1599 // call below it's safe to call updateVrFlinger(), which will
1600 // potentially trigger a display handoff.
1601 updateVrFlinger();
1602
Dan Stoza6b9454d2014-11-07 16:00:59 -08001603 bool refreshNeeded = handleMessageTransaction();
1604 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001605 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001606 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001607 // Signal a refresh if a transaction modified the window state,
1608 // a new buffer was latched, or if HWC has requested a full
1609 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001610 signalRefresh();
1611 }
1612 break;
1613 }
1614 case MessageQueue::REFRESH: {
1615 handleMessageRefresh();
1616 break;
1617 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001618 }
1619}
1620
Dan Stoza6b9454d2014-11-07 16:00:59 -08001621bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001622 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001623
1624 // Apply any ready transactions in the queues if there are still transactions that have not been
1625 // applied, wake up during the next vsync period and check again
1626 bool transactionNeeded = false;
1627 if (!flushTransactionQueues()) {
1628 transactionNeeded = true;
1629 }
1630
Mathias Agopian4fec8732012-06-29 14:12:52 -07001631 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001632 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001633 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001634
1635 if (transactionNeeded) {
1636 setTransactionFlags(eTransactionNeeded);
1637 }
1638
1639 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001640}
1641
Mathias Agopian4fec8732012-06-29 14:12:52 -07001642void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001645 mRefreshPending = false;
1646
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001647 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001648 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001649 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001650 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001651 for (const auto& [token, display] : mDisplays) {
1652 beginFrame(display);
1653 prepareFrame(display);
1654 doDebugFlashRegions(display, repaintEverything);
1655 doComposition(display, repaintEverything);
1656 }
1657
Adrian Roos1e1a1282017-11-01 19:05:31 +01001658 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001659 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001660
1661 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001662 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001663
Dan Stozabfbffeb2016-07-21 14:49:33 -07001664 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001665 for (const auto& [token, displayDevice] : mDisplays) {
1666 auto display = displayDevice->getCompositionDisplay();
1667 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001668 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001669 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001670 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671
Alec Mouri86770e52018-09-24 22:40:58 +00001672 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001673 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001674 if (mHadClientComposition) {
1675 base::unique_fd flushFence(getRenderEngine().flush());
1676 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1677 getBE().flushFence = new Fence(std::move(flushFence));
1678 } else {
1679 // Cleanup for hygiene.
1680 getBE().flushFence = Fence::NO_FENCE;
1681 }
1682 }
1683
Jorim Jaggi90535212018-05-23 23:44:06 +02001684 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001685
David Sodman7e4ae112018-02-09 15:02:28 -08001686 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001687 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001688 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001689 compositionInfo.hwc.hwcLayer = nullptr;
1690 }
David Sodmanba340492018-08-05 21:51:33 -07001691 }
David Sodman7e4ae112018-02-09 15:02:28 -08001692
1693 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696
1697bool SurfaceFlinger::handleMessageInvalidate() {
1698 ATRACE_CALL();
1699 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700}
1701
David Sodman79bba0e2018-08-05 18:07:49 -07001702void SurfaceFlinger::calculateWorkingSet() {
1703 ATRACE_CALL();
1704 ALOGV(__FUNCTION__);
1705
David Sodman79bba0e2018-08-05 18:07:49 -07001706 // build the h/w work list
1707 if (CC_UNLIKELY(mGeometryInvalid)) {
1708 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001709 for (const auto& [token, displayDevice] : mDisplays) {
1710 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001711 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001712 if (!displayId) {
1713 continue;
1714 }
David Sodman79bba0e2018-08-05 18:07:49 -07001715
Lloyd Pique32cbe282018-10-19 13:09:22 -07001716 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001717 for (size_t i = 0; i < currentLayers.size(); i++) {
1718 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001719
Dominik Laskowski075d3172018-05-24 15:50:06 -07001720 if (!layer->hasHwcLayer(*displayId)) {
1721 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1722 layer->forceClientComposition(*displayId);
1723 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001724 }
1725 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001726
Lloyd Pique32cbe282018-10-19 13:09:22 -07001727 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 if (mDebugDisableHWC || mDebugRegion) {
1729 layer->forceClientComposition(*displayId);
1730 }
David Sodman79bba0e2018-08-05 18:07:49 -07001731 }
1732 }
1733 }
1734
1735 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001736 for (const auto& [token, displayDevice] : mDisplays) {
1737 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001738 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001740 continue;
1741 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001742 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001743
1744 if (mDrawingState.colorMatrixChanged) {
1745 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001746 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001747 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001748 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001750 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1751 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001752 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001753 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001754 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1755 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001756 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
1759
Peiyong Lind3788632018-09-18 16:01:31 -07001760 // TODO(b/111562338) remove when composer 2.3 is shipped.
1761 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001762 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001763 }
1764
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001765 if (layer->getRoundedCornerState().radius > 0.0f) {
1766 layer->forceClientComposition(*displayId);
1767 }
1768
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001770 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001772 continue;
1773 }
1774
Lloyd Pique32cbe282018-10-19 13:09:22 -07001775 const auto& displayState = display->getState();
1776 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1777 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001778 }
1779
Peiyong Lin13effd12018-07-24 17:01:47 -07001780 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001781 ColorMode colorMode;
1782 Dataspace dataSpace;
1783 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001784 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001785 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 }
1787 }
1788
1789 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001790
1791 for (const auto& [token, display] : mDisplays) {
1792 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001793 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001794 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001795
1796 if (displayId) {
1797 if (!layer->setHwcLayer(*displayId)) {
1798 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1799 }
1800 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001801 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001802
Dominik Laskowski05275f12018-11-01 15:03:24 -07001803 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001804 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1805 }
1806 }
David Sodman79bba0e2018-08-05 18:07:49 -07001807}
1808
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1810 bool repaintEverything) {
1811 auto display = displayDevice->getCompositionDisplay();
1812 const auto& displayState = display->getState();
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 // is debugging enabled
1815 if (CC_LIKELY(!mDebugRegion))
1816 return;
1817
Lloyd Pique32cbe282018-10-19 13:09:22 -07001818 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001819 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001821 if (!dirtyRegion.isEmpty()) {
1822 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001823 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824
David Sodmanfa9b2af2017-12-24 13:28:59 -08001825 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001826 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001827 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001828
Lloyd Pique31cb2942018-10-19 17:23:03 -07001829 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830 }
1831 }
1832
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834
1835 if (mDebugRegion > 1) {
1836 usleep(mDebugRegion * 1000);
1837 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001838
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840}
1841
Adrian Roos1e1a1282017-11-01 19:05:31 +01001842void SurfaceFlinger::doTracing(const char* where) {
1843 ATRACE_CALL();
1844 ATRACE_NAME(where);
1845 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001846 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001847 }
1848}
1849
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001850void SurfaceFlinger::logLayerStats() {
1851 ATRACE_CALL();
1852 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001853 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001854 if (display->isPrimary()) {
1855 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001856 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001857 }
1858 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001859
1860 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001861 }
1862}
1863
David Sodman2b406362017-12-15 13:33:47 -08001864void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 ATRACE_CALL();
1867 ALOGV("preComposition");
1868
David Sodman2b406362017-12-15 13:33:47 -08001869 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1870
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001872 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001873 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874 needExtraInvalidate = true;
1875 }
Robert Carr2047fae2016-11-28 14:09:09 -08001876 });
1877
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 if (needExtraInvalidate) {
1879 signalLayerUpdate();
1880 }
1881}
1882
Ana Krulece588e312018-09-18 12:32:24 -07001883void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1884 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001885 // Update queue of past composite+present times and determine the
1886 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001887 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001888 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001889 while (!getBE().mCompositePresentTimes.empty()) {
1890 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001891 // Cached values should have been updated before calling this method,
1892 // which helps avoid duplicate syscalls.
1893 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1894 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1895 break;
1896 }
1897 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001898 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 }
1900
1901 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001902 while (getBE().mCompositePresentTimes.size() > 16) {
1903 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 }
1905
Ana Krulece588e312018-09-18 12:32:24 -07001906 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001907}
1908
Ana Krulece588e312018-09-18 12:32:24 -07001909void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1910 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Integer division and modulo round toward 0 not -inf, so we need to
1912 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001913 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1914 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1915 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916
Brian Andersond0010582017-03-07 13:20:31 -08001917 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1918 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001919 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001920 }
1921
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922 // Snap the latency to a value that removes scheduling jitter from the
1923 // composition and present times, which often have >1ms of jitter.
1924 // Reducing jitter is important if an app attempts to extrapolate
1925 // something (such as user input) to an accurate diasplay time.
1926 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1927 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001928 nsecs_t bias = stats.vsyncPeriod / 2;
1929 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1930 nsecs_t snappedCompositeToPresentLatency =
1931 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932
David Sodman99974d22017-11-28 12:04:33 -08001933 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001934 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1935 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001936 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937}
1938
Ady Abraham8164d482019-01-11 14:47:59 -08001939// debug patch for b/119477596 - add stack guards to catch stack
1940// corruptions and disable clang optimizations.
1941// The code below is temporary and planned to be removed once stack
1942// corruptions are found.
1943#pragma clang optimize off
1944class StackGuard {
1945public:
1946 StackGuard(const char* name, const char* func, int line) {
1947 guarders.reserve(MIN_CAPACITY);
1948 guarders.push_back({this, name, func, line});
1949 validate();
1950 }
1951 ~StackGuard() {
1952 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1953 if (i->guard == this) {
1954 guarders.erase(i);
1955 break;
1956 }
1957 }
1958 }
1959
1960 static void validate() {
1961 for (const auto& guard : guarders) {
1962 if (guard.guard->cookie != COOKIE_VALUE) {
1963 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1964 CallStack stack(LOG_TAG);
1965 abort();
1966 }
1967 }
1968 }
1969
1970private:
1971 uint64_t cookie = COOKIE_VALUE;
1972 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1973 static constexpr size_t MIN_CAPACITY = 16;
1974
1975 struct GuarderElement {
1976 StackGuard* guard;
1977 const char* name;
1978 const char* func;
1979 int line;
1980 };
1981
1982 static std::vector<GuarderElement> guarders;
1983};
1984std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1985
1986#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1987
1988#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001989void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990{
Ady Abraham8164d482019-01-11 14:47:59 -08001991 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ATRACE_CALL();
1993 ALOGV("postComposition");
1994
Brian Anderson3546a3f2016-07-14 11:51:14 -07001995 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001996 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001997 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001998 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001999 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002000 }
Ady Abraham8164d482019-01-11 14:47:59 -08002001 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002002
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002003 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002004 const auto displayDevice = getDefaultDisplayDeviceLocked();
2005 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002006
David Sodman73beded2017-11-15 11:56:06 -08002007 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002009 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2010
Lloyd Pique32cbe282018-10-19 13:09:22 -07002011 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002013 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2014 ->getRenderSurface()
2015 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002016 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 } else {
2018 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2019 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020
Ady Abraham8164d482019-01-11 14:47:59 -08002021 ASSERT_ON_STACK_GUARD();
2022
David Sodman73beded2017-11-15 11:56:06 -08002023 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2025 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002026 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002027 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029
Ana Krulece588e312018-09-18 12:32:24 -07002030 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002031 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002032 if (mUseScheduler) {
2033 mScheduler->getDisplayStatInfo(&stats);
2034 } else {
2035 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2036 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2037 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038
Ady Abraham8164d482019-01-11 14:47:59 -08002039 ASSERT_ON_STACK_GUARD();
2040
David Sodman2b406362017-12-15 13:33:47 -08002041 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 // when we started doing work for this frame, but that should be okay
2043 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002044 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002045 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(compositorTiming);
2047
Brian Andersond0010582017-03-07 13:20:31 -08002048 {
David Sodman99974d22017-11-28 12:04:33 -08002049 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002051 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002052
2053 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002054 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Robert Carr2047fae2016-11-28 14:09:09 -08002056 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002057 bool frameLatched =
2058 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2059 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002060 DEFINE_STACK_GUARD(frameLatched);
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 }
Ady Abraham8164d482019-01-11 14:47:59 -08002065 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002066 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002067
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002068 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002069 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002070 if (mUseScheduler) {
2071 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002073 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002074 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2075 enableHardwareVsync();
2076 } else {
2077 disableHardwareVsync(false);
2078 }
Ady Abraham8164d482019-01-11 14:47:59 -08002079 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002080 }
2081 }
2082
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002083 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2085 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002086 if (mUseScheduler) {
2087 mScheduler->enableHardwareVsync();
2088 } else {
2089 enableHardwareVsync();
2090 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002091 }
2092 }
2093
Ady Abraham8164d482019-01-11 14:47:59 -08002094 ASSERT_ON_STACK_GUARD();
2095
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002096 if (mAnimCompositionPending) {
2097 mAnimCompositionPending = false;
2098
Brian Anderson4e606e32017-03-16 15:34:57 -07002099 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002100 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002101 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002102
2103 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002105 // The HWC doesn't support present fences, so use the refresh
2106 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002107 const nsecs_t presentTime =
2108 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(presentTime);
2110
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002112 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 }
2114 mAnimFrameTracker.advanceFrame();
2115 }
Dan Stozab90cf072015-03-05 11:05:59 -08002116
Ady Abraham8164d482019-01-11 14:47:59 -08002117 ASSERT_ON_STACK_GUARD();
2118
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002119 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002120 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002121 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002122 }
2123
Ady Abraham8164d482019-01-11 14:47:59 -08002124 ASSERT_ON_STACK_GUARD();
2125
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002126 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002127
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
2129
Lloyd Pique32cbe282018-10-19 13:09:22 -07002130 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2131 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002132 return;
2133 }
2134
2135 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002137 if (mHasPoweredOff) {
2138 mHasPoweredOff = false;
2139 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002140 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002141 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002142 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002143 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002144 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2145 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002146 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002147 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002148 }
David Sodman4a36e932017-11-07 14:29:47 -08002149 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002150
2151 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002152 }
David Sodman4a36e932017-11-07 14:29:47 -08002153 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002154 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002155
2156 {
2157 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002159 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002161 if (refillCount > 0) {
2162 const size_t offset = mTexturePool.size();
2163 mTexturePool.resize(mTexturePoolSize);
2164 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2165 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2166 }
Ady Abraham8164d482019-01-11 14:47:59 -08002167 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002168 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002169
Marissa Wallfda30bb2018-10-12 11:34:28 -07002170 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002171 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002172
2173 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002174}
Ady Abraham8164d482019-01-11 14:47:59 -08002175#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002176
2177void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002178 ATRACE_CALL();
2179 ALOGV("rebuildLayerStacks");
2180
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002181 // We need to clear these out now as these may be holding on to a
2182 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2183 // also holds a reference. When the set of visible layers is recomputed,
2184 // some layers may be destroyed if the only thing keeping them alive was
2185 // that list of visible layers associated with each display. The layer
2186 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2187 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2188 for (const auto& [token, display] : mDisplays) {
2189 getBE().mCompositionInfo[token].clear();
2190 }
2191
Mathias Agopiancd60f992012-08-16 16:28:27 -07002192 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002193 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002194 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002195 mVisibleRegionsDirty = false;
2196 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002197
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002198 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002199 const auto& displayDevice = pair.second;
2200 auto display = displayDevice->getCompositionDisplay();
2201 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002202 Region opaqueRegion;
2203 Region dirtyRegion;
2204 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002205 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 const ui::Transform& tr = displayState.transform;
2207 const Rect bounds = displayState.bounds;
2208 if (displayState.isEnabled) {
2209 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002212 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002213 const auto displayId = displayDevice->getId();
2214 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 Region drawRegion(tr.transform(
2216 layer->visibleNonTransparentRegion));
2217 drawRegion.andSelf(bounds);
2218 if (!drawRegion.isEmpty()) {
2219 layersSortedByZ.add(layer);
2220 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002221 // Clear out the HWC layer if this layer was
2222 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002223 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002225 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002226 // WM changes display->layerStack upon sleep/awake.
2227 // Here we make sure we delete the HWC layers even if
2228 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002229 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002230 }
2231
2232 // If a layer is not going to get a release fence because
2233 // it is invisible, but it is also going to release its
2234 // old buffer, add it to the list of layers needing
2235 // fences.
2236 if (hwcLayerDestroyed) {
2237 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2238 mLayersWithQueuedFrames.cend(), layer);
2239 if (found != mLayersWithQueuedFrames.cend()) {
2240 layersNeedingFences.add(layer);
2241 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002242 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002243 });
2244 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2246 displayDevice->setLayersNeedingFences(layersNeedingFences);
2247
2248 Region undefinedRegion{bounds};
2249 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2250
2251 display->editState().undefinedRegion = undefinedRegion;
2252 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002254 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002255}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002256
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002257// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002259// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002261// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002262// The returned HDR data space is one of
2263// - Dataspace::UNKNOWN
2264// - Dataspace::BT2020_HLG
2265// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002266Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2267 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002268 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002269 *outHdrDataSpace = Dataspace::UNKNOWN;
2270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002272 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 case Dataspace::V0_SCRGB:
2274 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002275 case Dataspace::BT2020:
2276 case Dataspace::BT2020_ITU:
2277 case Dataspace::BT2020_LINEAR:
2278 case Dataspace::DISPLAY_BT2020:
2279 bestDataSpace = Dataspace::DISPLAY_BT2020;
2280 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002282 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 case Dataspace::BT2020_PQ:
2285 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002287 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002288 case Dataspace::BT2020_HLG:
2289 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 // When there's mixed PQ content and HLG content, we set the HDR
2291 // data space to be BT2020_PQ and convert HLG to PQ.
2292 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2293 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002294 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002295 break;
2296 default:
2297 break;
2298 }
Romain Guy54f154a2017-10-24 21:40:32 +01002299 }
2300
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002302}
2303
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2306 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2308 *outMode = ColorMode::NATIVE;
2309 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002312 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002313
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002316
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002317 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2318
Peiyong Lindfde5112018-06-05 10:58:41 -07002319 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002320 const bool isHdr =
2321 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002322 if (isHdr) {
2323 bestDataSpace = hdrDataSpace;
2324 }
2325
Chia-I Wu0d711262018-05-21 15:19:35 -07002326 RenderIntent intent;
2327 switch (mDisplayColorSetting) {
2328 case DisplayColorSetting::MANAGED:
2329 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002330 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002331 break;
2332 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002333 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002334 break;
2335 default: // vendor display color setting
2336 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2337 break;
2338 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002339
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002340 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002341}
2342
Lloyd Pique32cbe282018-10-19 13:09:22 -07002343void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2344 auto display = displayDevice->getCompositionDisplay();
2345 const auto& displayState = display->getState();
2346
2347 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2348 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2349 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002350
David Sodmanfa9b2af2017-12-24 13:28:59 -08002351 // If nothing has changed (!dirty), don't recompose.
2352 // If something changed, but we don't currently have any visible layers,
2353 // and didn't when we last did a composition, then skip it this time.
2354 // The second rule does two things:
2355 // - When all layers are removed from a display, we'll emit one black
2356 // frame, then nothing more until we get new layers.
2357 // - When a display is created with a private layer stack, we won't
2358 // emit any black frames until a layer is added to the layer stack.
2359 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002360
Dominik Laskowski075d3172018-05-24 15:50:06 -07002361 const char flagPrefix[] = {'-', '+'};
2362 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002363 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2364 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2365 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2366 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002367
Lloyd Pique31cb2942018-10-19 17:23:03 -07002368 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002369
David Sodmanfa9b2af2017-12-24 13:28:59 -08002370 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002371 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002372 }
2373}
2374
Lloyd Pique32cbe282018-10-19 13:09:22 -07002375void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2376 auto display = displayDevice->getCompositionDisplay();
2377 const auto& displayState = display->getState();
2378
2379 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380 return;
David Sodman2b406362017-12-15 13:33:47 -08002381 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382
Lloyd Pique31cb2942018-10-19 17:23:03 -07002383 status_t result = display->getRenderSurface()->prepareFrame(
2384 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002387}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002388
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002390 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 ALOGV("doComposition");
2392
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393 auto display = displayDevice->getCompositionDisplay();
2394 const auto& displayState = display->getState();
2395
2396 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002398 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002399
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002404 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002405 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002406 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002407}
2408
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409void SurfaceFlinger::postFrame()
2410{
2411 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002412 const auto display = getDefaultDisplayDeviceLocked();
2413 if (display && getHwComposer().isConnected(*display->getId())) {
2414 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2416 logFrameStats();
2417 }
2418 }
2419}
2420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002422 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002424
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425 auto display = displayDevice->getCompositionDisplay();
2426 const auto& displayState = display->getState();
2427 const auto displayId = display->getId();
2428
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002430
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 if (displayId) {
2433 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002434 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002435 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002437 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002438
Chia-I Wu7b549592017-11-15 09:14:57 -08002439 // The layer buffer from the previous frame (if any) is released
2440 // by HWC only when the release fence from this frame (if any) is
2441 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 if (displayId && layer->hasHwcLayer(*displayId)) {
2443 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2444 layer->getHwcLayer(*displayId));
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.
David Sodman15094112018-10-11 09:39:37 -07002452 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
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
David Sodman15094112018-10-11 09:39:37 -07002458 layer->getBE().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()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002468 layer->getBE().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);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002527 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002529 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2532 if (index >= 0) {
2533 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2534 mInterceptor->saveDisplayDeletion(state.sequenceId);
2535 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002536 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002538 }
2539
2540 processDisplayChangesLocked();
2541 }
2542
2543 mPendingHotplugEvents.clear();
2544}
2545
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002548 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 const sp<IGraphicBufferProducer>& producer) {
2550 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002551 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002553 creationArgs.isSecure = state.isSecure;
2554 creationArgs.displaySurface = dispSurface;
2555 creationArgs.hasWideColorGamut = false;
2556 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2559 creationArgs.isPrimary = isInternalDisplay;
2560
2561 if (useColorManagement && displayId) {
2562 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002564 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002565 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002566 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002567
Dominik Laskowski7e045462018-05-30 13:02:02 -07002568 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002570 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571 }
tangrobin6753a022018-08-10 10:58:54 +08002572 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 if (displayId) {
2575 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002576 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002578 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579
Lloyd Pique90c115d2018-09-18 21:39:42 -07002580 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002582 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002583
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 // Make sure that composition can never be stalled by a virtual display
2585 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002586 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002587 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2589 }
2590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 creationArgs.displayInstallOrientation =
2592 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002593
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596
Lloyd Pique90c115d2018-09-18 21:39:42 -07002597 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
2599 if (maxFrameBufferAcquiredBuffers >= 3) {
2600 nativeWindowSurface->preallocateBuffers();
2601 }
2602
2603 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002604 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002605 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002607 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002609 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2610 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 if (!state.isVirtual()) {
2612 LOG_ALWAYS_FATAL_IF(!displayId);
2613 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 display->setLayerStack(state.layerStack);
2617 display->setProjection(state.orientation, state.viewport, state.frame);
2618 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621}
2622
Lloyd Pique347200f2017-12-14 17:00:15 -08002623void SurfaceFlinger::processDisplayChangesLocked() {
2624 // here we take advantage of Vector's copy-on-write semantics to
2625 // improve performance by skipping the transaction entirely when
2626 // know that the lists are identical
2627 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2628 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2629 if (!curr.isIdenticalTo(draw)) {
2630 mVisibleRegionsDirty = true;
2631 const size_t cc = curr.size();
2632 size_t dc = draw.size();
2633
2634 // find the displays that were removed
2635 // (ie: in drawing state but not in current state)
2636 // also handle displays that changed
2637 // (ie: displays that are in both lists)
2638 for (size_t i = 0; i < dc;) {
2639 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2640 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 // Save display IDs before disconnecting.
2642 const auto internalDisplayId = getInternalDisplayId();
2643 const auto externalDisplayId = getExternalDisplayId();
2644
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002647 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002650 if (mUseScheduler) {
2651 mScheduler->hotplugReceived(mAppConnectionHandle,
2652 EventThread::DisplayType::Primary, false);
2653 } else {
2654 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2655 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002657 if (mUseScheduler) {
2658 mScheduler->hotplugReceived(mAppConnectionHandle,
2659 EventThread::DisplayType::External, false);
2660 } else {
2661 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2662 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002663 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 } else {
2666 // this display is in both lists. see if something changed.
2667 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2670 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2671 if (state_binder != draw_binder) {
2672 // changing the surface is like destroying and
2673 // recreating the DisplayDevice, so we just remove it
2674 // from the drawing state, so that it get re-added
2675 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002677 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 mDrawingState.displays.removeItemsAt(i);
2681 dc--;
2682 // at this point we must loop to the next item
2683 continue;
2684 }
2685
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002688 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 }
2690 if ((state.orientation != draw[i].orientation) ||
2691 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 }
2694 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 }
2697 }
2698 }
2699 ++i;
2700 }
2701
2702 // find displays that were added
2703 // (ie: in current state but not in drawing state)
2704 for (size_t i = 0; i < cc; i++) {
2705 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2706 const DisplayDeviceState& state(curr[i]);
2707
Lloyd Pique542307f2018-10-19 13:24:08 -07002708 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 sp<IGraphicBufferProducer> producer;
2710 sp<IGraphicBufferProducer> bqProducer;
2711 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002712 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002715 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 // Virtual displays without a surface are dormant:
2717 // they have external state (layer stack, projection,
2718 // etc.) but no internal state (i.e. a DisplayDevice).
2719 if (state.surface != nullptr) {
2720 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002721 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 int width = 0;
2723 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2724 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2725 int height = 0;
2726 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2727 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2728 int intFormat = 0;
2729 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2730 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002731 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 displayId =
2734 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736
2737 // TODO: Plumb requested format back up to consumer
2738
2739 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 bqProducer, bqConsumer,
2742 state.displayName);
2743
2744 dispSurface = vds;
2745 producer = vds;
2746 }
2747 } else {
2748 ALOGE_IF(state.surface != nullptr,
2749 "adding a supported display, but rendering "
2750 "surface is provided (%p), ignoring it",
2751 state.surface.get());
2752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 displayId = state.displayId;
2754 LOG_ALWAYS_FATAL_IF(!displayId);
2755 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 producer = bqProducer;
2757 }
2758
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002762 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002764 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 LOG_ALWAYS_FATAL_IF(!displayId);
2766
2767 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002768 if (mUseScheduler) {
2769 mScheduler->hotplugReceived(mAppConnectionHandle,
2770 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002771 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002772 } else {
2773 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2774 true);
2775 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002777 if (mUseScheduler) {
2778 mScheduler->hotplugReceived(mAppConnectionHandle,
2779 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002780 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002781 } else {
2782 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2783 true);
2784 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002785 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 }
2787 }
2788 }
2789 }
2790 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002791
2792 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002793}
2794
Mathias Agopian87baae12012-07-31 12:38:26 -07002795void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002796{
Dan Stoza7dde5992015-05-22 09:51:44 -07002797 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002798 mCurrentState.traverseInZOrder([](Layer* layer) {
2799 layer->notifyAvailableFrames();
2800 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 /*
2803 * Traversal of the children
2804 * (perform the transaction for each of them if needed)
2805 */
2806
Robert Carr720e5062018-07-30 17:45:14 -07002807 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002808 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002811 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
2813 const uint32_t flags = layer->doTransaction(0);
2814 if (flags & Layer::eVisibleRegion)
2815 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002816
2817 if (flags & Layer::eInputInfoChanged) {
2818 inputChanged = true;
2819 }
Robert Carr2047fae2016-11-28 14:09:09 -08002820 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 }
2822
2823 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 */
2826
Mathias Agopiane57f2922012-08-09 16:29:12 -07002827 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002829 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002832 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002833 // The transform hint might have changed for some layers
2834 // (either because a display has changed, or because a layer
2835 // as changed).
2836 //
2837 // Walk through all the layers in currentLayers,
2838 // and update their transform hint.
2839 //
2840 // If a layer is visible only on a single display, then that
2841 // display is used to calculate the hint, otherwise we use the
2842 // default display.
2843 //
2844 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2845 // the hint is set before we acquire a buffer from the surface texture.
2846 //
2847 // NOTE: layer transactions have taken place already, so we use their
2848 // drawing state. However, SurfaceFlinger's own transaction has not
2849 // happened yet, so we must use the current state layer list
2850 // (soon to become the drawing state list).
2851 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002853 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002854 bool first = true;
2855 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002856 // NOTE: we rely on the fact that layers are sorted by
2857 // layerStack first (so we don't have to traverse the list
2858 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002860 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002861 currentlayerStack = layerStack;
2862 // figure out if this layerstack is mirrored
2863 // (more than one display) if so, pick the default display,
2864 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002865 hintDisplay = nullptr;
2866 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002867 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 if (hintDisplay) {
2869 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002870 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002872 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002873 }
2874 }
2875 }
2876 }
Chet Haase91d25932013-04-11 15:24:55 -07002877
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002878 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002879 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2880 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002881
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002882 // could be null when this layer is using a layerStack
2883 // that is not visible on any display. Also can occur at
2884 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002886 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002887
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002889 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002890 if (hintDisplay) {
2891 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002892 }
Robert Carr2047fae2016-11-28 14:09:09 -08002893
2894 first = false;
2895 });
Mathias Agopian84300952012-11-21 16:02:13 -08002896 }
2897
2898
Mathias Agopian3559b072012-08-15 13:46:03 -07002899 /*
2900 * Perform our own transaction if needed
2901 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002902
2903 if (mLayersAdded) {
2904 mLayersAdded = false;
2905 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002906 mVisibleRegionsDirty = true;
2907 }
2908
2909 // some layers might have been removed, so
2910 // we need to update the regions they're exposing.
2911 if (mLayersRemoved) {
2912 mLayersRemoved = false;
2913 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002914 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002915 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002916 // this layer is not visible anymore
2917 // TODO: we could traverse the tree from front to back and
2918 // compute the actual visible region
2919 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 Region visibleReg;
2921 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002922 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002923 }
Robert Carr2047fae2016-11-28 14:09:09 -08002924 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925 }
2926
2927 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002928
Vishnu Nairde19f852018-12-18 16:11:53 -08002929 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002930 updateInputWindows();
2931 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002932 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002933
Riley Andrews03414a12014-07-01 14:22:59 -07002934 updateCursorAsync();
2935}
2936
Robert Carr720e5062018-07-30 17:45:14 -07002937void SurfaceFlinger::updateInputWindows() {
2938 ATRACE_CALL();
2939
Vishnu Nairde19f852018-12-18 16:11:53 -08002940 if (mInputFlinger == nullptr) {
2941 return;
2942 }
2943
Robert Carr720e5062018-07-30 17:45:14 -07002944 Vector<InputWindowInfo> inputHandles;
2945
2946 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2947 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002948 // When calculating the screen bounds we ignore the transparent region since it may
2949 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002950 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002951 }
2952 });
2953 mInputFlinger->setInputWindows(inputHandles);
2954}
2955
chaviwfbe5d9c2018-12-26 12:23:37 -08002956void SurfaceFlinger::executeInputWindowCommands() {
2957 if (!mInputFlinger) {
2958 return;
2959 }
2960
2961 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2962 if (transferTouchFocusCommand.fromToken != nullptr &&
2963 transferTouchFocusCommand.toToken != nullptr &&
2964 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2965 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2966 transferTouchFocusCommand.toToken);
2967 }
2968 }
2969
2970 mInputWindowCommands.clear();
2971}
2972
Riley Andrews03414a12014-07-01 14:22:59 -07002973void SurfaceFlinger::updateCursorAsync()
2974{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002975 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002976 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002977 continue;
2978 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002980 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2981 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002982 }
2983 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002984}
2985
chaviw61626f22018-11-15 16:26:27 -08002986void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2987 if (layer->hasReadyFrame()) {
2988 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2989 if (layer->shouldPresentNow(expectedPresentTime)) {
2990 bool ignored = false;
2991 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2992 }
2993 }
2994 layer->releasePendingBuffer(systemTime());
2995}
2996
Mathias Agopian4fec8732012-06-29 14:12:52 -07002997void SurfaceFlinger::commitTransaction()
2998{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002999 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003001 for (const auto& l : mLayersPendingRemoval) {
3002 recordBufferingStats(l->getName().string(),
3003 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003004
3005 // We need to release the HWC layers when the Layer is removed
3006 // from the current state otherwise the HWC layer just continues
3007 // showing at its last configured state until we eventually
3008 // abandon the buffer queue.
3009 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003010 l->destroyHwcLayersForAllDisplays();
3011 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003012 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 }
3014 mLayersPendingRemoval.clear();
3015 }
3016
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003017 // If this transaction is part of a window animation then the next frame
3018 // we composite should be considered an animation as well.
3019 mAnimCompositionPending = mAnimTransactionPending;
3020
Mathias Agopian4fec8732012-06-29 14:12:52 -07003021 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003022 // clear the "changed" flags in current state
3023 mCurrentState.colorMatrixChanged = false;
3024
Robert Carr1f0a16a2016-10-24 16:27:39 -07003025 mDrawingState.traverseInZOrder([](Layer* layer) {
3026 layer->commitChildList();
3027 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003028 mTransactionPending = false;
3029 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003030 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031}
3032
Lloyd Pique32cbe282018-10-19 13:09:22 -07003033void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003035 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003037
Lloyd Pique32cbe282018-10-19 13:09:22 -07003038 auto display = displayDevice->getCompositionDisplay();
3039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 Region aboveOpaqueLayers;
3041 Region aboveCoveredLayers;
3042 Region dirty;
3043
Mathias Agopian87baae12012-07-31 12:38:26 -07003044 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045
Robert Carr2047fae2016-11-28 14:09:09 -08003046 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003047 // start with the whole surface at its current location
3048 const Layer::State& s(layer->getDrawingState());
3049
Jesse Hall01e29052013-02-19 16:13:35 -08003050 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003051 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003052 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003054
Mathias Agopianab028732010-03-16 16:41:46 -07003055 /*
3056 * opaqueRegion: area of a surface that is fully opaque.
3057 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003059
3060 /*
3061 * visibleRegion: area of a surface that is visible on screen
3062 * and not fully transparent. This is essentially the layer's
3063 * footprint minus the opaque regions above it.
3064 * Areas covered by a translucent surface are considered visible.
3065 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003067
3068 /*
3069 * coveredRegion: area of a surface that is covered by all
3070 * visible regions above it (which includes the translucent areas).
3071 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003073
Jesse Halla8026d22012-09-25 13:25:04 -07003074 /*
3075 * transparentRegion: area of a surface that is hinted to be completely
3076 * transparent. This is only used to tell when the layer has no visible
3077 * non-transparent regions and can be removed from the layer list. It
3078 * does not affect the visibleRegion of this layer or any layers
3079 * beneath it. The hint may not be correct if apps don't respect the
3080 * SurfaceView restrictions (which, sadly, some don't).
3081 */
3082 Region transparentRegion;
3083
Mathias Agopianab028732010-03-16 16:41:46 -07003084
3085 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003086 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003087 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003091 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003092 if (!visibleRegion.isEmpty()) {
3093 // Remove the transparent area from the visible region
3094 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003095 if (tr.preserveRects()) {
3096 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003097 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003098 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003099 // transformation too complex, can't do the
3100 // transparent region optimization.
3101 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003102 }
Mathias Agopianab028732010-03-16 16:41:46 -07003103 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104
Mathias Agopianab028732010-03-16 16:41:46 -07003105 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003107 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003108 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003109 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003110 // the opaque region is the layer's footprint
3111 opaqueRegion = visibleRegion;
3112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 }
3114 }
3115
Robert Carre5f4f692018-01-12 13:12:28 -08003116 if (visibleRegion.isEmpty()) {
3117 layer->clearVisibilityRegions();
3118 return;
3119 }
3120
Mathias Agopianab028732010-03-16 16:41:46 -07003121 // Clip the covered region to the visible region
3122 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3123
3124 // Update aboveCoveredLayers for next (lower) layer
3125 aboveCoveredLayers.orSelf(visibleRegion);
3126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 // subtract the opaque region covered by the layers above us
3128 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129
3130 // compute this layer's dirty region
3131 if (layer->contentDirty) {
3132 // we need to invalidate the whole region
3133 dirty = visibleRegion;
3134 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003135 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 layer->contentDirty = false;
3137 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003138 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003139 * the exposed region consists of two components:
3140 * 1) what's VISIBLE now and was COVERED before
3141 * 2) what's EXPOSED now less what was EXPOSED before
3142 *
3143 * note that (1) is conservative, we start with the whole
3144 * visible region but only keep what used to be covered by
3145 * something -- which mean it may have been exposed.
3146 *
3147 * (2) handles areas that were not covered by anything but got
3148 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003149 */
Mathias Agopianab028732010-03-16 16:41:46 -07003150 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003151 const Region oldVisibleRegion = layer->visibleRegion;
3152 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003153 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3154 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
3156 dirty.subtractSelf(aboveOpaqueLayers);
3157
3158 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003159 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160
Mathias Agopianab028732010-03-16 16:41:46 -07003161 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003163
Jesse Halla8026d22012-09-25 13:25:04 -07003164 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 layer->setVisibleRegion(visibleRegion);
3166 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003167 layer->setVisibleNonTransparentRegion(
3168 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003169 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
Mathias Agopian87baae12012-07-31 12:38:26 -07003171 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172}
3173
Chia-I Wuab0c3192017-08-01 11:29:00 -07003174void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003175 for (const auto& [token, displayDevice] : mDisplays) {
3176 auto display = displayDevice->getCompositionDisplay();
3177 if (display->belongsInOutput(layer->getLayerStack())) {
3178 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003179 }
3180 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003181}
3182
Dan Stoza6b9454d2014-11-07 16:00:59 -08003183bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003185 ALOGV("handlePageFlip");
3186
Brian Andersond6927fb2016-07-23 23:37:30 -07003187 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188
Mathias Agopian4fec8732012-06-29 14:12:52 -07003189 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003190 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003191 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003192
3193 // Store the set of layers that need updates. This set must not change as
3194 // buffers are being latched, as this could result in a deadlock.
3195 // Example: Two producers share the same command stream and:
3196 // 1.) Layer 0 is latched
3197 // 2.) Layer 0 gets a new frame
3198 // 2.) Layer 1 gets a new frame
3199 // 3.) Layer 1 is latched.
3200 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3201 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003202 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003203 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003204 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003205 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3206 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003207 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003208 } else {
3209 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003210 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003211 } else {
3212 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003213 }
Robert Carr2047fae2016-11-28 14:09:09 -08003214 });
3215
Lloyd Piquef2c79392018-12-20 16:23:33 -08003216 if (!mLayersWithQueuedFrames.empty()) {
3217 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3218 // writes to Layer current state. See also b/119481871
3219 Mutex::Autolock lock(mStateLock);
3220
3221 for (auto& layer : mLayersWithQueuedFrames) {
3222 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3223 layer->useSurfaceDamage();
3224 invalidateLayerStack(layer, dirty);
3225 if (layer->isBufferLatched()) {
3226 newDataLatched = true;
3227 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003228 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003229 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003230
Alec Mouri86770e52018-09-24 22:40:58 +00003231 // Clear the renderengine fence here...
3232 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3233 // clear instead of sp::clear.
3234 getBE().flushFence = Fence::NO_FENCE;
3235
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003236 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237
Vishnu Nairde19f852018-12-18 16:11:53 -08003238 if (visibleRegions) {
3239 // Update input window info if the layer receives its first buffer.
3240 updateInputWindows();
3241 }
3242
Dan Stoza6b9454d2014-11-07 16:00:59 -08003243 // If we will need to wake up at some time in the future to deal with a
3244 // queued frame that shouldn't be displayed during this vsync period, wake
3245 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003246 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247 signalLayerUpdate();
3248 }
3249
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003250 // enter boot animation on first buffer latch
3251 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3252 ALOGI("Enter boot animation");
3253 mBootStage = BootStage::BOOTANIMATION;
3254 }
3255
Dan Stoza6b9454d2014-11-07 16:00:59 -08003256 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003257 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258}
3259
Mathias Agopianad456f92011-01-13 17:53:01 -08003260void SurfaceFlinger::invalidateHwcGeometry()
3261{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003262 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003263}
3264
Lloyd Pique32cbe282018-10-19 13:09:22 -07003265void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003266 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003267 auto display = displayDevice->getCompositionDisplay();
3268
Dan Stoza71433162014-02-04 16:22:36 -08003269 // We only need to actually compose the display if:
3270 // 1) It is being handled by hardware composer, which may need this to
3271 // keep its virtual display state machine in sync, or
3272 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003273 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003274 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003275 return;
3276 }
3277
Dan Stoza9e56aa02015-11-02 13:00:03 -08003278 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003279 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003280
3281 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003282 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283}
3284
Lloyd Pique32cbe282018-10-19 13:09:22 -07003285bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003286 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003287
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288 auto display = displayDevice->getCompositionDisplay();
3289 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003290 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003291
3292 const Region bounds(displayState.bounds);
3293 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003294 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003295 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003296
Peiyong Lind3788632018-09-18 16:01:31 -07003297 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003298 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003299
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003300 // Framebuffer will live in this scope for GPU composition.
3301 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3302
Dan Stoza9e56aa02015-11-02 13:00:03 -08003303 if (hasClientComposition) {
3304 ALOGV("hasClientComposition");
3305
Lloyd Pique31cb2942018-10-19 17:23:03 -07003306 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003307
3308 if (buf == nullptr) {
3309 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3310 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003311 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003312 return false;
3313 }
3314
3315 // Bind the framebuffer in this scope.
3316 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3317 buf->getNativeBuffer());
3318
3319 if (fbo->getStatus() != NO_ERROR) {
3320 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003322 return false;
3323 }
3324
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003325 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003326 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003327 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003328 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003329 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003330 getRenderEngine().setOutputDataSpace(outputDataspace);
3331 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003332 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003333
Lloyd Pique441d5042018-10-18 16:49:51 -07003334 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003335 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003336 getHwComposer()
3337 .hasDisplayCapability(displayId,
3338 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003339
Peiyong Lind3788632018-09-18 16:01:31 -07003340 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003341 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3342 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003343 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003344 }
3345
Lloyd Pique31cb2942018-10-19 17:23:03 -07003346 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003347
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003348 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003350 // when using overlays, we assume a fully transparent framebuffer
3351 // NOTE: we could reduce how much we need to clear, for instance
3352 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003353 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003354 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003355 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003356 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003357 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003358 // we're left with the letterbox region
3359 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003360 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003361
3362 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003363 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003364
Mathias Agopianb9494d52012-04-18 02:28:45 -07003365 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003366 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003367 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003368 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003369 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003370 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003371
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 const Rect& bounds = displayState.bounds;
3373 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003374 if (scissor != bounds) {
3375 // scissor doesn't match the screen's dimensions, so we
3376 // need to clear everything outside of it and enable
3377 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003378
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003379 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003380 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003381 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003382 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003383
Mathias Agopian85d751c2012-08-29 16:59:24 -07003384 /*
3385 * and then, render the layers targeted at the framebuffer
3386 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003387
Dan Stoza9e56aa02015-11-02 13:00:03 -08003388 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003389 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003390 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003392 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003393 displayTransform.transform(layer->visibleRegion)));
3394 ALOGV("Layer: %s", layer->getName().string());
3395 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003396 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003397 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003398 case HWC2::Composition::Cursor:
3399 case HWC2::Composition::Device:
3400 case HWC2::Composition::Sideband:
3401 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003402 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003403 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003404 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003405 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003406 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 // never clear the very first layer since we're
3408 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003409 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003412 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003414 if (layer->hasColorTransform()) {
3415 mat4 tmpMatrix;
3416 if (applyColorMatrix) {
3417 tmpMatrix = mDrawingState.colorMatrix;
3418 }
3419 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003420 getRenderEngine().setColorTransform(tmpMatrix);
3421 } else {
3422 getRenderEngine().setColorTransform(colorMatrix);
3423 }
David Sodmanc1498e62018-09-12 14:36:26 -07003424 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003425 break;
3426 }
3427 default:
3428 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003429 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003430 } else {
3431 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003432 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003434 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003435
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003436 // Perform some cleanup steps if we used client composition.
3437 if (hasClientComposition) {
3438 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003439 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003440 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003441 // Clear out error flags here so that we don't wait until next
3442 // composition to log.
3443 getRenderEngine().checkErrors();
3444 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003445 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446}
3447
Chia-I Wu28e3a252018-09-07 12:05:02 -07003448void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003449 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003450 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003451}
3452
Dan Stoza7d89d062015-04-30 13:29:25 -07003453status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003454 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003455 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003456 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003457 const sp<Layer>& parent,
3458 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003459{
Dan Stoza7d89d062015-04-30 13:29:25 -07003460 // add this layer to the current state list
3461 {
3462 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003464 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3465 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003466 return NO_MEMORY;
3467 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003468 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003469 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003470 } else if (parent == nullptr) {
3471 lbc->onRemovedFromCurrentState();
3472 } else if (parent->isRemovedFromCurrentState()) {
3473 parent->addChild(lbc);
3474 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003475 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003476 parent->addChild(lbc);
3477 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003478
Yiwei Zhang243b3782018-05-15 17:40:04 -07003479 if (gbc != nullptr) {
3480 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3481 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3482 mMaxGraphicBufferProducerListSize,
3483 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3484 mGraphicBufferProducerList.size(),
3485 mMaxGraphicBufferProducerListSize, mNumLayers);
3486 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003487 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003488 }
3489
Mathias Agopian96f08192010-06-02 23:28:45 -07003490 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003491 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003492
Dan Stoza7d89d062015-04-30 13:29:25 -07003493 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003494}
3495
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003496uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003497 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003498}
3499
Mathias Agopian3f844832013-08-07 21:24:32 -07003500uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003501 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502}
3503
Mathias Agopian3f844832013-08-07 21:24:32 -07003504uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003505 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003506}
3507
3508uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003509 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003510 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003511 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003513 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 }
3515 return old;
3516}
3517
Marissa Wall713b63f2018-10-17 15:42:43 -07003518bool SurfaceFlinger::flushTransactionQueues() {
3519 Mutex::Autolock _l(mStateLock);
3520 auto it = mTransactionQueues.begin();
3521 while (it != mTransactionQueues.end()) {
3522 auto& [applyToken, transactionQueue] = *it;
3523
3524 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003525 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3526 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003527 break;
3528 }
chaviw273171b2018-12-26 11:46:30 -08003529 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003530 transactionQueue.pop();
3531 }
3532
3533 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3534 }
3535 return mTransactionQueues.empty();
3536}
3537
chaviwca27f252018-02-06 16:46:39 -08003538bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3539 for (const ComposerState& state : states) {
3540 // Here we need to check that the interface we're given is indeed
3541 // one of our own. A malicious client could give us a nullptr
3542 // IInterface, or one of its own or even one of our own but a
3543 // different type. All these situations would cause us to crash.
3544 if (state.client == nullptr) {
3545 return true;
3546 }
3547
3548 sp<IBinder> binder = IInterface::asBinder(state.client);
3549 if (binder == nullptr) {
3550 return true;
3551 }
3552
3553 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3554 return true;
3555 }
3556 }
3557 return false;
3558}
3559
Marissa Wall17b4e452018-12-26 16:32:34 -08003560bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3561 const Vector<ComposerState>& states) {
3562 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3563 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3564 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3565 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3566 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3567 return false;
3568 }
3569
Marissa Wall713b63f2018-10-17 15:42:43 -07003570 for (const ComposerState& state : states) {
3571 const layer_state_t& s = state.state;
3572 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3573 continue;
3574 }
3575 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003576 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003577 }
3578 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003579 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003580}
3581
3582void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3583 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003584 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003585 const InputWindowCommands& inputWindowCommands,
3586 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003587 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003588 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003589
chaviwca27f252018-02-06 16:46:39 -08003590 if (containsAnyInvalidClientState(states)) {
3591 return;
3592 }
3593
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 // If its TransactionQueue already has a pending TransactionState or if it is pending
3595 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003596 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3597 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003598 setTransactionFlags(eTransactionNeeded);
3599 return;
3600 }
3601
chaviw273171b2018-12-26 11:46:30 -08003602 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003603}
3604
3605void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003606 const Vector<DisplayState>& displays, uint32_t flags,
3607 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003608 uint32_t transactionFlags = 0;
3609
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003610 if (flags & eAnimation) {
3611 // For window updates that are part of an animation we must wait for
3612 // previous animation "frames" to be handled.
3613 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003614 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003615 if (CC_UNLIKELY(err != NO_ERROR)) {
3616 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003617 // caller after a few seconds.
3618 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3619 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003620 mAnimTransactionPending = false;
3621 break;
3622 }
3623 }
3624 }
3625
chaviwca27f252018-02-06 16:46:39 -08003626 for (const DisplayState& display : displays) {
3627 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003628 }
3629
Marissa Walle2ffb422018-10-12 11:33:52 -07003630 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003631 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003633 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003634 // If the state doesn't require a traversal and there are callbacks, send them now
3635 if (!(clientStateFlags & eTraversalNeeded)) {
3636 mTransactionCompletedThread.sendCallbacks();
3637 }
3638 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003639
chaviw273171b2018-12-26 11:46:30 -08003640 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3641
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003642 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3643 // anyway. This can be used as a flush mechanism for previous async transactions.
3644 // Empty animation transaction can be used to simulate back-pressure, so also force a
3645 // transaction for empty animation transactions.
3646 if (transactionFlags == 0 &&
3647 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003648 transactionFlags = eTransactionNeeded;
3649 }
3650
Mathias Agopian386aa982011-11-07 21:58:03 -08003651 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003652 if (mInterceptor->isEnabled()) {
3653 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003654 }
Irvel468051e2016-06-13 16:44:44 -07003655
Mathias Agopian386aa982011-11-07 21:58:03 -08003656 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003657 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3658 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003659 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003660
3661 // if this is a synchronous transaction, wait for it to take effect
3662 // before returning.
3663 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003664 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003665 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003666 if (flags & eAnimation) {
3667 mAnimTransactionPending = true;
3668 }
3669 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003670 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3671 if (CC_UNLIKELY(err != NO_ERROR)) {
3672 // just in case something goes wrong in SF, return to the
3673 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3675 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003676 break;
3677 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679 }
3680}
3681
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003682uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3683 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3684 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003685
Mathias Agopiane57f2922012-08-09 16:29:12 -07003686 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003687 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3688
3689 const uint32_t what = s.what;
3690 if (what & DisplayState::eSurfaceChanged) {
3691 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3692 state.surface = s.surface;
3693 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003694 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003695 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003696 if (what & DisplayState::eLayerStackChanged) {
3697 if (state.layerStack != s.layerStack) {
3698 state.layerStack = s.layerStack;
3699 flags |= eDisplayTransactionNeeded;
3700 }
3701 }
3702 if (what & DisplayState::eDisplayProjectionChanged) {
3703 if (state.orientation != s.orientation) {
3704 state.orientation = s.orientation;
3705 flags |= eDisplayTransactionNeeded;
3706 }
3707 if (state.frame != s.frame) {
3708 state.frame = s.frame;
3709 flags |= eDisplayTransactionNeeded;
3710 }
3711 if (state.viewport != s.viewport) {
3712 state.viewport = s.viewport;
3713 flags |= eDisplayTransactionNeeded;
3714 }
3715 }
3716 if (what & DisplayState::eDisplaySizeChanged) {
3717 if (state.width != s.width) {
3718 state.width = s.width;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 if (state.height != s.height) {
3722 state.height = s.height;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 }
3726
Mathias Agopiane57f2922012-08-09 16:29:12 -07003727 return flags;
3728}
3729
Robert Carrd4ae7f32018-06-07 16:10:57 -07003730bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3731 IPCThreadState* ipc = IPCThreadState::self();
3732 const int pid = ipc->getCallingPid();
3733 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003734 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003735 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003736 return false;
3737 }
3738 return true;
3739}
3740
chaviwca27f252018-02-06 16:46:39 -08003741uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3742 const layer_state_t& s = composerState.state;
3743 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3744
Mathias Agopian13127d82013-03-05 17:47:11 -08003745 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003746 if (layer == nullptr) {
3747 return 0;
3748 }
3749
chaviw8b3871a2017-11-01 17:41:01 -07003750 uint32_t flags = 0;
3751
Garfield Tan8a3083e2018-12-03 13:21:07 -08003752 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003753 bool geometryAppliesWithResize =
3754 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003755
3756 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3757 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003758 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003759 layer->pushPendingState();
3760 }
3761
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (what & layer_state_t::ePositionChanged) {
3763 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3764 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 }
chaviw8b3871a2017-11-01 17:41:01 -07003766 }
3767 if (what & layer_state_t::eLayerChanged) {
3768 // NOTE: index needs to be calculated before we update the state
3769 const auto& p = layer->getParent();
3770 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003771 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003772 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 mCurrentState.layersSortedByZ.removeAt(idx);
3774 mCurrentState.layersSortedByZ.add(layer);
3775 // we need traversal (state changed)
3776 // AND transaction (list changed)
3777 flags |= eTransactionNeeded|eTraversalNeeded;
3778 }
chaviw8b3871a2017-11-01 17:41:01 -07003779 } else {
3780 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003781 flags |= eTransactionNeeded|eTraversalNeeded;
3782 }
3783 }
chaviw8b3871a2017-11-01 17:41:01 -07003784 }
3785 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003786 // NOTE: index needs to be calculated before we update the state
3787 const auto& p = layer->getParent();
3788 if (p == nullptr) {
3789 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3790 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3791 mCurrentState.layersSortedByZ.removeAt(idx);
3792 mCurrentState.layersSortedByZ.add(layer);
3793 // we need traversal (state changed)
3794 // AND transaction (list changed)
3795 flags |= eTransactionNeeded|eTraversalNeeded;
3796 }
3797 } else {
3798 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3799 flags |= eTransactionNeeded|eTraversalNeeded;
3800 }
chaviw8b3871a2017-11-01 17:41:01 -07003801 }
3802 }
3803 if (what & layer_state_t::eSizeChanged) {
3804 if (layer->setSize(s.w, s.h)) {
3805 flags |= eTraversalNeeded;
3806 }
3807 }
3808 if (what & layer_state_t::eAlphaChanged) {
3809 if (layer->setAlpha(s.alpha))
3810 flags |= eTraversalNeeded;
3811 }
3812 if (what & layer_state_t::eColorChanged) {
3813 if (layer->setColor(s.color))
3814 flags |= eTraversalNeeded;
3815 }
Peiyong Lind3788632018-09-18 16:01:31 -07003816 if (what & layer_state_t::eColorTransformChanged) {
3817 if (layer->setColorTransform(s.colorTransform)) {
3818 flags |= eTraversalNeeded;
3819 }
3820 }
chaviw8b3871a2017-11-01 17:41:01 -07003821 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003822 // TODO: b/109894387
3823 //
3824 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3825 // rotation. To see the problem observe that if we have a square parent, and a child
3826 // of the same size, then we rotate the child 45 degrees around it's center, the child
3827 // must now be cropped to a non rectangular 8 sided region.
3828 //
3829 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3830 // private API, and the WindowManager only uses rotation in one case, which is on a top
3831 // level layer in which cropping is not an issue.
3832 //
3833 // However given that abuse of rotation matrices could lead to surfaces extending outside
3834 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3835 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3836 // transformations.
3837 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003838 flags |= eTraversalNeeded;
3839 }
3840 if (what & layer_state_t::eTransparentRegionChanged) {
3841 if (layer->setTransparentRegionHint(s.transparentRegion))
3842 flags |= eTraversalNeeded;
3843 }
3844 if (what & layer_state_t::eFlagsChanged) {
3845 if (layer->setFlags(s.flags, s.mask))
3846 flags |= eTraversalNeeded;
3847 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003848 if (what & layer_state_t::eCropChanged_legacy) {
3849 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003850 flags |= eTraversalNeeded;
3851 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003852 if (what & layer_state_t::eCornerRadiusChanged) {
3853 if (layer->setCornerRadius(s.cornerRadius))
3854 flags |= eTraversalNeeded;
3855 }
chaviw8b3871a2017-11-01 17:41:01 -07003856 if (what & layer_state_t::eLayerStackChanged) {
3857 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3858 // We only allow setting layer stacks for top level layers,
3859 // everything else inherits layer stack from its parent.
3860 if (layer->hasParent()) {
3861 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3862 layer->getName().string());
3863 } else if (idx < 0) {
3864 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3865 "that also does not appear in the top level layer list. Something"
3866 " has gone wrong.", layer->getName().string());
3867 } else if (layer->setLayerStack(s.layerStack)) {
3868 mCurrentState.layersSortedByZ.removeAt(idx);
3869 mCurrentState.layersSortedByZ.add(layer);
3870 // we need traversal (state changed)
3871 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003872 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003873 }
3874 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003875 if (what & layer_state_t::eDeferTransaction_legacy) {
3876 if (s.barrierHandle_legacy != nullptr) {
3877 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3878 } else if (s.barrierGbp_legacy != nullptr) {
3879 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003880 if (authenticateSurfaceTextureLocked(gbp)) {
3881 const auto& otherLayer =
3882 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003883 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003884 } else {
3885 ALOGE("Attempt to defer transaction to to an"
3886 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003887 }
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 // We don't trigger a traversal here because if no other state is
3890 // changed, we don't want this to cause any more work
3891 }
3892 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003893 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003895 if (!hadParent) {
3896 mCurrentState.layersSortedByZ.remove(layer);
3897 }
chaviw8b3871a2017-11-01 17:41:01 -07003898 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 }
3901 if (what & layer_state_t::eReparentChildren) {
3902 if (layer->reparentChildren(s.reparentHandle)) {
3903 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003904 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003905 }
chaviw8b3871a2017-11-01 17:41:01 -07003906 if (what & layer_state_t::eDetachChildren) {
3907 layer->detachChildren();
3908 }
3909 if (what & layer_state_t::eOverrideScalingModeChanged) {
3910 layer->setOverrideScalingMode(s.overrideScalingMode);
3911 // We don't trigger a traversal here because if no other state is
3912 // changed, we don't want this to cause any more work
3913 }
Marissa Wall61c58622018-07-18 10:12:20 -07003914 if (what & layer_state_t::eTransformChanged) {
3915 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3916 }
3917 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3918 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3919 flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eCropChanged) {
3922 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3923 }
Marissa Wall861616d2018-10-22 12:52:23 -07003924 if (what & layer_state_t::eFrameChanged) {
3925 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3926 }
Marissa Wall61c58622018-07-18 10:12:20 -07003927 if (what & layer_state_t::eBufferChanged) {
3928 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eAcquireFenceChanged) {
3931 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eDataspaceChanged) {
3934 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3935 }
3936 if (what & layer_state_t::eHdrMetadataChanged) {
3937 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3940 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eApiChanged) {
3943 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eSidebandStreamChanged) {
3946 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3947 }
Robert Carr720e5062018-07-30 17:45:14 -07003948 if (what & layer_state_t::eInputInfoChanged) {
3949 layer->setInputInfo(s.inputInfo);
3950 flags |= eTraversalNeeded;
3951 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003952 std::vector<sp<CallbackHandle>> callbackHandles;
3953 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3954 mTransactionCompletedThread.run();
3955 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3956 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3957 }
3958 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003959 if (what & layer_state_t::eCachedBufferChanged) {
3960 sp<GraphicBuffer> buffer =
3961 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3962 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3963 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003964 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3965 // Do not put anything that updates layer state or modifies flags after
3966 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003967 return flags;
3968}
3969
chaviw273171b2018-12-26 11:46:30 -08003970uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3971 uint32_t flags = 0;
3972 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3973 flags |= eTraversalNeeded;
3974 }
3975
3976 mInputWindowCommands.merge(inputWindowCommands);
3977 return flags;
3978}
3979
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003980status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003981 const String8& name,
3982 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003983 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003984 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003985 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003987 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003988 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003989 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003991 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003992
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003993 status_t result = NO_ERROR;
3994
3995 sp<Layer> layer;
3996
Cody Northropbc755282017-03-31 12:00:08 -06003997 String8 uniqueName = getUniqueLayerName(name);
3998
Mathias Agopian3165cc22012-08-08 19:42:09 -07003999 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004000 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004001 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4002 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004005 case ISurfaceComposerClient::eFXSurfaceBufferState:
4006 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4007 break;
chaviw13fdc492017-06-27 12:40:18 -07004008 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004009 // check if buffer size is set for color layer.
4010 if (w > 0 || h > 0) {
4011 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4012 int(w), int(h));
4013 return BAD_VALUE;
4014 }
4015
chaviw13fdc492017-06-27 12:40:18 -07004016 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004017 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004018 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004019 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004020 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004021 // check if buffer size is set for container layer.
4022 if (w > 0 || h > 0) {
4023 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4024 int(w), int(h));
4025 return BAD_VALUE;
4026 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004027 result = createContainerLayer(client,
4028 uniqueName, w, h, flags,
4029 handle, &layer);
4030 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004031 default:
4032 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 break;
4034 }
4035
Dan Stoza7d89d062015-04-30 13:29:25 -07004036 if (result != NO_ERROR) {
4037 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004039
Chia-I Wuab0c3192017-08-01 11:29:00 -07004040 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4041 // TODO b/64227542
4042 if (windowType == 441731) {
4043 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4044 layer->setPrimaryDisplayOnly();
4045 }
4046
Albert Chaulk479c60c2017-01-27 14:21:34 -05004047 layer->setInfo(windowType, ownerUid);
4048
Robert Carrb89ea9d2018-12-10 13:01:14 -08004049 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4050 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4051 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004052 if (result != NO_ERROR) {
4053 return result;
4054 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004055 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004056
4057 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004058 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059}
4060
Cody Northropbc755282017-03-31 12:00:08 -06004061String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4062{
4063 bool matchFound = true;
4064 uint32_t dupeCounter = 0;
4065
4066 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4067 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4068
Dan Stoza436ccf32018-06-21 12:10:12 -07004069 // Grab the state lock since we're accessing mCurrentState
4070 Mutex::Autolock lock(mStateLock);
4071
Cody Northropbc755282017-03-31 12:00:08 -06004072 // Loop over layers until we're sure there is no matching name
4073 while (matchFound) {
4074 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004075 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004076 if (layer->getName() == uniqueName) {
4077 matchFound = true;
4078 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4079 }
4080 });
4081 }
4082
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004083 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4084 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004085
4086 return uniqueName;
4087}
4088
Marissa Wallfd668622018-05-10 10:21:13 -07004089status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4090 uint32_t w, uint32_t h, uint32_t flags,
4091 PixelFormat& format, sp<IBinder>* handle,
4092 sp<IGraphicBufferProducer>* gbp,
4093 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004095 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 case PIXEL_FORMAT_TRANSPARENT:
4097 case PIXEL_FORMAT_TRANSLUCENT:
4098 format = PIXEL_FORMAT_RGBA_8888;
4099 break;
4100 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004101 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 break;
4103 }
4104
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004105 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004106 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004107 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004108 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004109 *handle = layer->getHandle();
4110 *gbp = layer->getProducer();
4111 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004113
Marissa Wallfd668622018-05-10 10:21:13 -07004114 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004115 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116}
4117
Marissa Wall61c58622018-07-18 10:12:20 -07004118status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4119 uint32_t w, uint32_t h, uint32_t flags,
4120 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004121 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004122 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004123 *handle = layer->getHandle();
4124 *outLayer = layer;
4125
4126 return NO_ERROR;
4127}
4128
chaviw13fdc492017-06-27 12:40:18 -07004129status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004130 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004131 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004133 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004135 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004136}
4137
Robert Carr6b3f6c52018-08-13 13:05:17 -07004138status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4139 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4140 sp<IBinder>* handle, sp<Layer>* outLayer)
4141{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004142 *outLayer =
4143 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004144 *handle = (*outLayer)->getHandle();
4145 return NO_ERROR;
4146}
4147
4148
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004149void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004150 mLayersPendingRemoval.add(layer);
4151 mLayersRemoved = true;
4152 setTransactionFlags(eTransactionNeeded);
4153}
4154
Robert Carr695d5282018-12-18 15:27:58 -08004155void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004156{
Robert Carr2e102c92018-10-23 12:11:15 -07004157 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004158 // If a layer has a parent, we allow it to out-live it's handle
4159 // with the idea that the parent holds a reference and will eventually
4160 // be cleaned up. However no one cleans up the top-level so we do so
4161 // here.
4162 if (layer->getParent() == nullptr) {
4163 mCurrentState.layersSortedByZ.remove(layer);
4164 }
4165 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004166 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004167}
4168
Mathias Agopianb60314a2012-04-10 22:09:54 -07004169// ---------------------------------------------------------------------------
4170
Andy McFadden13a082e2012-08-24 10:16:42 -07004171void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004172 const auto display = getDefaultDisplayDeviceLocked();
4173 if (!display) return;
4174
4175 const sp<IBinder> token = display->getDisplayToken().promote();
4176 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004177
Jesse Hall01e29052013-02-19 16:13:35 -08004178 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004179 Vector<ComposerState> state;
4180 Vector<DisplayState> displays;
4181 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004182 d.what = DisplayState::eDisplayProjectionChanged |
4183 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004184 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004185 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004186 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004187 d.frame.makeInvalid();
4188 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004189 d.width = 0;
4190 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004191 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004192 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004193
Dominik Laskowskie9774092018-12-11 10:04:24 -08004194 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004195
Dominik Laskowski83b88212018-12-11 13:34:06 -08004196 const nsecs_t vsyncPeriod = getVsyncPeriod();
4197 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004198
Brian Andersond0010582017-03-07 13:20:31 -08004199 // Use phase of 0 since phase is not known.
4200 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004201 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004202 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004203}
4204
4205void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004206 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004207 postMessageAsync(
4208 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004209}
4210
Dominik Laskowskie9774092018-12-11 10:04:24 -08004211void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004212 if (display->isVirtual()) {
4213 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004214 return;
4215 }
4216
Dominik Laskowski075d3172018-05-24 15:50:06 -07004217 const auto displayId = display->getId();
4218 LOG_ALWAYS_FATAL_IF(!displayId);
4219
Dominik Laskowski34157762018-10-31 13:07:19 -07004220 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004221
4222 int currentMode = display->getPowerMode();
4223 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004224 return;
4225 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227 display->setPowerMode(mode);
4228
Lloyd Pique4dccc412018-01-22 17:21:36 -08004229 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004230 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004231 }
4232
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004233 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004234 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004236 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004237 if (mUseScheduler) {
4238 mScheduler->onScreenAcquired(mAppConnectionHandle);
4239 } else {
4240 mEventThread->onScreenAcquired();
4241 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004242 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004243 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004244
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004245 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004246 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004247 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004248
4249 struct sched_param param = {0};
4250 param.sched_priority = 1;
4251 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4252 ALOGW("Couldn't set SCHED_FIFO on display on");
4253 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004254 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004255 // Turn off the display
4256 struct sched_param param = {0};
4257 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4258 ALOGW("Couldn't set SCHED_OTHER on display off");
4259 }
4260
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004261 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004262 if (mUseScheduler) {
4263 mScheduler->disableHardwareVsync(true);
4264 } else {
4265 disableHardwareVsync(true); // also cancels any in-progress resync
4266 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004267 if (mUseScheduler) {
4268 mScheduler->onScreenReleased(mAppConnectionHandle);
4269 } else {
4270 mEventThread->onScreenReleased();
4271 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004272 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004273
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004275 mVisibleRegionsDirty = true;
4276 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004277 } else if (mode == HWC_POWER_MODE_DOZE ||
4278 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004279 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004282 if (mUseScheduler) {
4283 mScheduler->onScreenAcquired(mAppConnectionHandle);
4284 } else {
4285 mEventThread->onScreenAcquired();
4286 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004287 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004288 }
4289 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4290 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004292 if (mUseScheduler) {
4293 mScheduler->disableHardwareVsync(true);
4294 } else {
4295 disableHardwareVsync(true); // also cancels any in-progress resync
4296 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004297 if (mUseScheduler) {
4298 mScheduler->onScreenReleased(mAppConnectionHandle);
4299 } else {
4300 mEventThread->onScreenReleased();
4301 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004302 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004305 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004306 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004307 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004309 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004310 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004311 }
4312
Dominik Laskowski34157762018-10-31 13:07:19 -07004313 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314}
4315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004317 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 const auto display = getDisplayDevice(displayToken);
4319 if (!display) {
4320 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4321 displayToken.get());
4322 } else if (display->isVirtual()) {
4323 ALOGW("Attempt to set power mode %d for virtual display", mode);
4324 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004325 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004326 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004328}
4329
4330// ---------------------------------------------------------------------------
4331
Lloyd Pique755e3192018-01-31 16:46:15 -08004332status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4333 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004334 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004335
Mathias Agopianbd115332013-04-18 16:41:04 -07004336 IPCThreadState* ipc = IPCThreadState::self();
4337 const int pid = ipc->getCallingPid();
4338 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004339
Mathias Agopianbd115332013-04-18 16:41:04 -07004340 if ((uid != AID_SHELL) &&
4341 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004342 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4343 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004344 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004345 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004346 // (this would indicate SF is stuck, but we want to be able to
4347 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004348 status_t err = mStateLock.timedLock(s2ns(1));
4349 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004350 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351 StringAppendF(&result,
4352 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4353 "(no locks held)\n",
4354 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004355 }
4356
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357 bool dumpAll = true;
4358 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004359 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004360
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004361 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004362 if ((index < numArgs) &&
4363 (args[index] == String16("--list"))) {
4364 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004366 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004367 }
4368
4369 if ((index < numArgs) &&
4370 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004371 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004372 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004373 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004374 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004375
4376 if ((index < numArgs) &&
4377 (args[index] == String16("--latency-clear"))) {
4378 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004379 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004380 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004381 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004382
4383 if ((index < numArgs) &&
4384 (args[index] == String16("--dispsync"))) {
4385 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004386 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004387 dumpAll = false;
4388 }
Dan Stozab90cf072015-03-05 11:05:59 -08004389
4390 if ((index < numArgs) &&
4391 (args[index] == String16("--static-screen"))) {
4392 index++;
4393 dumpStaticScreenStats(result);
4394 dumpAll = false;
4395 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004396
4397 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004398 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004399 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004400 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004401 dumpAll = false;
4402 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004403
4404 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4405 index++;
4406 dumpWideColorInfo(result);
4407 dumpAll = false;
4408 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409
4410 if ((index < numArgs) &&
4411 (args[index] == String16("--enable-layer-stats"))) {
4412 index++;
4413 mLayerStats.enable();
4414 dumpAll = false;
4415 }
4416
4417 if ((index < numArgs) &&
4418 (args[index] == String16("--disable-layer-stats"))) {
4419 index++;
4420 mLayerStats.disable();
4421 dumpAll = false;
4422 }
4423
4424 if ((index < numArgs) &&
4425 (args[index] == String16("--clear-layer-stats"))) {
4426 index++;
4427 mLayerStats.clear();
4428 dumpAll = false;
4429 }
4430
4431 if ((index < numArgs) &&
4432 (args[index] == String16("--dump-layer-stats"))) {
4433 index++;
4434 mLayerStats.dump(result);
4435 dumpAll = false;
4436 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004437
4438 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004439 (args[index] == String16("--frame-composition"))) {
4440 index++;
4441 dumpFrameCompositionInfo(result);
4442 dumpAll = false;
4443 }
4444
4445 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004446 (args[index] == String16("--display-identification"))) {
4447 index++;
4448 dumpDisplayIdentificationData(result);
4449 dumpAll = false;
4450 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004451
4452 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4453 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004454 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004455 dumpAll = false;
4456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004458
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004460 if (asProto) {
4461 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4462 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4463 } else {
4464 dumpAllLocked(args, index, result);
4465 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004466 }
4467
Mathias Agopian9795c422009-08-26 16:36:26 -07004468 if (locked) {
4469 mStateLock.unlock();
4470 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 return NO_ERROR;
4474}
4475
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4477 std::string& result) const {
4478 mCurrentState.traverseInZOrder(
4479 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004480}
4481
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004482void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004483 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484 String8 name;
4485 if (index < args.size()) {
4486 name = String8(args[index]);
4487 index++;
4488 }
4489
Dominik Laskowski83b88212018-12-11 13:34:06 -08004490 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004491
4492 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004493 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004494 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004495 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004496 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004497 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004498 }
Robert Carr2047fae2016-11-28 14:09:09 -08004499 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500 }
4501}
4502
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004503void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004505 String8 name;
4506 if (index < args.size()) {
4507 name = String8(args[index]);
4508 index++;
4509 }
4510
Robert Carr2047fae2016-11-28 14:09:09 -08004511 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004512 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004513 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004514 }
Robert Carr2047fae2016-11-28 14:09:09 -08004515 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004516
Svetoslavd85084b2014-03-20 10:28:31 -07004517 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004518}
4519
Jamie Gennis6547ff42013-07-16 20:12:42 -07004520// This should only be called from the main thread. Otherwise it would need
4521// the lock and should use mCurrentState rather than mDrawingState.
4522void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004523 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004524 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004525 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004526
4527 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4528}
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004531 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004532
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004533 if (isLayerTripleBufferingDisabled())
4534 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4537 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4538 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4539 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4540 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4541 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004542 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004543}
4544
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4546 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004547 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4548 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004549 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004550 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004552 }
David Sodman4a36e932017-11-07 14:29:47 -08004553 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004554 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004555 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4557 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004558}
4559
Dan Stozae77c7662016-05-13 11:37:28 -07004560void SurfaceFlinger::recordBufferingStats(const char* layerName,
4561 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004562 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4563 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004564 for (const auto& segment : history) {
4565 if (!segment.usedThirdBuffer) {
4566 stats.twoBufferTime += segment.totalTime;
4567 }
4568 if (segment.occupancyAverage < 1.0f) {
4569 stats.doubleBufferedTime += segment.totalTime;
4570 } else if (segment.occupancyAverage < 2.0f) {
4571 stats.tripleBufferedTime += segment.totalTime;
4572 }
4573 ++stats.numSegments;
4574 stats.totalTime += segment.totalTime;
4575 }
4576}
4577
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4579 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004580
4581 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4582 const size_t count = currentLayers.size();
4583 for (size_t i=0 ; i<count ; i++) {
4584 currentLayers[i]->dumpFrameEvents(result);
4585 }
4586}
4587
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004589 result.append("Buffering stats:\n");
4590 result.append(" [Layer name] <Active time> <Two buffer> "
4591 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004592 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004593 typedef std::tuple<std::string, float, float, float> BufferTuple;
4594 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004595 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004596 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004597 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004598 if (stats.numSegments == 0) {
4599 continue;
4600 }
4601 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4602 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4603 stats.totalTime;
4604 float doubleBufferRatio = static_cast<float>(
4605 stats.doubleBufferedTime) / stats.totalTime;
4606 float tripleBufferRatio = static_cast<float>(
4607 stats.tripleBufferedTime) / stats.totalTime;
4608 sorted.insert({activeTime, {name, twoBufferRatio,
4609 doubleBufferRatio, tripleBufferRatio}});
4610 }
4611 for (const auto& sortedPair : sorted) {
4612 float activeTime = sortedPair.first;
4613 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4615 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004616 }
4617 result.append("\n");
4618}
4619
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004621 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004622 const auto displayId = display->getId();
4623 if (!displayId) {
4624 continue;
4625 }
4626 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004627 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628 continue;
4629 }
4630
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result,
4632 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4633 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004634 uint8_t port;
4635 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004636 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004637 result.append("no identification data\n");
4638 continue;
4639 }
4640
4641 if (!isEdid(data)) {
4642 result.append("unknown identification data: ");
4643 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004645 }
4646 result.append("\n");
4647 continue;
4648 }
4649
4650 const auto edid = parseEdid(data);
4651 if (!edid) {
4652 result.append("invalid EDID: ");
4653 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004655 }
4656 result.append("\n");
4657 continue;
4658 }
4659
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004661 result.append(edid->displayName.data(), edid->displayName.length());
4662 result.append("\"\n");
4663 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004664}
4665
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4667 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4668 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4669 StringAppendF(&result, "DisplayColorSetting: %s\n",
4670 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004671
4672 // TODO: print out if wide-color mode is active or not
4673
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004674 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004675 const auto displayId = display->getId();
4676 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 continue;
4678 }
4679
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004681 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004682 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 }
4685
Lloyd Pique32cbe282018-10-19 13:09:22 -07004686 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687 StringAppendF(&result, " Current color mode: %s (%d)\n",
4688 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004689 }
4690 result.append("\n");
4691}
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004694 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004695 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4696 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004697 continue;
4698 }
4699
Dominik Laskowski05275f12018-11-01 15:03:24 -07004700 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4702 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004703 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 compositionInfo.dump(result, nullptr);
4705 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004706 }
4707 }
David Sodman7e4ae112018-02-09 15:02:28 -08004708}
4709
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004710LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004711 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004712 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4713 const State& state = useDrawing ? mDrawingState : mCurrentState;
4714 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004715 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004716 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004717 });
4718
4719 return layersProto;
4720}
4721
Lloyd Pique32cbe282018-10-19 13:09:22 -07004722LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004723 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004724
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004725 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004726 resolution->set_w(displayDevice.getWidth());
4727 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004728
Lloyd Pique32cbe282018-10-19 13:09:22 -07004729 auto display = displayDevice.getCompositionDisplay();
4730 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004731
Lloyd Pique32cbe282018-10-19 13:09:22 -07004732 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4733 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4734 layersProto.set_global_transform(displayState.orientation);
4735
4736 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004737 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004738 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004739 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004740 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004741 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004742 }
4743 });
4744
4745 return layersProto;
4746}
4747
Mathias Agopian74d211a2013-04-22 16:55:35 +02004748void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 bool colorize = false;
4751 if (index < args.size()
4752 && (args[index] == String16("--color"))) {
4753 colorize = true;
4754 index++;
4755 }
4756
4757 Colorizer colorizer(colorize);
4758
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759 // figure out if we're stuck somewhere
4760 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4763
4764 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004765 * Dump library configuration.
4766 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767
4768 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004769 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004771 appendSfConfigString(result);
4772 appendUiConfigString(result);
4773 appendGuiConfigString(result);
4774 result.append("\n");
4775
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004776 result.append("\nDisplay identification data:\n");
4777 dumpDisplayIdentificationData(result);
4778
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004779 result.append("\nWide-Color information:\n");
4780 dumpWideColorInfo(result);
4781
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004782 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004783 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004784 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004785 result.append(SyncFeatures::getInstance().toString());
4786 result.append("\n");
4787
Andy McFadden41d67d72014-04-25 16:58:34 -07004788 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004789 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004790 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004791
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004792 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4793 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004794 StringAppendF(&result,
4795 "app phase %" PRId64 " ns, "
4796 "sf phase %" PRId64 " ns, "
4797 "early app phase %" PRId64 " ns, "
4798 "early sf phase %" PRId64 " ns, "
4799 "early app gl phase %" PRId64 " ns, "
4800 "early sf gl phase %" PRId64 " ns, "
4801 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4802 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4803 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004804
Dan Stozab90cf072015-03-05 11:05:59 -08004805 // Dump static screen stats
4806 result.append("\n");
4807 dumpStaticScreenStats(result);
4808 result.append("\n");
4809
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004811
Dan Stozae77c7662016-05-13 11:37:28 -07004812 dumpBufferingStats(result);
4813
Andy McFadden4803b742012-09-24 19:07:20 -07004814 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004815 * Dump the visible layer list
4816 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4819 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4820 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004821 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004822
Chia-I Wu2f884132018-09-13 15:17:58 -07004823 {
4824 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4825 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004826 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004827 result.append("\n");
4828 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004829
David Sodman7e4ae112018-02-09 15:02:28 -08004830 result.append("\nFrame-Composition information:\n");
4831 dumpFrameCompositionInfo(result);
4832 result.append("\n");
4833
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004834 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004835 * Dump Display state
4836 */
4837
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004838 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004839 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004840 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004841 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004842 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004843 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004844 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004845
4846 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847 * Dump SurfaceFlinger global state
4848 */
4849
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004850 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004851 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004852 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004854 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004855
Dominik Laskowski075d3172018-05-24 15:50:06 -07004856 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004857 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4858 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004859 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4860 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004861 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004862 StringAppendF(&result,
4863 " transaction-flags : %08x\n"
4864 " gpu_to_cpu_unsupported : %d\n",
4865 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004866
Dominik Laskowski075d3172018-05-24 15:50:06 -07004867 if (const auto displayId = getInternalDisplayId();
4868 displayId && getHwComposer().isConnected(*displayId)) {
4869 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004870 StringAppendF(&result,
4871 " refresh-rate : %f fps\n"
4872 " x-dpi : %f\n"
4873 " y-dpi : %f\n",
4874 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4875 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004876 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004877
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
Yiwei Zhang5434a782018-12-05 18:06:32 -08004880 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004881 /*
4882 * VSYNC state
4883 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004884 if (mUseScheduler) {
4885 mScheduler->dump(mAppConnectionHandle, result);
4886 } else {
4887 mEventThread->dump(result);
4888 }
Dan Stozae22aec72016-08-01 13:20:59 -07004889 result.append("\n");
4890
4891 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004892 * Tracing state
4893 */
4894 mTracing.dump(result);
4895 result.append("\n");
4896
4897 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004898 * HWC layer minidump
4899 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004900 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004901 const auto displayId = display->getId();
4902 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004903 continue;
4904 }
4905
Yiwei Zhang5434a782018-12-05 18:06:32 -08004906 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004907 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004908 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004909 result.append("\n");
4910 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911
4912 /*
4913 * Dump HWComposer state
4914 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004915 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004916 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004917 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004918 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004919 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004920 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004921
4922 /*
4923 * Dump gralloc state
4924 */
4925 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4926 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004927
4928 /*
4929 * Dump VrFlinger state if in use.
4930 */
4931 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4932 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004933 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004934 result.append("\n");
4935 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004936}
4937
Dominik Laskowski075d3172018-05-24 15:50:06 -07004938const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004939 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004940 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004941 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004942 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004943 }
4944 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004945
Dominik Laskowski34157762018-10-31 13:07:19 -07004946 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004947 static const Vector<sp<Layer>> empty;
4948 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004949}
4950
Keun young Park63f165f2012-08-31 10:53:36 -07004951bool SurfaceFlinger::startDdmConnection()
4952{
4953 void* libddmconnection_dso =
4954 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4955 if (!libddmconnection_dso) {
4956 return false;
4957 }
4958 void (*DdmConnection_start)(const char* name);
4959 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004960 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004961 if (!DdmConnection_start) {
4962 dlclose(libddmconnection_dso);
4963 return false;
4964 }
4965 (*DdmConnection_start)(getServiceName());
4966 return true;
4967}
4968
Chia-I Wu28f320b2018-05-03 11:02:56 -07004969void SurfaceFlinger::updateColorMatrixLocked() {
4970 mat4 colorMatrix;
4971 if (mGlobalSaturationFactor != 1.0f) {
4972 // Rec.709 luma coefficients
4973 float3 luminance{0.213f, 0.715f, 0.072f};
4974 luminance *= 1.0f - mGlobalSaturationFactor;
4975 mat4 saturationMatrix = mat4(
4976 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4977 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4978 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4979 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4980 );
4981 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4982 } else {
4983 colorMatrix = mClientColorMatrix * mDaltonizer();
4984 }
4985
4986 if (mCurrentState.colorMatrix != colorMatrix) {
4987 mCurrentState.colorMatrix = colorMatrix;
4988 mCurrentState.colorMatrixChanged = true;
4989 setTransactionFlags(eTransactionNeeded);
4990 }
4991}
4992
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004993status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994#pragma clang diagnostic push
4995#pragma clang diagnostic error "-Wswitch-enum"
4996 switch (static_cast<ISurfaceComposerTag>(code)) {
4997 // These methods should at minimum make sure that the client requested
4998 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004999 case BOOT_FINISHED:
5000 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 case CREATE_DISPLAY:
5002 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005003 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 case GET_ACTIVE_COLOR_MODE:
5005 case GET_ANIMATION_FRAME_STATS:
5006 case GET_HDR_CAPABILITIES:
5007 case SET_ACTIVE_CONFIG:
5008 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005009 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005010 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005011 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005012 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5013 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005014 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5015 IPCThreadState* ipc = IPCThreadState::self();
5016 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5017 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005018 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 }
Robert Carr1db73f62016-12-21 12:58:51 -08005020 return OK;
5021 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005023 IPCThreadState* ipc = IPCThreadState::self();
5024 const int pid = ipc->getCallingPid();
5025 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005026 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5027 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005028 return PERMISSION_DENIED;
5029 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005032 // Used by apps to hook Choreographer to SurfaceFlinger.
5033 case CREATE_DISPLAY_EVENT_CONNECTION:
5034 // The following calls are currently used by clients that do not
5035 // request necessary permissions. However, they do not expose any secret
5036 // information, so it is OK to pass them.
5037 case AUTHENTICATE_SURFACE:
5038 case GET_ACTIVE_CONFIG:
5039 case GET_BUILT_IN_DISPLAY:
5040 case GET_DISPLAY_COLOR_MODES:
5041 case GET_DISPLAY_CONFIGS:
5042 case GET_DISPLAY_STATS:
5043 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5044 // Calling setTransactionState is safe, because you need to have been
5045 // granted a reference to Client* and Handle* to do anything with it.
5046 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005047 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005048 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005049 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005050 case GET_PROTECTED_CONTENT_SUPPORT:
5051 case CACHE_BUFFER:
5052 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005053 return OK;
5054 }
5055 case CAPTURE_LAYERS:
5056 case CAPTURE_SCREEN: {
5057 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005058 IPCThreadState* ipc = IPCThreadState::self();
5059 const int pid = ipc->getCallingPid();
5060 const int uid = ipc->getCallingUid();
5061 if ((uid != AID_GRAPHICS) &&
5062 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5063 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5064 return PERMISSION_DENIED;
5065 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005066 return OK;
5067 }
5068 // The following codes are deprecated and should never be allowed to access SF.
5069 case CONNECT_DISPLAY_UNUSED:
5070 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5071 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5072 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005073 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005074 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005075
5076 // These codes are used for the IBinder protocol to either interrogate the recipient
5077 // side of the transaction for its canonical interface descriptor or to dump its state.
5078 // We let them pass by default.
5079 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5080 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5081 code == IBinder::SYSPROPS_TRANSACTION) {
5082 return OK;
5083 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005084 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005086 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005087 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5088 return OK;
5089 }
5090 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5091 return PERMISSION_DENIED;
5092#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005093}
5094
Ana Krulec13be8ad2018-08-21 02:43:56 +00005095status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5096 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005097 status_t credentialCheck = CheckTransactCodeCredentials(code);
5098 if (credentialCheck != OK) {
5099 return credentialCheck;
5100 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5103 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005104 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005105 IPCThreadState* ipc = IPCThreadState::self();
5106 const int uid = ipc->getCallingUid();
5107 if (CC_UNLIKELY(uid != AID_SYSTEM
5108 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005109 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005110 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005111 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005112 return PERMISSION_DENIED;
5113 }
5114 int n;
5115 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005116 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005117 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118 return NO_ERROR;
5119 case 1002: // SHOW_UPDATES
5120 n = data.readInt32();
5121 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005122 invalidateHwcGeometry();
5123 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005126 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005127 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005128 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005129 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005130 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005131 setTransactionFlags(
5132 eTransactionNeeded|
5133 eDisplayTransactionNeeded|
5134 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005135 return NO_ERROR;
5136 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005137 case 1006:{ // send empty update
5138 signalRefresh();
5139 return NO_ERROR;
5140 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005141 case 1008: // toggle use of hw composer
5142 n = data.readInt32();
5143 mDebugDisableHWC = n ? 1 : 0;
5144 invalidateHwcGeometry();
5145 repaintEverything();
5146 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005147 case 1009: // toggle use of transform hint
5148 n = data.readInt32();
5149 mDebugDisableTransformHint = n ? 1 : 0;
5150 invalidateHwcGeometry();
5151 repaintEverything();
5152 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005153 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005154 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005155 reply->writeInt32(0);
5156 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005157 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005158 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005159 return NO_ERROR;
5160 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005161 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005162 if (!display) {
5163 return NAME_NOT_FOUND;
5164 }
5165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005166 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005167 return NO_ERROR;
5168 }
5169 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005170 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005171 // daltonize
5172 n = data.readInt32();
5173 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005174 case 1:
5175 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5176 break;
5177 case 2:
5178 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5179 break;
5180 case 3:
5181 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5182 break;
5183 default:
5184 mDaltonizer.setType(ColorBlindnessType::None);
5185 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005186 }
5187 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005188 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005189 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005190 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005191 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005192
5193 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005194 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005195 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005196 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005197 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005198 // apply a color matrix
5199 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005200 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005201 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005202 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005203 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005204 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005205 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005206 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005207 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005208 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005209 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005210
5211 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5212 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005213 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005214 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5215 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5216 }
5217
Chia-I Wu28f320b2018-05-03 11:02:56 -07005218 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005219 return NO_ERROR;
5220 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005221 // This is an experimental interface
5222 // Needs to be shifted to proper binder interface when we productize
5223 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005224 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005225 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005226 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005227 return NO_ERROR;
5228 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005229 case 1017: {
5230 n = data.readInt32();
5231 mForceFullDamage = static_cast<bool>(n);
5232 return NO_ERROR;
5233 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005234 case 1018: { // Modify Choreographer's phase offset
5235 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005236 if (mUseScheduler) {
5237 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5238 } else {
5239 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5240 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005241 return NO_ERROR;
5242 }
5243 case 1019: { // Modify SurfaceFlinger's phase offset
5244 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005245 if (mUseScheduler) {
5246 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5247 } else {
5248 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5249 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005250 return NO_ERROR;
5251 }
Irvel468051e2016-06-13 16:44:44 -07005252 case 1020: { // Layer updates interceptor
5253 n = data.readInt32();
5254 if (n) {
5255 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005256 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005257 }
5258 else{
5259 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005260 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005261 }
5262 return NO_ERROR;
5263 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005264 case 1021: { // Disable HWC virtual displays
5265 n = data.readInt32();
5266 mUseHwcVirtualDisplays = !n;
5267 return NO_ERROR;
5268 }
Romain Guy0147a172017-06-01 13:53:56 -07005269 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005270 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005271 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005272
Chia-I Wu28f320b2018-05-03 11:02:56 -07005273 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005274 return NO_ERROR;
5275 }
Romain Guy54f154a2017-10-24 21:40:32 +01005276 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005277 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005278 invalidateHwcGeometry();
5279 repaintEverything();
5280 return NO_ERROR;
5281 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005282 // Deprecate, use 1030 to check whether the device is color managed.
5283 case 1024: {
5284 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005285 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005286 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005287 n = data.readInt32();
5288 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005289 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005290 mTracing.enable();
5291 doTracing("tracing.enable");
5292 reply->writeInt32(NO_ERROR);
5293 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005294 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005295 status_t err = mTracing.disable();
5296 reply->writeInt32(err);
5297 }
5298 return NO_ERROR;
5299 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005300 case 1026: { // Get layer tracing status
5301 reply->writeBool(mTracing.isEnabled());
5302 return NO_ERROR;
5303 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005304 // Is a DisplayColorSetting supported?
5305 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005306 const auto display = getDefaultDisplayDevice();
5307 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005308 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005309 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005310
5311 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5312 switch (setting) {
5313 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005314 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005315 break;
5316 case DisplayColorSetting::UNMANAGED:
5317 reply->writeBool(true);
5318 break;
5319 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005320 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005321 break;
5322 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005323 reply->writeBool(
5324 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005325 break;
5326 }
5327 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005328 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005329 // Is VrFlinger active?
5330 case 1028: {
5331 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005332 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005333 return NO_ERROR;
5334 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005335 // Is device color managed?
5336 case 1030: {
5337 reply->writeBool(useColorManagement);
5338 return NO_ERROR;
5339 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005340 // Override default composition data space
5341 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5342 // && adb shell stop zygote && adb shell start zygote
5343 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5344 // adb shell stop zygote && adb shell start zygote
5345 case 1031: {
5346 Mutex::Autolock _l(mStateLock);
5347 n = data.readInt32();
5348 if (n) {
5349 n = data.readInt32();
5350 if (n) {
5351 Dataspace dataspace = static_cast<Dataspace>(n);
5352 if (!validateCompositionDataspace(dataspace)) {
5353 return BAD_VALUE;
5354 }
5355 mDefaultCompositionDataspace = dataspace;
5356 }
5357 n = data.readInt32();
5358 if (n) {
5359 Dataspace dataspace = static_cast<Dataspace>(n);
5360 if (!validateCompositionDataspace(dataspace)) {
5361 return BAD_VALUE;
5362 }
5363 mWideColorGamutCompositionDataspace = dataspace;
5364 }
5365 } else {
5366 // restore composition data space.
5367 mDefaultCompositionDataspace = defaultCompositionDataspace;
5368 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5369 }
5370 return NO_ERROR;
5371 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005372 }
5373 }
5374 return err;
5375}
5376
Steven Thomas6d8110b2017-08-31 18:24:21 -07005377void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005378 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005379 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005380}
5381
Ana Krulec7d1d6832018-12-27 11:10:09 -08005382void SurfaceFlinger::repaintEverythingForHWC() {
5383 mRepaintEverything = true;
5384 mEventQueue->invalidateForHWC();
5385}
5386
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005387// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5388class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005389public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005390 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5391 ~WindowDisconnector() {
5392 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005393 }
5394
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395private:
5396 ANativeWindow* mWindow;
5397 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005398};
5399
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005400status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005401 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5402 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005403 uint32_t reqWidth, uint32_t reqHeight,
5404 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005405 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005408 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005409
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005410 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5411
Chia-I Wu20261cb2018-08-23 12:55:44 -07005412 sp<DisplayDevice> display;
5413 {
5414 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005415
Chia-I Wu20261cb2018-08-23 12:55:44 -07005416 display = getDisplayDeviceLocked(displayToken);
5417 if (!display) return BAD_VALUE;
5418
Chia-I Wucb023152018-08-28 12:57:23 -07005419 // set the requested width/height to the logical display viewport size
5420 // by default
5421 if (reqWidth == 0 || reqHeight == 0) {
5422 reqWidth = uint32_t(display->getViewport().width());
5423 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005424 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005425 }
5426
Peiyong Lin0e003c92018-09-17 11:09:51 -07005427 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5428 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005429
5430 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005431 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005432 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5433 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005434}
5435
5436status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005437 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5438 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005439 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005440 ATRACE_CALL();
5441
5442 class LayerRenderArea : public RenderArea {
5443 public:
Robert Carr578038f2018-03-09 12:25:24 -08005444 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005445 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5446 bool childrenOnly)
5447 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005448 mLayer(layer),
5449 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005450 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005451 mFlinger(flinger),
5452 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005453 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005454 Rect getBounds() const override {
5455 const Layer::State& layerState(mLayer->getDrawingState());
5456 return mLayer->getBufferSize(layerState);
5457 }
Marissa Wall61c58622018-07-18 10:12:20 -07005458 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005459 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005460 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005461 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005462 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005463 }
chaviwa76b2712017-09-20 12:02:26 -07005464 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005465 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005466 Rect getSourceCrop() const override {
5467 if (mCrop.isEmpty()) {
5468 return getBounds();
5469 } else {
5470 return mCrop;
5471 }
5472 }
Robert Carr578038f2018-03-09 12:25:24 -08005473 class ReparentForDrawing {
5474 public:
5475 const sp<Layer>& oldParent;
5476 const sp<Layer>& newParent;
5477
5478 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5479 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005480 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005481 }
Robert Carr15eae092018-03-23 13:43:53 -07005482 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005483 };
5484
5485 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005486 const Rect sourceCrop = getSourceCrop();
5487 // no need to check rotation because there is none
5488 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5489 sourceCrop.height() != getReqHeight();
5490
Robert Carr578038f2018-03-09 12:25:24 -08005491 if (!mChildrenOnly) {
5492 mTransform = mLayer->getTransform().inverse();
5493 drawLayers();
5494 } else {
5495 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005496 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005497 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5498 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005499
5500 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5501 drawLayers();
5502 }
5503 }
chaviwa76b2712017-09-20 12:02:26 -07005504
chaviwa76b2712017-09-20 12:02:26 -07005505 private:
chaviw7206d492017-11-10 16:16:12 -08005506 const sp<Layer> mLayer;
5507 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005508
5509 // In the "childrenOnly" case we reparent the children to a screenshot
5510 // layer which has no properties set and which does not draw.
5511 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005512 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005513 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005514
5515 SurfaceFlinger* mFlinger;
5516 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005517 };
5518
5519 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5520 auto parent = layerHandle->owner.promote();
5521
Robert Carr2e102c92018-10-23 12:11:15 -07005522 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005523 ALOGE("captureLayers called with a removed parent");
5524 return NAME_NOT_FOUND;
5525 }
5526
Robert Carr578038f2018-03-09 12:25:24 -08005527 const int uid = IPCThreadState::self()->getCallingUid();
5528 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005529 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005530 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5531 return PERMISSION_DENIED;
5532 }
5533
chaviw7206d492017-11-10 16:16:12 -08005534 Rect crop(sourceCrop);
5535 if (sourceCrop.width() <= 0) {
5536 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005537 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005538 }
5539
5540 if (sourceCrop.height() <= 0) {
5541 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005542 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005543 }
5544
5545 int32_t reqWidth = crop.width() * frameScale;
5546 int32_t reqHeight = crop.height() * frameScale;
5547
Chia-I Wu20261cb2018-08-23 12:55:44 -07005548 // really small crop or frameScale
5549 if (reqWidth <= 0) {
5550 reqWidth = 1;
5551 }
5552 if (reqHeight <= 0) {
5553 reqHeight = 1;
5554 }
5555
Peiyong Lin0e003c92018-09-17 11:09:51 -07005556 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005557
Robert Carr578038f2018-03-09 12:25:24 -08005558 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005559 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5560 if (!layer->isVisible()) {
5561 return;
Robert Carr578038f2018-03-09 12:25:24 -08005562 } else if (childrenOnly && layer == parent.get()) {
5563 return;
chaviwa76b2712017-09-20 12:02:26 -07005564 }
5565 visitor(layer);
5566 });
5567 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005568 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005569}
5570
5571status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5572 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005573 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005574 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005575 bool useIdentityTransform) {
5576 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005577
Peiyong Lin0e003c92018-09-17 11:09:51 -07005578 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005579 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5580 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005581 *outBuffer =
5582 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5583 static_cast<android_pixel_format>(reqPixelFormat), 1,
5584 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005585
5586 // This mutex protects syncFd and captureResult for communication of the return values from the
5587 // main thread back to this Binder thread
5588 std::mutex captureMutex;
5589 std::condition_variable captureCondition;
5590 std::unique_lock<std::mutex> captureLock(captureMutex);
5591 int syncFd = -1;
5592 std::optional<status_t> captureResult;
5593
Robert Carr03480e22018-01-04 16:02:06 -08005594 const int uid = IPCThreadState::self()->getCallingUid();
5595 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5596
Dominik Laskowski8c001672018-05-30 16:52:06 -07005597 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598 // If there is a refresh pending, bug out early and tell the binder thread to try again
5599 // after the refresh.
5600 if (mRefreshPending) {
5601 ATRACE_NAME("Skipping screenshot for now");
5602 std::unique_lock<std::mutex> captureLock(captureMutex);
5603 captureResult = std::make_optional<status_t>(EAGAIN);
5604 captureCondition.notify_one();
5605 return;
5606 }
5607
5608 status_t result = NO_ERROR;
5609 int fd = -1;
5610 {
5611 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005612 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005613 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5614 useIdentityTransform, forSystem, &fd);
5615 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005616 }
5617
5618 {
5619 std::unique_lock<std::mutex> captureLock(captureMutex);
5620 syncFd = fd;
5621 captureResult = std::make_optional<status_t>(result);
5622 captureCondition.notify_one();
5623 }
5624 });
5625
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005626 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005627 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005628 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 while (*captureResult == EAGAIN) {
5630 captureResult.reset();
5631 result = postMessageAsync(message);
5632 if (result != NO_ERROR) {
5633 return result;
5634 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005635 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636 }
5637 result = *captureResult;
5638 }
5639
5640 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005641 sync_wait(syncFd, -1);
5642 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005645 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005646}
5647
chaviwa76b2712017-09-20 12:02:26 -07005648void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005649 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005650 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005652
Lloyd Pique144e1162017-12-20 16:44:52 -08005653 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005654
chaviwa76b2712017-09-20 12:02:26 -07005655 const auto reqWidth = renderArea.getReqWidth();
5656 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005657 const auto sourceCrop = renderArea.getSourceCrop();
5658 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005659
Peiyong Lin0e003c92018-09-17 11:09:51 -07005660 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005661 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005662
Mathias Agopian180f10d2013-04-10 22:55:41 -07005663 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005664 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005665
5666 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005667 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005668 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005669
chaviw50da5042018-04-09 13:49:37 -07005670 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005671 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005672 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005673
chaviwa76b2712017-09-20 12:02:26 -07005674 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005675 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005676 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005677 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005678 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005679}
5680
chaviwa76b2712017-09-20 12:02:26 -07005681status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5682 TraverseLayersFunction traverseLayers,
5683 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005684 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005685 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005686 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005687 ATRACE_CALL();
5688
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005689 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005690
5691 traverseLayers([&](Layer* layer) {
5692 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5693 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005694
Robert Carr03480e22018-01-04 16:02:06 -08005695 // We allow the system server to take screenshots of secure layers for
5696 // use in situations like the Screen-rotation animation and place
5697 // the impetus on WindowManager to not persist them.
5698 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005699 ALOGW("FB is protected: PERMISSION_DENIED");
5700 return PERMISSION_DENIED;
5701 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005702 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005703
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005704 // this binds the given EGLImage as a framebuffer for the
5705 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005706 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005707 if (bufferBond.getStatus() != NO_ERROR) {
5708 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005709 return INVALID_OPERATION;
5710 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005711
Dan Stozaabcda352017-06-01 14:37:39 -07005712 // this will in fact render into our dequeued buffer
5713 // via an FBO, which means we didn't have to create
5714 // an EGLSurface and therefore we're not
5715 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005716 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005717
Peiyong Linfb530cf2018-12-15 05:07:38 +00005718 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005719 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005720 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005721 }
Alec Mouri492bc572018-09-11 21:40:04 +00005722 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005723
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005724 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005725}
5726
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005727// ---------------------------------------------------------------------------
5728
Dan Stoza412903f2017-04-27 13:42:17 -07005729void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5730 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005731}
5732
Dan Stoza412903f2017-04-27 13:42:17 -07005733void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5734 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005735}
5736
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005737void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005738 const LayerVector::Visitor& visitor) {
5739 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005740 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005741 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005742 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005743 continue;
5744 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005745 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005746 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005747 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005748 return;
5749 }
chaviwa76b2712017-09-20 12:02:26 -07005750 if (!layer->isVisible()) {
5751 return;
5752 }
5753 visitor(layer);
5754 });
5755 }
5756}
5757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005758}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005759
Lloyd Pique074e8122018-07-26 12:57:23 -07005760
Mathias Agopian3f844832013-08-07 21:24:32 -07005761#if defined(__gl_h_)
5762#error "don't include gl/gl.h in this file"
5763#endif
5764
5765#if defined(__gl2_h_)
5766#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005767#endif