blob: 08a9eebafd921056075d5473bf65924651312a8d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700160ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
161 switch (rotation) {
162 case ISurfaceComposer::eRotateNone:
163 return ui::Transform::ROT_0;
164 case ISurfaceComposer::eRotate90:
165 return ui::Transform::ROT_90;
166 case ISurfaceComposer::eRotate180:
167 return ui::Transform::ROT_180;
168 case ISurfaceComposer::eRotate270:
169 return ui::Transform::ROT_270;
170 }
171 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
172 return ui::Transform::ROT_0;
173}
174
Peiyong Linfca547f2018-07-09 13:03:33 -0700175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Peiyong Lin9d846a52018-11-05 13:18:20 -0800190// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
191bool validateCompositionDataspace(Dataspace dataspace) {
192 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
193}
194
Steven Thomasb02664d2017-07-26 18:48:28 -0700195} // namespace anonymous
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Mathias Agopian99b49842011-06-27 16:05:52 -0700199const String16 sHardwareTest("android.permission.HARDWARE_TEST");
200const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
201const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
202const String16 sDump("android.permission.DUMP");
203
204// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700205int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700206bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800207uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800208bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800209bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800210int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600211bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700212int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700213bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700214bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700215Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
216ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
217Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
218ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700219
Kalle Raitaa099a242017-01-11 11:17:29 -0800220std::string getHwcServiceName() {
221 char value[PROPERTY_VALUE_MAX] = {};
222 property_get("debug.sf.hwc_service_name", value, "default");
223 ALOGI("Using HWComposer service: '%s'", value);
224 return std::string(value);
225}
226
227bool useTrebleTestingOverride() {
228 char value[PROPERTY_VALUE_MAX] = {};
229 property_get("debug.sf.treble_testing_override", value, "false");
230 ALOGI("Treble testing override: '%s'", value);
231 return std::string(value) == "true";
232}
233
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
235 switch(displayColorSetting) {
236 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700237 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700239 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700241 return std::string("Enhanced");
242 default:
243 return std::string("Unknown ") +
244 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246}
247
David Sodmanbc815282017-11-05 18:57:52 -0800248SurfaceFlingerBE::SurfaceFlingerBE()
249 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800250 mFrameBuckets(),
251 mTotalTime(0),
252 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800253 mComposerSequenceId(0) {
254}
255
Lloyd Pique90c115d2018-09-18 21:39:42 -0700256SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
257 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800258 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700259 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700260 mTransactionPending(false),
261 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700262 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700263 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800265 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800267 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800268 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800269 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700271 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700272 mDebugDisableTransformHint(0),
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800273 mDebugEnableProtectedContent(false),
Mathias Agopian9795c422009-08-26 16:36:26 -0700274 mDebugInTransaction(0),
275 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700276 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800277 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800278 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800279 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800280 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700281 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700282 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800283 mCompositionEngine{getFactory().createCompositionEngine()} {
284 mSetInputWindowsListener = new SetInputWindowsListener(this);
285}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800286
Lloyd Pique90c115d2018-09-18 21:39:42 -0700287SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
288 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800289 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 mDefaultCompositionDataspace =
309 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
310 mWideColorGamutCompositionDataspace =
311 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
312 defaultCompositionDataspace = mDefaultCompositionDataspace;
313 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
314 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
315 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
316 wideColorGamutCompositionPixelFormat =
317 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
322 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
323 switch (tmpPrimaryDisplayOrientation) {
324 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800338
Sundong Ahn85131bd2019-02-18 15:51:53 +0900339 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // debugging stuff...
342 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700345 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 property_get("debug.sf.showupdates", value, "0");
348 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700350 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000351
352 // DDMS debugging deprecated (b/120782499)
353 property_get("debug.sf.ddms", value, "0");
354 int debugDdms = atoi(value);
355 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800361 property_get("debug.sf.enable_hwc_vds", value, "0");
362 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800363 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800365 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Ana Krulece5a06e02019-03-06 17:09:03 -0800373 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800374 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800375
376 int int_value = atoi(value);
377 if (int_value) {
378 mUseSmart90ForVideo = true;
379 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800380
Dan Stozaec460082018-12-17 15:35:09 -0800381 property_get("debug.sf.luma_sampling", value, "1");
382 mLumaSampling = atoi(value);
383
Ana Krulec757f63a2019-01-25 10:46:18 -0800384 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
385 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700386
Romain Guy11d63f42017-07-20 12:47:14 -0700387 // We should be reading 'persist.sys.sf.color_saturation' here
388 // but since /data may be encrypted, we need to wait until after vold
389 // comes online to attempt to read the property. The property is
390 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800391
392 if (useTrebleTestingOverride()) {
393 // Without the override SurfaceFlinger cannot connect to HIDL
394 // services that are not listed in the manifests. Considered
395 // deriving the setting from the set service name, but it
396 // would be brittle if the name that's not 'default' is used
397 // for production purposes later on.
398 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407SurfaceFlinger::~SurfaceFlinger()
408{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Dan Stozac7014012014-02-14 15:03:43 -0800411void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412{
413 // the window manager died on us. prepare its eulogy.
414
Andy McFadden13a082e2012-08-24 10:16:42 -0700415 // restore initial conditions (default device unblank, etc)
416 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
418 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700419 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Robert Carr1db73f62016-12-21 12:58:51 -0800422static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700423 status_t err = client->initCheck();
424 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 }
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return nullptr;
428}
429
430sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
431 return initClient(new Client(this));
432}
433
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700434sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
435 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436{
437 class DisplayToken : public BBinder {
438 sp<SurfaceFlinger> flinger;
439 virtual ~DisplayToken() {
440 // no more references, this display must be terminated
441 Mutex::Autolock _l(flinger->mStateLock);
442 flinger->mCurrentState.displays.removeItem(this);
443 flinger->setTransactionFlags(eDisplayTransactionNeeded);
444 }
445 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700446 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447 : flinger(flinger) {
448 }
449 };
450
451 sp<BBinder> token = new DisplayToken(this);
452
453 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454 // Display ID is assigned when virtual display is allocated by HWC.
455 DisplayDeviceState state;
456 state.isSecure = secure;
457 state.displayName = displayName;
458 mCurrentState.displays.add(token, state);
459 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 return token;
461}
462
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 Mutex::Autolock _l(mStateLock);
465
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
467 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 return;
470 }
471
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
473 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 ALOGE("destroyDisplay called for non-virtual display");
475 return;
476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 mInterceptor->saveDisplayDeletion(state.sequenceId);
478 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 setTransactionFlags(eDisplayTransactionNeeded);
480}
481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
483 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 const auto internalDisplayId = getInternalDisplayIdLocked();
486 if (!internalDisplayId) {
487 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 }
489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 std::vector<PhysicalDisplayId> displayIds;
491 displayIds.reserve(mPhysicalDisplayTokens.size());
492 displayIds.push_back(internalDisplayId->value);
493
494 for (const auto& [id, token] : mPhysicalDisplayTokens) {
495 if (id != *internalDisplayId) {
496 displayIds.push_back(id.value);
497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 return displayIds;
501}
502
503sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
504 Mutex::Autolock lock(mStateLock);
505 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
Ady Abraham37965d42018-11-01 13:43:32 -0700508status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
509 if (!outGetColorManagement) {
510 return BAD_VALUE;
511 }
512 *outGetColorManagement = useColorManagement;
513 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700514}
515
Lloyd Pique441d5042018-10-18 16:49:51 -0700516HWComposer& SurfaceFlinger::getHwComposer() const {
517 return mCompositionEngine->getHwComposer();
518}
519
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700520renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
521 return mCompositionEngine->getRenderEngine();
522}
523
Lloyd Pique70d91362018-10-18 16:02:55 -0700524compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
525 return *mCompositionEngine.get();
526}
527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528void SurfaceFlinger::bootFinished()
529{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700530 if (mStartPropertySetThread->join() != NO_ERROR) {
531 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533 const nsecs_t now = systemTime();
534 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000535 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536
537 // wait patiently for the window manager death
538 const String16 name("window");
539 sp<IBinder> window(defaultServiceManager()->getService(name));
540 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700541 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700542 }
Robert Carr720e5062018-07-30 17:45:14 -0700543 sp<IBinder> input(defaultServiceManager()->getService(
544 String16("inputflinger")));
545 if (input == nullptr) {
546 ALOGE("Failed to link to input service");
547 } else {
548 mInputFlinger = interface_cast<IInputFlinger>(input);
549 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Ana Krulecbd6654b2019-02-15 15:18:15 -0800564 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567
Ady Abraham97d04232019-03-05 19:48:12 -0800568 // set the refresh rate according to the policy
569 const auto displayId = getInternalDisplayIdLocked();
570 LOG_ALWAYS_FATAL_IF(!displayId);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571
Ady Abraham97d04232019-03-05 19:48:12 -0800572 const auto performanceRefreshRate =
573 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
574
575 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
Ana Krulecbd6654b2019-02-15 15:18:15 -0800576 mPhaseOffsets->setRefreshRateType(
577 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800578 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800579 } else {
580 mPhaseOffsets->setRefreshRateType(
581 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800582 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800583 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
617
Ana Krulec757f63a2019-01-25 10:46:18 -0800618 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800622 mScheduler =
623 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
624 auto resyncCallback =
625 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800626
Ana Krulecc2870422019-01-29 19:00:58 -0800627 mAppConnectionHandle =
628 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
629 resyncCallback,
630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
632 resyncCallback, [this](nsecs_t timestamp) {
633 mInterceptor->saveVSyncEvent(timestamp);
634 });
635
636 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
637 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
638 mSfConnectionHandle.get());
639
Kevin DuBois413287f2019-02-25 08:46:47 -0800640 mRegionSamplingThread =
641 new RegionSamplingThread(*this, *mScheduler,
642 RegionSamplingThread::EnvironmentTimingTunables());
643
Steven Thomasb02664d2017-07-26 18:48:28 -0700644 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700645 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700646 renderEngineFeature |= (useColorManagement ?
647 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700648 renderEngineFeature |= (useContextPriority ?
649 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700650
651 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800652 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700654 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800655 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700656
657 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
658 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700659 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
660 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800661 // Process any initial hotplug and resulting display changes.
662 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 const auto display = getDefaultDisplayDeviceLocked();
664 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700665 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700670 // This callback is called from the vr flinger dispatch thread. We
671 // need to call signalTransaction(), which requires holding
672 // mStateLock when we're not on the main thread. Acquiring
673 // mStateLock from the vr flinger dispatch thread might trigger a
674 // deadlock in surface flinger (see b/66916578), so post a message
675 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
678 mVrFlingerRequestsDisplay = requestDisplay;
679 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
683 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 .value_or(0),
686 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (!mVrFlinger) {
688 ALOGE("Failed to start vrflinger");
689 }
690 }
691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700698 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700699
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701
702 const bool presentFenceReliable =
703 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
704 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705
706 if (mStartPropertySetThread->Start() != NO_ERROR) {
707 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709
Ady Abraham97d04232019-03-05 19:48:12 -0800710 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800711 mScheduler->setChangeRefreshRateCallback(
712 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
713 Mutex::Autolock lock(mStateLock);
714 setRefreshRateTo(type, event);
715 });
Kevin DuBois36233132019-02-19 14:08:55 -0800716 }
Ady Abraham1902d072019-03-01 17:18:59 -0800717 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
718 getHwComposer().getConfigs(*display->getId()));
719 mRefreshRateStats =
720 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
721 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700737 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800738
739 property_get("persist.sys.sf.color_mode", value, "0");
740 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700758 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800796status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
797 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800802 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700803 if (!displayId) {
804 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700805 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 // TODO: Not sure if display density should handled by SF any longer
808 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700811 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800812 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 }
815 return density;
816 }
817 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("ro.sf.lcd_density"); }
822 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 DisplayInfo info = DisplayInfo();
828
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 float xdpi = hwConfig->getDpiX();
830 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
834 // Default display viewport to display width and height
835 info.viewportW = info.w;
836 info.viewportH = info.h;
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 // The density of the device is provided by a build property
840 float density = Density::getBuildDensity() / 160.0f;
841 if (density == 0) {
842 // the build doesn't provide a density -- this is wrong!
843 // use xdpi instead
844 ALOGE("ro.sf.lcd_density must be defined as a build property");
845 density = xdpi / 160.0f;
846 }
847 if (Density::getEmuDensity()) {
848 // if "qemu.sf.lcd_density" is specified, it overrides everything
849 xdpi = ydpi = density = Density::getEmuDensity();
850 density /= 160.0f;
851 }
852 info.density = density;
853
854 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855 const auto display = getDefaultDisplayDeviceLocked();
856 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857
858 // This is for screenrecord
859 const Rect viewport = display->getViewport();
860 if (viewport.isValid()) {
861 info.viewportW = uint32_t(viewport.getWidth());
862 info.viewportH = uint32_t(viewport.getHeight());
863 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 } else {
865 // TODO: where should this value come from?
866 static const int TV_DENSITY = 213;
867 info.density = TV_DENSITY / 160.0f;
868 info.orientation = 0;
869 }
870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 info.xdpi = xdpi;
872 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800874 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875
Andy McFadden91b2ca82014-06-13 14:04:23 -0700876 // This is how far in advance a buffer must be queued for
877 // presentation at a given time. If you want a buffer to appear
878 // on the screen at time N, you must submit the buffer before
879 // (N - presentationDeadline).
880 //
881 // Normally it's one full refresh period (to give SF a chance to
882 // latch the buffer), but this can be reduced by configuring a
883 // DispSync offset. Any additional delays introduced by the hardware
884 // composer or panel must be accounted for here.
885 //
886 // We add an additional 1ms to allow for processing time and
887 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800888 info.presentationDeadline =
889 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700890
891 // All non-virtual displays are currently considered secure.
892 info.secure = true;
893
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800894 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700895 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800896 std::swap(info.w, info.h);
897 }
898
Michael Wright28f24d02016-07-12 13:30:53 -0700899 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulecc2870422019-01-29 19:00:58 -0800910 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return NO_ERROR;
912}
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
915 const auto display = getDisplayDevice(displayToken);
916 if (!display) {
917 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800918 return BAD_VALUE;
919 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Ady Abraham447052e2019-02-13 16:07:27 -0800924void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800925 Scheduler::ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800927
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 // Lock is acquired by setRefreshRateTo.
929 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800930 if (!display) {
931 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
932 displayToken.get());
933 return;
934 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700935 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800936 ALOGW("Attempt to set active config %d for virtual display", mode);
937 return;
938 }
939 int currentDisplayPowerMode = display->getPowerMode();
940 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
941 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700942 return;
943 }
944
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800946 // config twice. However event generation config might have changed so we need to update it
947 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800948 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800949 const Scheduler::ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
Ady Abraham9360a222019-02-27 17:05:30 -0800950 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800951
952 if (!mDesiredActiveConfigChanged) {
953 // This is the first time we set the desired
954 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
955
956 // This will trigger HWC refresh without resetting the idle timer.
957 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800959 mDesiredActiveConfigChanged = true;
960 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800965
966 std::vector<int32_t> allowedConfig;
967 allowedConfig.push_back(mode);
968
969 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970}
971
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972void SurfaceFlinger::setActiveConfigInternal() {
973 ATRACE_CALL();
974
975 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800976 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977
978 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
979 display->setActiveConfig(mUpcomingActiveConfig.configId);
980
Ana Krulecc2870422019-01-29 19:00:58 -0800981 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800982 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800983 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800984 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
985 mUpcomingActiveConfig.configId);
986 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987}
988
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -0800990 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800991 // we may be in the process of changing the active state
992 if (mWaitForNextInvalidate) {
993 mWaitForNextInvalidate = false;
994
995 repaintEverythingForHWC();
996 // We do not want to give another frame to HWC while we are transitioning.
997 return true;
998 }
999
1000 if (mCheckPendingFence) {
1001 if (mPreviousPresentFence != Fence::NO_FENCE &&
1002 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1003 // fence has not signaled yet. wait for the next invalidate
1004 repaintEverythingForHWC();
1005 return true;
1006 }
1007
1008 // We received the present fence from the HWC, so we assume it successfully updated
1009 // the config, hence we update SF.
1010 mCheckPendingFence = false;
1011 setActiveConfigInternal();
1012 }
1013
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001014 // Store the local variable to release the lock.
1015 ActiveConfigInfo desiredActiveConfig;
1016 {
1017 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 if (!mDesiredActiveConfigChanged) {
1019 return false;
1020 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001021 desiredActiveConfig = mDesiredActiveConfig;
1022 }
1023
1024 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1026 // display is not valid or we are already in the requested mode
1027 // on both cases there is nothing left to do
1028 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1029 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1030 mDesiredActiveConfigChanged = false;
1031 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1032 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001033 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034
Ady Abraham838de062019-02-04 10:24:03 -08001035 // Desired active config was set, it is different than the config currently in use, however
1036 // allowed configs might have change by the time we process the refresh.
1037 // Make sure the desired config is still allowed
1038 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1039 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1040 mDesiredActiveConfig.configId = display->getActiveConfig();
1041 return false;
1042 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 mUpcomingActiveConfig = desiredActiveConfig;
1044 const auto displayId = display->getId();
1045 LOG_ALWAYS_FATAL_IF(!displayId);
1046
1047 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1048 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1049
1050 // we need to submit an empty frame to HWC to start the process
1051 mWaitForNextInvalidate = true;
1052 mCheckPendingFence = true;
1053
1054 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001055}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1058 Vector<ColorMode>* outColorModes) {
1059 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001060 return BAD_VALUE;
1061 }
1062
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001064 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001065 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1066
1067 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1068 if (!displayId) {
1069 return NAME_NOT_FOUND;
1070 }
1071
Dominik Laskowski075d3172018-05-24 15:50:06 -07001072 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001073 }
Michael Wright28f24d02016-07-12 13:30:53 -07001074 outColorModes->clear();
1075 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1076
1077 return NO_ERROR;
1078}
1079
Daniel Solomon42d04562019-01-20 21:03:19 -08001080status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1081 ui::DisplayPrimaries &primaries) {
1082 if (!displayToken) {
1083 return BAD_VALUE;
1084 }
1085
1086 // Currently we only support this API for a single internal display.
1087 if (getInternalDisplayToken() != displayToken) {
1088 return BAD_VALUE;
1089 }
1090
1091 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1092 return NO_ERROR;
1093}
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1096 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001097 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001098 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001099 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001100}
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001103 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 Vector<ColorMode> modes;
1105 getDisplayColorModes(displayToken, &modes);
1106 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1107 if (mode < ColorMode::NATIVE || !exists) {
1108 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1109 decodeColorMode(mode).c_str(), mode, displayToken.get());
1110 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001111 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 const auto display = getDisplayDevice(displayToken);
1113 if (!display) {
1114 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1115 decodeColorMode(mode).c_str(), mode, displayToken.get());
1116 } else if (display->isVirtual()) {
1117 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1118 decodeColorMode(mode).c_str(), mode);
1119 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001120 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1121 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 }
1123 }));
1124
Michael Wright28f24d02016-07-12 13:30:53 -07001125 return NO_ERROR;
1126}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001127
Svetoslavd85084b2014-03-20 10:28:31 -07001128status_t SurfaceFlinger::clearAnimationFrameStats() {
1129 Mutex::Autolock _l(mStateLock);
1130 mAnimFrameTracker.clearStats();
1131 return NO_ERROR;
1132}
1133
1134status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1135 Mutex::Autolock _l(mStateLock);
1136 mAnimFrameTracker.getStats(outStats);
1137 return NO_ERROR;
1138}
1139
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001140status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1141 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001142 Mutex::Autolock _l(mStateLock);
1143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001144 const auto display = getDisplayDeviceLocked(displayToken);
1145 if (!display) {
1146 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001147 return BAD_VALUE;
1148 }
1149
Peiyong Linfb069302018-04-25 14:34:31 -07001150 // At this point the DisplayDeivce should already be set up,
1151 // meaning the luminance information is already queried from
1152 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001153 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001154 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1155 capabilities.getDesiredMaxLuminance(),
1156 capabilities.getDesiredMaxAverageLuminance(),
1157 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001158
1159 return NO_ERROR;
1160}
1161
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001162status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1163 ui::PixelFormat* outFormat,
1164 ui::Dataspace* outDataspace,
1165 uint8_t* outComponentMask) const {
1166 if (!outFormat || !outDataspace || !outComponentMask) {
1167 return BAD_VALUE;
1168 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001169 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001170 if (!display || !display->getId()) {
1171 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1172 return BAD_VALUE;
1173 }
1174 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1175 outDataspace, outComponentMask);
1176}
1177
Kevin DuBois74e53772018-11-19 10:52:38 -08001178status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1179 bool enable, uint8_t componentMask,
1180 uint64_t maxFrames) const {
1181 const auto display = getDisplayDevice(displayToken);
1182 if (!display || !display->getId()) {
1183 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1184 return BAD_VALUE;
1185 }
1186
1187 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1188 componentMask, maxFrames);
1189}
1190
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001191status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1192 uint64_t maxFrames, uint64_t timestamp,
1193 DisplayedFrameStats* outStats) const {
1194 const auto display = getDisplayDevice(displayToken);
1195 if (!display || !display->getId()) {
1196 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1197 return BAD_VALUE;
1198 }
1199
1200 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1201 outStats);
1202}
1203
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001204status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1205 if (!outSupported) {
1206 return BAD_VALUE;
1207 }
1208 *outSupported = getRenderEngine().supportsProtectedContent();
1209 return NO_ERROR;
1210}
1211
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001212status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1213 bool* outIsWideColorDisplay) const {
1214 if (!displayToken || !outIsWideColorDisplay) {
1215 return BAD_VALUE;
1216 }
1217 Mutex::Autolock _l(mStateLock);
1218 const auto display = getDisplayDeviceLocked(displayToken);
1219 if (!display) {
1220 return BAD_VALUE;
1221 }
1222 *outIsWideColorDisplay = display->hasWideColorGamut();
1223 return NO_ERROR;
1224}
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001227 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 if (mInjectVSyncs == enable) {
1231 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233
Ana Krulecc2870422019-01-29 19:00:58 -08001234 auto resyncCallback =
1235 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001236
Ana Krulec98b5b242018-08-10 15:03:23 -07001237 // TODO(akrulec): Part of the Injector should be refactored, so that it
1238 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239 if (enable) {
1240 ALOGV("VSync Injections enabled");
1241 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001242 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001243 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001244 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001245 impl::EventThread::InterceptVSyncsCallback(),
1246 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001247 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001249 } else {
1250 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001251 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1252 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 }
1254
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001256 }));
1257
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 return NO_ERROR;
1259}
1260
1261status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 Mutex::Autolock _l(mStateLock);
1263
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001264 if (!mInjectVSyncs) {
1265 ALOGE("VSync Injections not enabled");
1266 return BAD_VALUE;
1267 }
1268 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1269 ALOGV("Injecting VSync inside SurfaceFlinger");
1270 mVSyncInjector->onInjectSyncEvent(when);
1271 }
1272 return NO_ERROR;
1273}
1274
Lloyd Pique755e3192018-01-31 16:46:15 -08001275status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1276 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001277 // Try to acquire a lock for 1s, fail gracefully
1278 const status_t err = mStateLock.timedLock(s2ns(1));
1279 const bool locked = (err == NO_ERROR);
1280 if (!locked) {
1281 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1282 return TIMED_OUT;
1283 }
1284
1285 outLayers->clear();
1286 mCurrentState.traverseInZOrder([&](Layer* layer) {
1287 outLayers->push_back(layer->getLayerDebugInfo());
1288 });
1289
1290 mStateLock.unlock();
1291 return NO_ERROR;
1292}
1293
Peiyong Linc6780972018-10-28 15:24:08 -07001294status_t SurfaceFlinger::getCompositionPreference(
1295 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1296 Dataspace* outWideColorGamutDataspace,
1297 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001298 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001299 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001300 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001301 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001302 return NO_ERROR;
1303}
1304
Dan Stozaec460082018-12-17 15:35:09 -08001305status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1306 const sp<IBinder>& stopLayerHandle,
1307 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001308 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001309 return BAD_VALUE;
1310 }
1311 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001312 return NO_ERROR;
1313}
1314
Dan Stozaec460082018-12-17 15:35:09 -08001315status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001316 if (!listener) {
1317 return BAD_VALUE;
1318 }
Dan Stozaec460082018-12-17 15:35:09 -08001319 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001320 return NO_ERROR;
1321}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001322// ----------------------------------------------------------------------------
1323
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001324sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1325 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001326 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 Mutex::Autolock lock(mStateLock);
1328 return getVsyncPeriod();
1329 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001330
Ana Krulecc2870422019-01-29 19:00:58 -08001331 const auto& handle =
1332 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001333
Ana Krulecc2870422019-01-29 19:00:58 -08001334 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001335}
1336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338
1339void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341}
1342
1343void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349}
1350
1351void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001352 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001357 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001358 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001359}
1360
1361status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001362 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001363 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364 if (res == NO_ERROR) {
1365 msg->wait();
1366 }
1367 return res;
1368}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001369
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001370void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001371 do {
1372 waitForEvent();
1373 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001374}
1375
Dominik Laskowski83b88212018-12-11 13:34:06 -08001376nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001377 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001378 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1379 return 0;
1380 }
1381
1382 const auto config = getHwComposer().getActiveConfig(*displayId);
1383 return config ? config->getVsyncPeriod() : 0;
1384}
1385
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001386void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1387 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001388 ATRACE_NAME("SF onVsync");
1389
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001392 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 return;
1394 }
1395
Dominik Laskowski075d3172018-05-24 15:50:06 -07001396 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001397 return;
1398 }
1399
Dominik Laskowski075d3172018-05-24 15:50:06 -07001400 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001401 // For now, we don't do anything with external display vsyncs.
1402 return;
1403 }
1404
Ana Krulecc2870422019-01-29 19:00:58 -08001405 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001406}
1407
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001409 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1410 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411}
1412
Ady Abraham838de062019-02-04 10:24:03 -08001413bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1414 std::lock_guard lock(mAllowedConfigsLock);
1415
1416 // if allowed configs are not set yet for this display, every config is considered allowed
1417 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1418 return true;
1419 }
1420
1421 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1422}
1423
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001424void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Ady Abraham1902d072019-03-01 17:18:59 -08001425 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001426 mPhaseOffsets->setRefreshRateType(refreshRate);
1427
1428 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1429 mVsyncModulator.setPhaseOffsets(early, gl, late);
1430
1431 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001432 return;
1433 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001434
Ana Krulec7d1d6832018-12-27 11:10:09 -08001435 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001436 const auto displayId = getInternalDisplayIdLocked();
1437 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001438 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001439
Ady Abraham1902d072019-03-01 17:18:59 -08001440 auto desiredConfigId = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate).configId;
1441 const auto display = getDisplayDeviceLocked(displayToken);
1442 if (desiredConfigId == display->getActiveConfig()) {
1443 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444 }
Ady Abraham1902d072019-03-01 17:18:59 -08001445
1446 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1447 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1448 return;
1449 }
1450
1451 setDesiredActiveConfig(getInternalDisplayTokenLocked(), desiredConfigId, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001455 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 // Ignore events that do not have the right sequenceId.
1460 if (sequenceId != getBE().mComposerSequenceId) {
1461 return;
1462 }
1463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Only lock if we're not on the main thread. This function is normally
1465 // called on a hwbinder thread, but for the primary display it's called on
1466 // the main thread with the state lock already held, so don't attempt to
1467 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001468 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001471
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001472 if (std::this_thread::get_id() == mMainThreadId) {
1473 // Process all pending hot plug events immediately if we are on the main thread.
1474 processDisplayHotplugEventsLocked();
1475 }
1476
Lloyd Piqueba04e622017-12-14 17:11:26 -08001477 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001478}
1479
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001480void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001482 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001485 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001486}
1487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001488void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001489 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001491 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 getHwComposer().setVsyncEnabled(*displayId,
1493 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1494 }
Mathias Agopian86303202012-07-24 22:46:10 -07001495}
1496
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001498void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001499 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001500 // Clear the drawing state so that the logic inside of
1501 // handleTransactionLocked will fire. It will determine the delta between
1502 // mCurrentState and mDrawingState and re-apply all changes when we make the
1503 // transition.
1504 mDrawingState.displays.clear();
1505 mDisplays.clear();
1506}
1507
Steven Thomas050b2c82017-03-06 11:45:16 -08001508void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001509 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001510 if (!mVrFlinger)
1511 return;
1512 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001513 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001514 return;
1515 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001516
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 ALOGE("Vr flinger is only supported for remote hardware composer"
1519 " service connections. Ignoring request to transition to vr"
1520 " flinger.");
1521 mVrFlingerRequestsDisplay = false;
1522 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001523 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001525 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Steven Thomas0123ac62018-07-12 11:32:34 -07001527 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001528 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001529
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001530 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001531
1532 // Clear out all the output layers from the composition engine for all
1533 // displays before destroying the hardware composer interface. This ensures
1534 // any HWC layers are destroyed through that interface before it becomes
1535 // invalid.
1536 for (const auto& [token, displayDevice] : mDisplays) {
1537 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1538 compositionengine::Output::OutputLayers());
1539 }
1540
Steven Thomas0123ac62018-07-12 11:32:34 -07001541 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1542 // called below. Clear the reference now so we don't accidentally use it
1543 // later.
1544 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001551 // Delete the current instance before creating the new one
1552 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1553 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1554 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1555 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001558 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001559
1560 if (vrFlingerRequestsDisplay) {
1561 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563
1564 mVisibleRegionsDirty = true;
1565 invalidateHwcGeometry();
1566
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001567 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001568 display = getDefaultDisplayDeviceLocked();
1569 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001570 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573 const nsecs_t vsyncPeriod = getVsyncPeriod();
1574 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001576 // The present fences returned from vr_hwc are not an accurate
1577 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001578 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Use phase of 0 since phase is not known.
1581 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001582 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001583 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001584
Ana Krulecc2870422019-01-29 19:00:58 -08001585 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001586
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001587 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589}
1590
Mathias Agopian4fec8732012-06-29 14:12:52 -07001591void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001592 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001593 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001594 case MessageQueue::INVALIDATE: {
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001595 if (mUseSmart90ForVideo) {
1596 // This call is made each time SF wakes up and creates a new frame. It is part
1597 // of video detection feature.
1598 mScheduler->updateFpsBasedOnNativeWindowApi();
1599 }
1600
Ady Abrahamb838aed2019-02-12 15:30:16 -08001601 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001602 break;
1603 }
1604
Alec Mourife3dc942019-02-12 14:19:18 -08001605 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001606 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001607 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001608 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001609 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1610 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001611 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001612 }
1613 // For now, only propagate backpressure when missing a hwc frame.
1614 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001615 if (mPropagateBackpressure) {
1616 signalLayerUpdate();
1617 break;
1618 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001619 }
Dan Stoza50182882016-07-08 12:02:20 -07001620
Steven Thomas050b2c82017-03-06 11:45:16 -08001621 // Now that we're going to make it to the handleMessageTransaction()
1622 // call below it's safe to call updateVrFlinger(), which will
1623 // potentially trigger a display handoff.
1624 updateVrFlinger();
1625
Dan Stoza6b9454d2014-11-07 16:00:59 -08001626 bool refreshNeeded = handleMessageTransaction();
1627 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001628
1629 updateCursorAsync();
1630 updateInputFlinger();
1631
Dan Stoza58784442014-12-02 16:58:17 -08001632 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001633 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001634 // Signal a refresh if a transaction modified the window state,
1635 // a new buffer was latched, or if HWC has requested a full
1636 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001637 signalRefresh();
1638 }
1639 break;
1640 }
1641 case MessageQueue::REFRESH: {
1642 handleMessageRefresh();
1643 break;
1644 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001645 }
1646}
1647
Dan Stoza6b9454d2014-11-07 16:00:59 -08001648bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001649 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001650 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001651
1652 // Apply any ready transactions in the queues if there are still transactions that have not been
1653 // applied, wake up during the next vsync period and check again
1654 bool transactionNeeded = false;
1655 if (!flushTransactionQueues()) {
1656 transactionNeeded = true;
1657 }
1658
Mathias Agopian4fec8732012-06-29 14:12:52 -07001659 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001660 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001662
1663 if (transactionNeeded) {
1664 setTransactionFlags(eTransactionNeeded);
1665 }
1666
1667 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668}
1669
Mathias Agopian4fec8732012-06-29 14:12:52 -07001670void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001672
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001673 mRefreshPending = false;
1674
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001675 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001676 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001677 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001678 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679 for (const auto& [token, display] : mDisplays) {
1680 beginFrame(display);
1681 prepareFrame(display);
1682 doDebugFlashRegions(display, repaintEverything);
1683 doComposition(display, repaintEverything);
1684 }
1685
Adrian Roos1e1a1282017-11-01 19:05:31 +01001686 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001687 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688
1689 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001690 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001691
Dan Stozabfbffeb2016-07-21 14:49:33 -07001692 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001693 for (const auto& [token, displayDevice] : mDisplays) {
1694 auto display = displayDevice->getCompositionDisplay();
1695 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001696 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001697 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001698 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699
Jorim Jaggi90535212018-05-23 23:44:06 +02001700 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001701
David Sodman7e4ae112018-02-09 15:02:28 -08001702 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705
1706bool SurfaceFlinger::handleMessageInvalidate() {
1707 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001708 bool refreshNeeded = handlePageFlip();
1709
Vishnu Nair4351ad52019-02-11 14:13:02 -08001710 if (mVisibleRegionsDirty) {
1711 computeLayerBounds();
1712 }
1713
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001714 for (auto& layer : mLayersPendingRefresh) {
1715 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001716 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001717 invalidateLayerStack(layer, visibleReg);
1718 }
1719 mLayersPendingRefresh.clear();
1720 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721}
1722
David Sodman79bba0e2018-08-05 18:07:49 -07001723void SurfaceFlinger::calculateWorkingSet() {
1724 ATRACE_CALL();
1725 ALOGV(__FUNCTION__);
1726
David Sodman79bba0e2018-08-05 18:07:49 -07001727 // build the h/w work list
1728 if (CC_UNLIKELY(mGeometryInvalid)) {
1729 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001730 for (const auto& [token, displayDevice] : mDisplays) {
1731 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001732 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 if (!displayId) {
1734 continue;
1735 }
David Sodman79bba0e2018-08-05 18:07:49 -07001736
Lloyd Pique32cbe282018-10-19 13:09:22 -07001737 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 for (size_t i = 0; i < currentLayers.size(); i++) {
1739 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001740
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001741 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001742 layer->forceClientComposition(displayDevice);
1743 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745
Lloyd Pique32cbe282018-10-19 13:09:22 -07001746 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001748 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 }
David Sodman79bba0e2018-08-05 18:07:49 -07001750 }
1751 }
1752 }
1753
1754 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001755 for (const auto& [token, displayDevice] : mDisplays) {
1756 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001757 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001758 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001759 continue;
1760 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001761 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001762
1763 if (mDrawingState.colorMatrixChanged) {
1764 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001765 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001766 Dataspace targetDataspace = Dataspace::UNKNOWN;
1767 if (useColorManagement) {
1768 ColorMode colorMode;
1769 RenderIntent renderIntent;
1770 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1771 display->setColorMode(colorMode, targetDataspace, renderIntent);
1772 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001773 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001774 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001775 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001776 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1777 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001778 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001779 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001780 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1781 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001782 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001783 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001784 }
1785
Peiyong Lind3788632018-09-18 16:01:31 -07001786 // TODO(b/111562338) remove when composer 2.3 is shipped.
1787 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001788 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001789 }
1790
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001791 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001792 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001793 }
1794
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001795 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001796 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001797 layer->setCompositionType(displayDevice,
1798 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001799 continue;
1800 }
1801
Lloyd Pique32cbe282018-10-19 13:09:22 -07001802 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001803 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Linc502cb72019-03-01 15:00:23 -08001804 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001805 }
1806 }
1807
1808 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001809
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001810 for (const auto& [token, displayDevice] : mDisplays) {
1811 auto display = displayDevice->getCompositionDisplay();
1812 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001813 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1814 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1815 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001816 }
1817 }
David Sodman79bba0e2018-08-05 18:07:49 -07001818}
1819
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1821 bool repaintEverything) {
1822 auto display = displayDevice->getCompositionDisplay();
1823 const auto& displayState = display->getState();
1824
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825 // is debugging enabled
1826 if (CC_LIKELY(!mDebugRegion))
1827 return;
1828
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001830 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001831 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001832 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001833 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001835 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001837 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001838 }
1839 }
1840
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001842
1843 if (mDebugRegion > 1) {
1844 usleep(mDebugRegion * 1000);
1845 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001846
Lloyd Pique32cbe282018-10-19 13:09:22 -07001847 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848}
1849
Adrian Roos1e1a1282017-11-01 19:05:31 +01001850void SurfaceFlinger::doTracing(const char* where) {
1851 ATRACE_CALL();
1852 ATRACE_NAME(where);
1853 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001854 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001855 }
1856}
1857
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001858void SurfaceFlinger::logLayerStats() {
1859 ATRACE_CALL();
1860 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001861 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001862 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001863 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001864 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001865 }
1866 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001867
1868 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001869 }
1870}
1871
David Sodman2b406362017-12-15 13:33:47 -08001872void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 ATRACE_CALL();
1875 ALOGV("preComposition");
1876
David Sodman2b406362017-12-15 13:33:47 -08001877 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1878
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001880 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001881 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882 needExtraInvalidate = true;
1883 }
Robert Carr2047fae2016-11-28 14:09:09 -08001884 });
1885
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 if (needExtraInvalidate) {
1887 signalLayerUpdate();
1888 }
1889}
1890
Ana Krulece588e312018-09-18 12:32:24 -07001891void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1892 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893 // Update queue of past composite+present times and determine the
1894 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001895 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001897 while (!getBE().mCompositePresentTimes.empty()) {
1898 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 // Cached values should have been updated before calling this method,
1900 // which helps avoid duplicate syscalls.
1901 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1902 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1903 break;
1904 }
1905 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001906 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907 }
1908
1909 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001910 while (getBE().mCompositePresentTimes.size() > 16) {
1911 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 }
1913
Ana Krulece588e312018-09-18 12:32:24 -07001914 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001915}
1916
Ana Krulece588e312018-09-18 12:32:24 -07001917void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1918 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 // Integer division and modulo round toward 0 not -inf, so we need to
1920 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001921 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1922 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1923 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924
Ana Krulec757f63a2019-01-25 10:46:18 -08001925 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001926 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001927 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001928 }
1929
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 // Snap the latency to a value that removes scheduling jitter from the
1931 // composition and present times, which often have >1ms of jitter.
1932 // Reducing jitter is important if an app attempts to extrapolate
1933 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001934 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001936 nsecs_t bias = stats.vsyncPeriod / 2;
1937 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1938 nsecs_t snappedCompositeToPresentLatency =
1939 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940
David Sodman99974d22017-11-28 12:04:33 -08001941 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001942 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1943 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001944 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945}
1946
David Sodman2b406362017-12-15 13:33:47 -08001947void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ATRACE_CALL();
1950 ALOGV("postComposition");
1951
Brian Anderson3546a3f2016-07-14 11:51:14 -07001952 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001953 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001954 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001955 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001956 }
1957
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001958 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001959 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001960
David Sodman73beded2017-11-15 11:56:06 -08001961 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001962 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001963 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001964 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001965 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1966 ->getRenderSurface()
1967 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001968 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001969 } else {
1970 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1971 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001972
David Sodman73beded2017-11-15 11:56:06 -08001973 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07001974 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
1975 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001976 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001977 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001978
Ana Krulece588e312018-09-18 12:32:24 -07001979 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001980 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981
David Sodman2b406362017-12-15 13:33:47 -08001982 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // when we started doing work for this frame, but that should be okay
1984 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001985 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001986 CompositorTiming compositorTiming;
1987 {
David Sodman99974d22017-11-28 12:04:33 -08001988 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1989 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001990 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991
Robert Carr2047fae2016-11-28 14:09:09 -08001992 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001993 bool frameLatched =
1994 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1995 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001996 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001997 recordBufferingStats(layer->getName().string(),
1998 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001999 }
Robert Carr2047fae2016-11-28 14:09:09 -08002000 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002001
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002002 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002003 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002004 }
2005
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002006 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002007 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2008 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002009 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002010 }
2011 }
2012
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002013 if (mAnimCompositionPending) {
2014 mAnimCompositionPending = false;
2015
Brian Anderson4e606e32017-03-16 15:34:57 -07002016 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002018 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002019 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002020 // The HWC doesn't support present fences, so use the refresh
2021 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002022 const nsecs_t presentTime =
2023 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002024 mAnimFrameTracker.setActualPresentTime(presentTime);
2025 }
2026 mAnimFrameTracker.advanceFrame();
2027 }
Dan Stozab90cf072015-03-05 11:05:59 -08002028
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002029 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002030 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002031 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002032 }
2033
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002034 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002035
Lloyd Pique32cbe282018-10-19 13:09:22 -07002036 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2037 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002038 return;
2039 }
2040
2041 nsecs_t currentTime = systemTime();
2042 if (mHasPoweredOff) {
2043 mHasPoweredOff = false;
2044 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002045 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002046 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002047 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2048 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002049 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002050 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002051 }
David Sodman4a36e932017-11-07 14:29:47 -08002052 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002053 }
David Sodman4a36e932017-11-07 14:29:47 -08002054 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002055
2056 {
2057 std::lock_guard lock(mTexturePoolMutex);
2058 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2059 if (refillCount > 0) {
2060 const size_t offset = mTexturePool.size();
2061 mTexturePool.resize(mTexturePoolSize);
2062 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2063 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2064 }
2065 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002066
Marissa Wallfda30bb2018-10-12 11:34:28 -07002067 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002068 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002069
Kevin DuBois413287f2019-02-25 08:46:47 -08002070 if (mLumaSampling && mRegionSamplingThread) {
2071 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002072 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002073}
2074
Vishnu Nair4351ad52019-02-11 14:13:02 -08002075void SurfaceFlinger::computeLayerBounds() {
2076 for (const auto& pair : mDisplays) {
2077 const auto& displayDevice = pair.second;
2078 const auto display = displayDevice->getCompositionDisplay();
2079 for (const auto& layer : mDrawingState.layersSortedByZ) {
2080 // only consider the layers on the given layer stack
2081 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002082 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002083 }
2084
2085 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2086 }
2087 }
2088}
2089
Mathias Agopiancd60f992012-08-16 16:28:27 -07002090void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 ATRACE_CALL();
2092 ALOGV("rebuildLayerStacks");
2093
Mathias Agopiancd60f992012-08-16 16:28:27 -07002094 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002095 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002096 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002097 mVisibleRegionsDirty = false;
2098 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002099
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002100 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 const auto& displayDevice = pair.second;
2102 auto display = displayDevice->getCompositionDisplay();
2103 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002104 Region opaqueRegion;
2105 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002106 compositionengine::Output::OutputLayers layersSortedByZ;
2107 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002108 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002109 const ui::Transform& tr = displayState.transform;
2110 const Rect bounds = displayState.bounds;
2111 if (displayState.isEnabled) {
2112 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002113
Jeff Sharkey76488112017-02-27 14:15:18 -07002114 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002115 auto compositionLayer = layer->getCompositionLayer();
2116 if (compositionLayer == nullptr) {
2117 return;
2118 }
2119
Lloyd Pique32cbe282018-10-19 13:09:22 -07002120 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002121 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2122 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2123
Lloyd Pique07e33212018-12-18 16:33:37 -08002124 bool needsOutputLayer = false;
2125
Lloyd Piqueef36b002019-01-23 17:52:04 -08002126 if (display->belongsInOutput(layer->getLayerStack(),
2127 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002128 Region drawRegion(tr.transform(
2129 layer->visibleNonTransparentRegion));
2130 drawRegion.andSelf(bounds);
2131 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002132 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002133 }
Chia-I Wu83806892017-11-16 10:50:20 -08002134 }
2135
Lloyd Pique07e33212018-12-18 16:33:37 -08002136 if (needsOutputLayer) {
2137 layersSortedByZ.emplace_back(
2138 display->getOrCreateOutputLayer(displayId, compositionLayer,
2139 layerFE));
2140 deprecated_layersSortedByZ.add(layer);
2141
2142 auto& outputLayerState = layersSortedByZ.back()->editState();
2143 outputLayerState.visibleRegion =
2144 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2145 } else if (displayId) {
2146 // For layers that are being removed from a HWC display,
2147 // and that have queued frames, add them to a a list of
2148 // released layers so we can properly set a fence.
2149 bool hasExistingOutputLayer =
2150 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2151 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2152 mLayersWithQueuedFrames.cend(),
2153 layer) != mLayersWithQueuedFrames.cend();
2154
2155 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002156 layersNeedingFences.add(layer);
2157 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002158 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002159 });
2160 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002161
2162 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2163
2164 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 displayDevice->setLayersNeedingFences(layersNeedingFences);
2166
2167 Region undefinedRegion{bounds};
2168 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2169
2170 display->editState().undefinedRegion = undefinedRegion;
2171 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002172 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002173 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002174}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002175
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002176// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002177// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002178// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002179// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002180// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002181// The returned HDR data space is one of
2182// - Dataspace::UNKNOWN
2183// - Dataspace::BT2020_HLG
2184// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2186 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002187 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002188 *outHdrDataSpace = Dataspace::UNKNOWN;
2189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002191 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002192 case Dataspace::V0_SCRGB:
2193 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002194 case Dataspace::BT2020:
2195 case Dataspace::BT2020_ITU:
2196 case Dataspace::BT2020_LINEAR:
2197 case Dataspace::DISPLAY_BT2020:
2198 bestDataSpace = Dataspace::DISPLAY_BT2020;
2199 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002200 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002201 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002202 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002203 case Dataspace::BT2020_PQ:
2204 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002205 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002206 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002207 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002208 case Dataspace::BT2020_HLG:
2209 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002210 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002211 // When there's mixed PQ content and HLG content, we set the HDR
2212 // data space to be BT2020_PQ and convert HLG to PQ.
2213 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2214 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002215 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002216 break;
2217 default:
2218 break;
2219 }
Romain Guy54f154a2017-10-24 21:40:32 +01002220 }
2221
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002222 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002223}
2224
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002225// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2227 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002228 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2229 *outMode = ColorMode::NATIVE;
2230 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002231 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002232 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002233 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002234
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002235 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002237
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002238 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2239
Peiyong Lina3ea5592019-02-10 14:45:00 -08002240 switch (mForceColorMode) {
2241 case ColorMode::SRGB:
2242 bestDataSpace = Dataspace::V0_SRGB;
2243 break;
2244 case ColorMode::DISPLAY_P3:
2245 bestDataSpace = Dataspace::DISPLAY_P3;
2246 break;
2247 default:
2248 break;
2249 }
2250
Peiyong Lindfde5112018-06-05 10:58:41 -07002251 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002252 const bool isHdr =
2253 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002254 if (isHdr) {
2255 bestDataSpace = hdrDataSpace;
2256 }
2257
Chia-I Wu0d711262018-05-21 15:19:35 -07002258 RenderIntent intent;
2259 switch (mDisplayColorSetting) {
2260 case DisplayColorSetting::MANAGED:
2261 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002262 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002263 break;
2264 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002265 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002266 break;
2267 default: // vendor display color setting
2268 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2269 break;
2270 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002271
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002272 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002273}
2274
Lloyd Pique32cbe282018-10-19 13:09:22 -07002275void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2276 auto display = displayDevice->getCompositionDisplay();
2277 const auto& displayState = display->getState();
2278
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002279 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002280 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2281 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002282
David Sodmanfa9b2af2017-12-24 13:28:59 -08002283 // If nothing has changed (!dirty), don't recompose.
2284 // If something changed, but we don't currently have any visible layers,
2285 // and didn't when we last did a composition, then skip it this time.
2286 // The second rule does two things:
2287 // - When all layers are removed from a display, we'll emit one black
2288 // frame, then nothing more until we get new layers.
2289 // - When a display is created with a private layer stack, we won't
2290 // emit any black frames until a layer is added to the layer stack.
2291 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002292
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 const char flagPrefix[] = {'-', '+'};
2294 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002295 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2296 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2297 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2298 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002299
Lloyd Pique31cb2942018-10-19 17:23:03 -07002300 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002301
David Sodmanfa9b2af2017-12-24 13:28:59 -08002302 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002303 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002304 }
2305}
2306
Lloyd Pique32cbe282018-10-19 13:09:22 -07002307void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2308 auto display = displayDevice->getCompositionDisplay();
2309 const auto& displayState = display->getState();
2310
2311 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002312 return;
David Sodman2b406362017-12-15 13:33:47 -08002313 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002314
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002315 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002316 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002317 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002318}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002319
Lloyd Pique32cbe282018-10-19 13:09:22 -07002320void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002321 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002322 ALOGV("doComposition");
2323
Lloyd Pique32cbe282018-10-19 13:09:22 -07002324 auto display = displayDevice->getCompositionDisplay();
2325 const auto& displayState = display->getState();
2326
2327 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002328 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002329 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002330
David Sodmanfa9b2af2017-12-24 13:28:59 -08002331 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002332 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002333
Lloyd Pique32cbe282018-10-19 13:09:22 -07002334 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002335 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002336 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002337 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002338}
2339
David Sodmanfa9b2af2017-12-24 13:28:59 -08002340void SurfaceFlinger::postFrame()
2341{
2342 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 const auto display = getDefaultDisplayDeviceLocked();
2344 if (display && getHwComposer().isConnected(*display->getId())) {
2345 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2347 logFrameStats();
2348 }
2349 }
2350}
2351
Lloyd Pique32cbe282018-10-19 13:09:22 -07002352void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002353 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002355
Lloyd Pique32cbe282018-10-19 13:09:22 -07002356 auto display = displayDevice->getCompositionDisplay();
2357 const auto& displayState = display->getState();
2358 const auto displayId = display->getId();
2359
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002361
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002363 if (displayId) {
2364 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002365 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002366 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002367 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002368 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002369 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002370
Chia-I Wu7b549592017-11-15 09:14:57 -08002371 // The layer buffer from the previous frame (if any) is released
2372 // by HWC only when the release fence from this frame (if any) is
2373 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002374 if (layer->getState().hwc) {
2375 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002376 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002377 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2378 usedClientComposition =
2379 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002380 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002381
2382 // If the layer was client composited in the previous frame, we
2383 // need to merge with the previous client target acquire fence.
2384 // Since we do not track that, always merge with the current
2385 // client target acquire fence when it is available, even though
2386 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002387 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002388 releaseFence =
2389 Fence::merge("LayerRelease", releaseFence,
2390 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002391 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002392
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002393 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 }
Chia-I Wu83806892017-11-16 10:50:20 -08002395
2396 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002398 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002399 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002401 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002403 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002404 }
2405 }
2406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 if (displayId) {
2408 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002409 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002410 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411}
2412
Mathias Agopian87baae12012-07-31 12:38:26 -07002413void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414{
Mathias Agopian841cde52012-03-01 15:44:37 -08002415 ATRACE_CALL();
2416
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002417 // here we keep a copy of the drawing state (that is the state that's
2418 // going to be overwritten by handleTransactionLocked()) outside of
2419 // mStateLock so that the side-effects of the State assignment
2420 // don't happen with mStateLock held (which can cause deadlocks).
2421 State drawingState(mDrawingState);
2422
Mathias Agopianca4d3602011-05-19 15:38:14 -07002423 Mutex::Autolock _l(mStateLock);
2424 const nsecs_t now = systemTime();
2425 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopianca4d3602011-05-19 15:38:14 -07002427 // Here we're guaranteed that some transaction flags are set
2428 // so we can call handleTransactionLocked() unconditionally.
2429 // We call getTransactionFlags(), which will also clear the flags,
2430 // with mStateLock held to guarantee that mCurrentState won't change
2431 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002432
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002433 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002434 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002435 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002436
Mathias Agopianca4d3602011-05-19 15:38:14 -07002437 mLastTransactionTime = systemTime() - now;
2438 mDebugInTransaction = 0;
2439 invalidateHwcGeometry();
2440 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002441}
2442
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2444 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 const std::optional<DisplayIdentificationInfo> info =
2446 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002449 continue;
2450 }
2451
Lloyd Piqueba04e622017-12-14 17:11:26 -08002452 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002454 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 mPhysicalDisplayTokens[info->id] = new BBinder();
2456 DisplayDeviceState state;
2457 state.displayId = info->id;
2458 state.isSecure = true; // All physical displays are currently considered secure.
2459 state.displayName = info->name;
2460 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2461 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002462 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002463 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002464 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465
Dominik Laskowski075d3172018-05-24 15:50:06 -07002466 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2467 if (index >= 0) {
2468 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2469 mInterceptor->saveDisplayDeletion(state.sequenceId);
2470 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002473 }
2474
2475 processDisplayChangesLocked();
2476 }
2477
2478 mPendingHotplugEvents.clear();
2479}
2480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002481void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002482 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2483 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002484}
2485
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002488 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 const sp<IGraphicBufferProducer>& producer) {
2490 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002491 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002493 creationArgs.isSecure = state.isSecure;
2494 creationArgs.displaySurface = dispSurface;
2495 creationArgs.hasWideColorGamut = false;
2496 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002498 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 creationArgs.isPrimary = isInternalDisplay;
2500
2501 if (useColorManagement && displayId) {
2502 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002504 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002507
Dominik Laskowski7e045462018-05-30 13:02:02 -07002508 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002510 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 }
tangrobin6753a022018-08-10 10:58:54 +08002512 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513
Dominik Laskowski075d3172018-05-24 15:50:06 -07002514 if (displayId) {
2515 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002516 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002518 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
Lloyd Pique90c115d2018-09-18 21:39:42 -07002520 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002522 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524 // Make sure that composition can never be stalled by a virtual display
2525 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002526 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002527 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2529 }
2530
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 creationArgs.displayInstallOrientation =
2532 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002533
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002535 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002536
Lloyd Pique90c115d2018-09-18 21:39:42 -07002537 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538
2539 if (maxFrameBufferAcquiredBuffers >= 3) {
2540 nativeWindowSurface->preallocateBuffers();
2541 }
2542
2543 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002544 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002545 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002547 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002549 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2550 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 if (!state.isVirtual()) {
2552 LOG_ALWAYS_FATAL_IF(!displayId);
2553 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 display->setLayerStack(state.layerStack);
2557 display->setProjection(state.orientation, state.viewport, state.frame);
2558 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002560 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561}
2562
Lloyd Pique347200f2017-12-14 17:00:15 -08002563void SurfaceFlinger::processDisplayChangesLocked() {
2564 // here we take advantage of Vector's copy-on-write semantics to
2565 // improve performance by skipping the transaction entirely when
2566 // know that the lists are identical
2567 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2568 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2569 if (!curr.isIdenticalTo(draw)) {
2570 mVisibleRegionsDirty = true;
2571 const size_t cc = curr.size();
2572 size_t dc = draw.size();
2573
2574 // find the displays that were removed
2575 // (ie: in drawing state but not in current state)
2576 // also handle displays that changed
2577 // (ie: displays that are in both lists)
2578 for (size_t i = 0; i < dc;) {
2579 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2580 if (j < 0) {
2581 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002582 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002583 // Save display ID before disconnecting.
2584 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002585 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002586
2587 if (!display->isVirtual()) {
2588 LOG_ALWAYS_FATAL_IF(!displayId);
2589 dispatchDisplayHotplugEvent(displayId->value, false);
2590 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002591 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002592
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002593 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 } else {
2595 // this display is in both lists. see if something changed.
2596 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002597 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002598 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2599 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2600 if (state_binder != draw_binder) {
2601 // changing the surface is like destroying and
2602 // recreating the DisplayDevice, so we just remove it
2603 // from the drawing state, so that it get re-added
2604 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002606 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002607 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002608 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002609 mDrawingState.displays.removeItemsAt(i);
2610 dc--;
2611 // at this point we must loop to the next item
2612 continue;
2613 }
2614
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002616 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002617 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002618 }
2619 if ((state.orientation != draw[i].orientation) ||
2620 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002621 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002622 }
2623 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002624 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002625 }
2626 }
2627 }
2628 ++i;
2629 }
2630
2631 // find displays that were added
2632 // (ie: in current state but not in drawing state)
2633 for (size_t i = 0; i < cc; i++) {
2634 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2635 const DisplayDeviceState& state(curr[i]);
2636
Lloyd Pique542307f2018-10-19 13:24:08 -07002637 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 sp<IGraphicBufferProducer> producer;
2639 sp<IGraphicBufferProducer> bqProducer;
2640 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002641 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002642
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002644 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 // Virtual displays without a surface are dormant:
2646 // they have external state (layer stack, projection,
2647 // etc.) but no internal state (i.e. a DisplayDevice).
2648 if (state.surface != nullptr) {
2649 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 int width = 0;
2652 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2653 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2654 int height = 0;
2655 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2656 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2657 int intFormat = 0;
2658 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2659 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002660 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002661
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662 displayId =
2663 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 }
2665
2666 // TODO: Plumb requested format back up to consumer
2667
2668 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002670 bqProducer, bqConsumer,
2671 state.displayName);
2672
2673 dispSurface = vds;
2674 producer = vds;
2675 }
2676 } else {
2677 ALOGE_IF(state.surface != nullptr,
2678 "adding a supported display, but rendering "
2679 "surface is provided (%p), ignoring it",
2680 state.surface.get());
2681
Dominik Laskowski075d3172018-05-24 15:50:06 -07002682 displayId = state.displayId;
2683 LOG_ALWAYS_FATAL_IF(!displayId);
2684 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 producer = bqProducer;
2686 }
2687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002688 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002691 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002693 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002695 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 }
2697 }
2698 }
2699 }
2700 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002701
2702 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002703}
2704
Mathias Agopian87baae12012-07-31 12:38:26 -07002705void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002706{
Dan Stoza7dde5992015-05-22 09:51:44 -07002707 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002708 mCurrentState.traverseInZOrder([](Layer* layer) {
2709 layer->notifyAvailableFrames();
2710 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002711
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712 /*
2713 * Traversal of the children
2714 * (perform the transaction for each of them if needed)
2715 */
2716
Mathias Agopian3559b072012-08-15 13:46:03 -07002717 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002718 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002720 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721
2722 const uint32_t flags = layer->doTransaction(0);
2723 if (flags & Layer::eVisibleRegion)
2724 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002725
2726 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002727 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002728 }
Robert Carr2047fae2016-11-28 14:09:09 -08002729 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 }
2731
2732 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002733 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 */
2735
Mathias Agopiane57f2922012-08-09 16:29:12 -07002736 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002738 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002739 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002741 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002742 // The transform hint might have changed for some layers
2743 // (either because a display has changed, or because a layer
2744 // as changed).
2745 //
2746 // Walk through all the layers in currentLayers,
2747 // and update their transform hint.
2748 //
2749 // If a layer is visible only on a single display, then that
2750 // display is used to calculate the hint, otherwise we use the
2751 // default display.
2752 //
2753 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2754 // the hint is set before we acquire a buffer from the surface texture.
2755 //
2756 // NOTE: layer transactions have taken place already, so we use their
2757 // drawing state. However, SurfaceFlinger's own transaction has not
2758 // happened yet, so we must use the current state layer list
2759 // (soon to become the drawing state list).
2760 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002762 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002763 bool first = true;
2764 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002765 // NOTE: we rely on the fact that layers are sorted by
2766 // layerStack first (so we don't have to traverse the list
2767 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002769 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002770 currentlayerStack = layerStack;
2771 // figure out if this layerstack is mirrored
2772 // (more than one display) if so, pick the default display,
2773 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 hintDisplay = nullptr;
2775 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002776 if (display->getCompositionDisplay()
2777 ->belongsInOutput(layer->getLayerStack(),
2778 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 if (hintDisplay) {
2780 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002781 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002784 }
2785 }
2786 }
2787 }
Chet Haase91d25932013-04-11 15:24:55 -07002788
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002789 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002790 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2791 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002792
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002793 // could be null when this layer is using a layerStack
2794 // that is not visible on any display. Also can occur at
2795 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002797 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002798
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002800 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 if (hintDisplay) {
2802 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002803 }
Robert Carr2047fae2016-11-28 14:09:09 -08002804
2805 first = false;
2806 });
Mathias Agopian84300952012-11-21 16:02:13 -08002807 }
2808
2809
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 /*
2811 * Perform our own transaction if needed
2812 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813
2814 if (mLayersAdded) {
2815 mLayersAdded = false;
2816 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002817 mVisibleRegionsDirty = true;
2818 }
2819
2820 // some layers might have been removed, so
2821 // we need to update the regions they're exposing.
2822 if (mLayersRemoved) {
2823 mLayersRemoved = false;
2824 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002825 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002827 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002829 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002830 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002831 }
Robert Carr2047fae2016-11-28 14:09:09 -08002832 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 }
2834
Vishnu Nairec0ab382019-02-13 15:32:56 -08002835 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002837}
2838
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002839void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002840 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002841 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002842 return;
2843 }
2844
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002845 if (mVisibleRegionsDirty || mInputInfoChanged) {
2846 mInputInfoChanged = false;
2847 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002848 } else if (mInputWindowCommands.syncInputWindows) {
2849 // If the caller requested to sync input windows, but there are no
2850 // changes to input windows, notify immediately.
2851 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002852 }
2853
2854 executeInputWindowCommands();
2855}
2856
2857void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002858 Vector<InputWindowInfo> inputHandles;
2859
2860 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2861 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002862 // When calculating the screen bounds we ignore the transparent region since it may
2863 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002864 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002865 }
2866 });
chaviw291d88a2019-02-14 10:33:58 -08002867
2868 mInputFlinger->setInputWindows(inputHandles,
2869 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2870 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002871}
2872
Vishnu Nairec0ab382019-02-13 15:32:56 -08002873void SurfaceFlinger::commitInputWindowCommands() {
2874 mInputWindowCommands.merge(mPendingInputWindowCommands);
2875 mPendingInputWindowCommands.clear();
2876}
2877
chaviwfbe5d9c2018-12-26 12:23:37 -08002878void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002879 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2880 if (transferTouchFocusCommand.fromToken != nullptr &&
2881 transferTouchFocusCommand.toToken != nullptr &&
2882 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2883 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2884 transferTouchFocusCommand.toToken);
2885 }
2886 }
2887
2888 mInputWindowCommands.clear();
2889}
2890
Riley Andrews03414a12014-07-01 14:22:59 -07002891void SurfaceFlinger::updateCursorAsync()
2892{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002894 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002895 continue;
2896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2899 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002900 }
2901 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002902}
2903
chaviw61626f22018-11-15 16:26:27 -08002904void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2905 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002906 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002907 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002908 }
2909 layer->releasePendingBuffer(systemTime());
2910}
2911
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912void SurfaceFlinger::commitTransaction()
2913{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002914 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002915 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 for (const auto& l : mLayersPendingRemoval) {
2917 recordBufferingStats(l->getName().string(),
2918 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002919
Lloyd Pique07e33212018-12-18 16:33:37 -08002920 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002921 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002922 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002923 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002924 }
2925 mLayersPendingRemoval.clear();
2926 }
2927
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002928 // If this transaction is part of a window animation then the next frame
2929 // we composite should be considered an animation as well.
2930 mAnimCompositionPending = mAnimTransactionPending;
2931
Mathias Agopian4fec8732012-06-29 14:12:52 -07002932 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002933 // clear the "changed" flags in current state
2934 mCurrentState.colorMatrixChanged = false;
2935
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 mDrawingState.traverseInZOrder([](Layer* layer) {
2937 layer->commitChildList();
2938 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002939 mTransactionPending = false;
2940 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002941 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942}
2943
Lloyd Pique32cbe282018-10-19 13:09:22 -07002944void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002946 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002948
Lloyd Pique32cbe282018-10-19 13:09:22 -07002949 auto display = displayDevice->getCompositionDisplay();
2950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 Region aboveOpaqueLayers;
2952 Region aboveCoveredLayers;
2953 Region dirty;
2954
Mathias Agopian87baae12012-07-31 12:38:26 -07002955 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956
Robert Carr2047fae2016-11-28 14:09:09 -08002957 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002958 // start with the whole surface at its current location
2959 const Layer::State& s(layer->getDrawingState());
2960
Jesse Hall01e29052013-02-19 16:13:35 -08002961 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08002962 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002963 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002964 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002965
Mathias Agopianab028732010-03-16 16:41:46 -07002966 /*
2967 * opaqueRegion: area of a surface that is fully opaque.
2968 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002970
2971 /*
2972 * visibleRegion: area of a surface that is visible on screen
2973 * and not fully transparent. This is essentially the layer's
2974 * footprint minus the opaque regions above it.
2975 * Areas covered by a translucent surface are considered visible.
2976 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002978
2979 /*
2980 * coveredRegion: area of a surface that is covered by all
2981 * visible regions above it (which includes the translucent areas).
2982 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002984
Jesse Halla8026d22012-09-25 13:25:04 -07002985 /*
2986 * transparentRegion: area of a surface that is hinted to be completely
2987 * transparent. This is only used to tell when the layer has no visible
2988 * non-transparent regions and can be removed from the layer list. It
2989 * does not affect the visibleRegion of this layer or any layers
2990 * beneath it. The hint may not be correct if apps don't respect the
2991 * SurfaceView restrictions (which, sadly, some don't).
2992 */
2993 Region transparentRegion;
2994
Mathias Agopianab028732010-03-16 16:41:46 -07002995
2996 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002997 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002998 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002999 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003000
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003002 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003003 if (!visibleRegion.isEmpty()) {
3004 // Remove the transparent area from the visible region
3005 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003006 if (tr.preserveRects()) {
3007 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003008 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003010 // transformation too complex, can't do the
3011 // transparent region optimization.
3012 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 }
Mathias Agopianab028732010-03-16 16:41:46 -07003014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015
Mathias Agopianab028732010-03-16 16:41:46 -07003016 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003017 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003018 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003019 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003020 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003021 // the opaque region is the layer's footprint
3022 opaqueRegion = visibleRegion;
3023 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024 }
3025 }
3026
Robert Carre5f4f692018-01-12 13:12:28 -08003027 if (visibleRegion.isEmpty()) {
3028 layer->clearVisibilityRegions();
3029 return;
3030 }
3031
Mathias Agopianab028732010-03-16 16:41:46 -07003032 // Clip the covered region to the visible region
3033 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3034
3035 // Update aboveCoveredLayers for next (lower) layer
3036 aboveCoveredLayers.orSelf(visibleRegion);
3037
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 // subtract the opaque region covered by the layers above us
3039 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040
3041 // compute this layer's dirty region
3042 if (layer->contentDirty) {
3043 // we need to invalidate the whole region
3044 dirty = visibleRegion;
3045 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 layer->contentDirty = false;
3048 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003049 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003050 * the exposed region consists of two components:
3051 * 1) what's VISIBLE now and was COVERED before
3052 * 2) what's EXPOSED now less what was EXPOSED before
3053 *
3054 * note that (1) is conservative, we start with the whole
3055 * visible region but only keep what used to be covered by
3056 * something -- which mean it may have been exposed.
3057 *
3058 * (2) handles areas that were not covered by anything but got
3059 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003060 */
Mathias Agopianab028732010-03-16 16:41:46 -07003061 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003062 const Region oldVisibleRegion = layer->visibleRegion;
3063 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003064 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3065 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 }
3067 dirty.subtractSelf(aboveOpaqueLayers);
3068
3069 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003070 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071
Mathias Agopianab028732010-03-16 16:41:46 -07003072 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003074
Jesse Halla8026d22012-09-25 13:25:04 -07003075 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 layer->setVisibleRegion(visibleRegion);
3077 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003078 layer->setVisibleNonTransparentRegion(
3079 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003080 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081
Mathias Agopian87baae12012-07-31 12:38:26 -07003082 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Chia-I Wuab0c3192017-08-01 11:29:00 -07003085void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003086 for (const auto& [token, displayDevice] : mDisplays) {
3087 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003088 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003089 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003090 }
3091 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003092}
3093
Dan Stoza6b9454d2014-11-07 16:00:59 -08003094bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 ALOGV("handlePageFlip");
3097
Brian Andersond6927fb2016-07-23 23:37:30 -07003098 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003101 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003102 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003103
3104 // Store the set of layers that need updates. This set must not change as
3105 // buffers are being latched, as this could result in a deadlock.
3106 // Example: Two producers share the same command stream and:
3107 // 1.) Layer 0 is latched
3108 // 2.) Layer 0 gets a new frame
3109 // 2.) Layer 1 gets a new frame
3110 // 3.) Layer 1 is latched.
3111 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3112 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003113 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003114 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003115 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003116 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003117 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003118 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003119 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003120 } else {
3121 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003122 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003123 } else {
3124 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003125 }
Robert Carr2047fae2016-11-28 14:09:09 -08003126 });
3127
Lloyd Piquef2c79392018-12-20 16:23:33 -08003128 if (!mLayersWithQueuedFrames.empty()) {
3129 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3130 // writes to Layer current state. See also b/119481871
3131 Mutex::Autolock lock(mStateLock);
3132
3133 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003134 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003135 mLayersPendingRefresh.push_back(layer);
3136 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003137 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003138 if (layer->isBufferLatched()) {
3139 newDataLatched = true;
3140 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003141 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003142 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003143
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003144 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003145
3146 // If we will need to wake up at some time in the future to deal with a
3147 // queued frame that shouldn't be displayed during this vsync period, wake
3148 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003149 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003150 signalLayerUpdate();
3151 }
3152
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003153 // enter boot animation on first buffer latch
3154 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3155 ALOGI("Enter boot animation");
3156 mBootStage = BootStage::BOOTANIMATION;
3157 }
3158
Dan Stoza6b9454d2014-11-07 16:00:59 -08003159 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003160 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161}
3162
Mathias Agopianad456f92011-01-13 17:53:01 -08003163void SurfaceFlinger::invalidateHwcGeometry()
3164{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003165 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003166}
3167
Lloyd Pique32cbe282018-10-19 13:09:22 -07003168void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003169 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003170 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003171 // We only need to actually compose the display if:
3172 // 1) It is being handled by hardware composer, which may need this to
3173 // keep its virtual display state machine in sync, or
3174 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003175 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003176 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003177 return;
3178 }
3179
Dan Stoza9e56aa02015-11-02 13:00:03 -08003180 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003181 base::unique_fd readyFence;
3182 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003183
3184 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003185 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186}
3187
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003188bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3189 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003190 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003191 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003192
Lloyd Pique32cbe282018-10-19 13:09:22 -07003193 auto display = displayDevice->getCompositionDisplay();
3194 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003195 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003196 auto& renderEngine = getRenderEngine();
3197 const bool supportProtectedContent =
3198 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003199
3200 const Region bounds(displayState.bounds);
3201 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003202 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003203 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003204
Peiyong Lind3788632018-09-18 16:01:31 -07003205 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003206 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003207
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003208 renderengine::DisplaySettings clientCompositionDisplay;
3209 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3210 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003211 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003212
Dan Stoza9e56aa02015-11-02 13:00:03 -08003213 if (hasClientComposition) {
3214 ALOGV("hasClientComposition");
3215
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003216 if (displayDevice->isPrimary() && supportProtectedContent) {
3217 bool needsProtected = false;
3218 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3219 // If the layer is a protected layer, mark protected context is needed.
3220 if (layer->isProtected()) {
3221 needsProtected = true;
3222 break;
3223 }
3224 }
3225 if (needsProtected != renderEngine.isProtected() &&
3226 renderEngine.useProtectedContext(needsProtected)) {
3227 display->getRenderSurface()->setProtected(needsProtected);
3228 }
3229 }
3230
Alec Mouri6338c9d2019-02-07 16:57:51 -08003231 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003232
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003233 if (buf == nullptr) {
3234 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3235 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003236 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003237 return false;
3238 }
3239
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003240 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3241 clientCompositionDisplay.clip = displayState.scissor;
3242 const ui::Transform& displayTransform = displayState.transform;
3243 mat4 m;
3244 m[0][0] = displayTransform[0][0];
3245 m[0][1] = displayTransform[0][1];
3246 m[0][3] = displayTransform[0][2];
3247 m[1][0] = displayTransform[1][0];
3248 m[1][1] = displayTransform[1][1];
3249 m[1][3] = displayTransform[1][2];
3250 m[3][0] = displayTransform[2][0];
3251 m[3][1] = displayTransform[2][1];
3252 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003253 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003254
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003255 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003256 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003257 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003258 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003259 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003260 clientCompositionDisplay.outputDataspace = outputDataspace;
3261 clientCompositionDisplay.maxLuminance =
3262 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003263
Lloyd Pique441d5042018-10-18 16:49:51 -07003264 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003265 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003266 getHwComposer()
3267 .hasDisplayCapability(displayId,
3268 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003269
Peiyong Lind3788632018-09-18 16:01:31 -07003270 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003271 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3272 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003273 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003274 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003275 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003276
Mathias Agopian85d751c2012-08-29 16:59:24 -07003277 /*
3278 * and then, render the layers targeted at the framebuffer
3279 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003280
Dan Stoza9e56aa02015-11-02 13:00:03 -08003281 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003282 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003283 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003284 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003285 const Region viewportRegion(displayState.viewport);
3286 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003287 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003288 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003289 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003290 switch (layer->getCompositionType(displayDevice)) {
3291 case Hwc2::IComposerClient::Composition::CURSOR:
3292 case Hwc2::IComposerClient::Composition::DEVICE:
3293 case Hwc2::IComposerClient::Composition::SIDEBAND:
3294 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003295 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003296 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003297 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003298 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003299 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003300 // never clear the very first layer since we're
3301 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003302 renderengine::LayerSettings layerSettings;
3303 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003304 bool prepared =
3305 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3306 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003307
3308 if (prepared) {
3309 layerSettings.source.buffer.buffer = nullptr;
3310 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3311 layerSettings.alpha = half(0.0);
3312 layerSettings.disableBlending = true;
3313 clientCompositionLayers.push_back(layerSettings);
3314 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003315 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003316 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003317 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003318 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003319 renderengine::LayerSettings layerSettings;
3320 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003321 layer->prepareClientLayer(renderArea, clip, clearRegion,
3322 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 if (prepared) {
3324 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003325 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003326 break;
3327 }
3328 default:
3329 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003330 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003331 } else {
3332 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003333 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003334 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003335 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003336
Alec Mouri820c7402019-01-23 13:02:39 -08003337 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003339 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003340
3341 // We boost GPU frequency here because there will be color spaces conversion
3342 // and it's expensive. We boost the GPU frequency so that GPU composition can
3343 // finish in time. We must reset GPU frequency afterwards, because high frequency
3344 // consumes extra battery.
3345 const bool expensiveRenderingExpected =
3346 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3347 if (expensiveRenderingExpected && displayId) {
3348 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3349 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003350 if (!debugRegion.isEmpty()) {
3351 Region::const_iterator it = debugRegion.begin();
3352 Region::const_iterator end = debugRegion.end();
3353 while (it != end) {
3354 const Rect& rect = *it++;
3355 renderengine::LayerSettings layerSettings;
3356 layerSettings.source.buffer.buffer = nullptr;
3357 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3358 layerSettings.geometry.boundaries = rect.toFloatRect();
3359 layerSettings.alpha = half(1.0);
3360 clientCompositionLayers.push_back(layerSettings);
3361 }
3362 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003363 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3364 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003365 if (expensiveRenderingExpected && displayId) {
3366 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3367 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003368 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003369 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370}
3371
Chia-I Wu28e3a252018-09-07 12:05:02 -07003372void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003373 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003374 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375}
3376
Dan Stoza7d89d062015-04-30 13:29:25 -07003377status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003378 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003379 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003380 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003381 const sp<Layer>& parent,
3382 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003383{
Dan Stoza7d89d062015-04-30 13:29:25 -07003384 // add this layer to the current state list
3385 {
3386 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003387 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003388 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3389 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003390 return NO_MEMORY;
3391 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003392 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003393 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003394 } else if (parent == nullptr) {
3395 lbc->onRemovedFromCurrentState();
3396 } else if (parent->isRemovedFromCurrentState()) {
3397 parent->addChild(lbc);
3398 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003399 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003400 parent->addChild(lbc);
3401 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003402
Yiwei Zhang243b3782018-05-15 17:40:04 -07003403 if (gbc != nullptr) {
3404 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3405 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3406 mMaxGraphicBufferProducerListSize,
3407 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3408 mGraphicBufferProducerList.size(),
3409 mMaxGraphicBufferProducerListSize, mNumLayers);
3410 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003411 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003412 }
3413
Mathias Agopian96f08192010-06-02 23:28:45 -07003414 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003415 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003416
Dan Stoza7d89d062015-04-30 13:29:25 -07003417 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003418}
3419
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003420uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003421 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003422}
3423
Mathias Agopian3f844832013-08-07 21:24:32 -07003424uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003425 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003426}
3427
Mathias Agopian3f844832013-08-07 21:24:32 -07003428uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003429 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003430}
3431
3432uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003433 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003434 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003435 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003437 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 }
3439 return old;
3440}
3441
Marissa Wall713b63f2018-10-17 15:42:43 -07003442bool SurfaceFlinger::flushTransactionQueues() {
3443 Mutex::Autolock _l(mStateLock);
3444 auto it = mTransactionQueues.begin();
3445 while (it != mTransactionQueues.end()) {
3446 auto& [applyToken, transactionQueue] = *it;
3447
3448 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003449 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3450 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003451 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003452 break;
3453 }
Robert Carr14167e02019-02-13 13:50:55 -08003454 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003455 transactionQueue.pop();
3456 }
3457
3458 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3459 }
3460 return mTransactionQueues.empty();
3461}
3462
chaviwca27f252018-02-06 16:46:39 -08003463bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3464 for (const ComposerState& state : states) {
3465 // Here we need to check that the interface we're given is indeed
3466 // one of our own. A malicious client could give us a nullptr
3467 // IInterface, or one of its own or even one of our own but a
3468 // different type. All these situations would cause us to crash.
3469 if (state.client == nullptr) {
3470 return true;
3471 }
3472
3473 sp<IBinder> binder = IInterface::asBinder(state.client);
3474 if (binder == nullptr) {
3475 return true;
3476 }
3477
3478 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3479 return true;
3480 }
3481 }
3482 return false;
3483}
3484
Marissa Wall17b4e452018-12-26 16:32:34 -08003485bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3486 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003487 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003488 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3489 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3490 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3491 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3492 return false;
3493 }
3494
Marissa Wall713b63f2018-10-17 15:42:43 -07003495 for (const ComposerState& state : states) {
3496 const layer_state_t& s = state.state;
3497 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3498 continue;
3499 }
3500 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003501 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003502 }
3503 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003504 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003505}
3506
3507void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3508 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003509 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003510 const InputWindowCommands& inputWindowCommands,
3511 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003512 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003513
3514 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3515
Mathias Agopian698c0872011-06-28 19:09:31 -07003516 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003517
chaviwca27f252018-02-06 16:46:39 -08003518 if (containsAnyInvalidClientState(states)) {
3519 return;
3520 }
3521
Marissa Wall713b63f2018-10-17 15:42:43 -07003522 // If its TransactionQueue already has a pending TransactionState or if it is pending
3523 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003524 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003525 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3526 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003527 setTransactionFlags(eTransactionNeeded);
3528 return;
3529 }
3530
Robert Carr14167e02019-02-13 13:50:55 -08003531 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003532}
3533
3534void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003535 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003536 const InputWindowCommands& inputWindowCommands,
3537 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003538 uint32_t transactionFlags = 0;
3539
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003540 if (flags & eAnimation) {
3541 // For window updates that are part of an animation we must wait for
3542 // previous animation "frames" to be handled.
3543 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003544 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003545 if (CC_UNLIKELY(err != NO_ERROR)) {
3546 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003547 // caller after a few seconds.
3548 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3549 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003550 mAnimTransactionPending = false;
3551 break;
3552 }
3553 }
3554 }
3555
chaviwca27f252018-02-06 16:46:39 -08003556 for (const DisplayState& display : displays) {
3557 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003558 }
3559
Marissa Walle2ffb422018-10-12 11:33:52 -07003560 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003561 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003562 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003563 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003564 // If the state doesn't require a traversal and there are callbacks, send them now
3565 if (!(clientStateFlags & eTraversalNeeded)) {
3566 mTransactionCompletedThread.sendCallbacks();
3567 }
3568 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003569
chaviw273171b2018-12-26 11:46:30 -08003570 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3571
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003572 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3573 // anyway. This can be used as a flush mechanism for previous async transactions.
3574 // Empty animation transaction can be used to simulate back-pressure, so also force a
3575 // transaction for empty animation transactions.
3576 if (transactionFlags == 0 &&
3577 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003578 transactionFlags = eTransactionNeeded;
3579 }
3580
Mathias Agopian386aa982011-11-07 21:58:03 -08003581 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003582 if (mInterceptor->isEnabled()) {
3583 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003584 }
Irvel468051e2016-06-13 16:44:44 -07003585
Mathias Agopian386aa982011-11-07 21:58:03 -08003586 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003587 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3588 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003589 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003590
3591 // if this is a synchronous transaction, wait for it to take effect
3592 // before returning.
3593 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003594 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003595 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003596 if (flags & eAnimation) {
3597 mAnimTransactionPending = true;
3598 }
chaviw95ef3c42019-02-14 10:55:09 -08003599
3600 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3601 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003602 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3603 if (CC_UNLIKELY(err != NO_ERROR)) {
3604 // just in case something goes wrong in SF, return to the
3605 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003606 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3607 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003608 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003609 break;
3610 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003611 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 }
3613}
3614
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003615uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3616 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3617 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003618
Mathias Agopiane57f2922012-08-09 16:29:12 -07003619 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003620 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3621
3622 const uint32_t what = s.what;
3623 if (what & DisplayState::eSurfaceChanged) {
3624 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3625 state.surface = s.surface;
3626 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003627 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003628 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003629 if (what & DisplayState::eLayerStackChanged) {
3630 if (state.layerStack != s.layerStack) {
3631 state.layerStack = s.layerStack;
3632 flags |= eDisplayTransactionNeeded;
3633 }
3634 }
3635 if (what & DisplayState::eDisplayProjectionChanged) {
3636 if (state.orientation != s.orientation) {
3637 state.orientation = s.orientation;
3638 flags |= eDisplayTransactionNeeded;
3639 }
3640 if (state.frame != s.frame) {
3641 state.frame = s.frame;
3642 flags |= eDisplayTransactionNeeded;
3643 }
3644 if (state.viewport != s.viewport) {
3645 state.viewport = s.viewport;
3646 flags |= eDisplayTransactionNeeded;
3647 }
3648 }
3649 if (what & DisplayState::eDisplaySizeChanged) {
3650 if (state.width != s.width) {
3651 state.width = s.width;
3652 flags |= eDisplayTransactionNeeded;
3653 }
3654 if (state.height != s.height) {
3655 state.height = s.height;
3656 flags |= eDisplayTransactionNeeded;
3657 }
3658 }
3659
Mathias Agopiane57f2922012-08-09 16:29:12 -07003660 return flags;
3661}
3662
Robert Carr14167e02019-02-13 13:50:55 -08003663bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003664 IPCThreadState* ipc = IPCThreadState::self();
3665 const int pid = ipc->getCallingPid();
3666 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003667 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003668 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003669 return false;
3670 }
3671 return true;
3672}
3673
Robert Carr14167e02019-02-13 13:50:55 -08003674uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3675 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003676 const layer_state_t& s = composerState.state;
3677 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3678
Mathias Agopian13127d82013-03-05 17:47:11 -08003679 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003680 if (layer == nullptr) {
3681 return 0;
3682 }
3683
chaviw8b3871a2017-11-01 17:41:01 -07003684 uint32_t flags = 0;
3685
Garfield Tan8a3083e2018-12-03 13:21:07 -08003686 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003687 bool geometryAppliesWithResize =
3688 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003689
3690 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3691 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003692 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003693 layer->pushPendingState();
3694 }
3695
chaviw8b3871a2017-11-01 17:41:01 -07003696 if (what & layer_state_t::ePositionChanged) {
3697 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3698 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003699 }
chaviw8b3871a2017-11-01 17:41:01 -07003700 }
3701 if (what & layer_state_t::eLayerChanged) {
3702 // NOTE: index needs to be calculated before we update the state
3703 const auto& p = layer->getParent();
3704 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003705 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003706 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003707 mCurrentState.layersSortedByZ.removeAt(idx);
3708 mCurrentState.layersSortedByZ.add(layer);
3709 // we need traversal (state changed)
3710 // AND transaction (list changed)
3711 flags |= eTransactionNeeded|eTraversalNeeded;
3712 }
chaviw8b3871a2017-11-01 17:41:01 -07003713 } else {
3714 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003715 flags |= eTransactionNeeded|eTraversalNeeded;
3716 }
3717 }
chaviw8b3871a2017-11-01 17:41:01 -07003718 }
3719 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003720 // NOTE: index needs to be calculated before we update the state
3721 const auto& p = layer->getParent();
3722 if (p == nullptr) {
3723 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3724 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3725 mCurrentState.layersSortedByZ.removeAt(idx);
3726 mCurrentState.layersSortedByZ.add(layer);
3727 // we need traversal (state changed)
3728 // AND transaction (list changed)
3729 flags |= eTransactionNeeded|eTraversalNeeded;
3730 }
3731 } else {
3732 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3733 flags |= eTransactionNeeded|eTraversalNeeded;
3734 }
chaviw8b3871a2017-11-01 17:41:01 -07003735 }
3736 }
3737 if (what & layer_state_t::eSizeChanged) {
3738 if (layer->setSize(s.w, s.h)) {
3739 flags |= eTraversalNeeded;
3740 }
3741 }
3742 if (what & layer_state_t::eAlphaChanged) {
3743 if (layer->setAlpha(s.alpha))
3744 flags |= eTraversalNeeded;
3745 }
3746 if (what & layer_state_t::eColorChanged) {
3747 if (layer->setColor(s.color))
3748 flags |= eTraversalNeeded;
3749 }
Peiyong Lind3788632018-09-18 16:01:31 -07003750 if (what & layer_state_t::eColorTransformChanged) {
3751 if (layer->setColorTransform(s.colorTransform)) {
3752 flags |= eTraversalNeeded;
3753 }
3754 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003755 if (what & layer_state_t::eBackgroundColorChanged) {
3756 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3757 flags |= eTraversalNeeded;
3758 }
3759 }
chaviw8b3871a2017-11-01 17:41:01 -07003760 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003761 // TODO: b/109894387
3762 //
3763 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3764 // rotation. To see the problem observe that if we have a square parent, and a child
3765 // of the same size, then we rotate the child 45 degrees around it's center, the child
3766 // must now be cropped to a non rectangular 8 sided region.
3767 //
3768 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3769 // private API, and the WindowManager only uses rotation in one case, which is on a top
3770 // level layer in which cropping is not an issue.
3771 //
3772 // However given that abuse of rotation matrices could lead to surfaces extending outside
3773 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3774 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3775 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003776 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003777 flags |= eTraversalNeeded;
3778 }
3779 if (what & layer_state_t::eTransparentRegionChanged) {
3780 if (layer->setTransparentRegionHint(s.transparentRegion))
3781 flags |= eTraversalNeeded;
3782 }
3783 if (what & layer_state_t::eFlagsChanged) {
3784 if (layer->setFlags(s.flags, s.mask))
3785 flags |= eTraversalNeeded;
3786 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003787 if (what & layer_state_t::eCropChanged_legacy) {
3788 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003789 flags |= eTraversalNeeded;
3790 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003791 if (what & layer_state_t::eCornerRadiusChanged) {
3792 if (layer->setCornerRadius(s.cornerRadius))
3793 flags |= eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 if (what & layer_state_t::eLayerStackChanged) {
3796 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3797 // We only allow setting layer stacks for top level layers,
3798 // everything else inherits layer stack from its parent.
3799 if (layer->hasParent()) {
3800 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3801 layer->getName().string());
3802 } else if (idx < 0) {
3803 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3804 "that also does not appear in the top level layer list. Something"
3805 " has gone wrong.", layer->getName().string());
3806 } else if (layer->setLayerStack(s.layerStack)) {
3807 mCurrentState.layersSortedByZ.removeAt(idx);
3808 mCurrentState.layersSortedByZ.add(layer);
3809 // we need traversal (state changed)
3810 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003811 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003812 }
3813 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003814 if (what & layer_state_t::eDeferTransaction_legacy) {
3815 if (s.barrierHandle_legacy != nullptr) {
3816 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3817 } else if (s.barrierGbp_legacy != nullptr) {
3818 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003819 if (authenticateSurfaceTextureLocked(gbp)) {
3820 const auto& otherLayer =
3821 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003822 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003823 } else {
3824 ALOGE("Attempt to defer transaction to to an"
3825 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003826 }
3827 }
chaviw8b3871a2017-11-01 17:41:01 -07003828 // We don't trigger a traversal here because if no other state is
3829 // changed, we don't want this to cause any more work
3830 }
3831 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003832 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003833 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003834 if (!hadParent) {
3835 mCurrentState.layersSortedByZ.remove(layer);
3836 }
chaviw8b3871a2017-11-01 17:41:01 -07003837 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003838 }
chaviw8b3871a2017-11-01 17:41:01 -07003839 }
3840 if (what & layer_state_t::eReparentChildren) {
3841 if (layer->reparentChildren(s.reparentHandle)) {
3842 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003843 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003844 }
chaviw8b3871a2017-11-01 17:41:01 -07003845 if (what & layer_state_t::eDetachChildren) {
3846 layer->detachChildren();
3847 }
3848 if (what & layer_state_t::eOverrideScalingModeChanged) {
3849 layer->setOverrideScalingMode(s.overrideScalingMode);
3850 // We don't trigger a traversal here because if no other state is
3851 // changed, we don't want this to cause any more work
3852 }
Marissa Wall61c58622018-07-18 10:12:20 -07003853 if (what & layer_state_t::eTransformChanged) {
3854 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3857 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eCropChanged) {
3861 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3862 }
Marissa Wall861616d2018-10-22 12:52:23 -07003863 if (what & layer_state_t::eFrameChanged) {
3864 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3865 }
Marissa Wall61c58622018-07-18 10:12:20 -07003866 if (what & layer_state_t::eAcquireFenceChanged) {
3867 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3868 }
3869 if (what & layer_state_t::eDataspaceChanged) {
3870 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3871 }
3872 if (what & layer_state_t::eHdrMetadataChanged) {
3873 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3874 }
3875 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3876 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3877 }
3878 if (what & layer_state_t::eApiChanged) {
3879 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3880 }
3881 if (what & layer_state_t::eSidebandStreamChanged) {
3882 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3883 }
Robert Carr720e5062018-07-30 17:45:14 -07003884 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003885 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3886 layer->setInputInfo(s.inputInfo);
3887 flags |= eTraversalNeeded;
3888 } else {
3889 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3890 }
Robert Carr720e5062018-07-30 17:45:14 -07003891 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003892 if (what & layer_state_t::eMetadataChanged) {
3893 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3894 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003895 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3896 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3897 flags |= eTraversalNeeded;
3898 }
3899 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003900 std::vector<sp<CallbackHandle>> callbackHandles;
3901 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3902 mTransactionCompletedThread.run();
3903 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3904 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3905 }
3906 }
Marissa Wall73411622019-01-25 10:45:41 -08003907
3908 if (what & layer_state_t::eBufferChanged) {
3909 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3910 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3911 s.buffer);
3912 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003913 if (what & layer_state_t::eCachedBufferChanged) {
3914 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003915 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3916 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003917 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3918 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003919 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3920 // Do not put anything that updates layer state or modifies flags after
3921 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003922 return flags;
3923}
3924
chaviw273171b2018-12-26 11:46:30 -08003925uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3926 uint32_t flags = 0;
3927 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3928 flags |= eTraversalNeeded;
3929 }
3930
chaviwa911b102019-02-14 10:18:33 -08003931 if (inputWindowCommands.syncInputWindows) {
3932 flags |= eTraversalNeeded;
3933 }
3934
Vishnu Nairec0ab382019-02-13 15:32:56 -08003935 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003936 return flags;
3937}
3938
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003939status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3940 uint32_t h, PixelFormat format, uint32_t flags,
3941 LayerMetadata metadata, sp<IBinder>* handle,
3942 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003943 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003944 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003945 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003946 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003947 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003948
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003949 status_t result = NO_ERROR;
3950
3951 sp<Layer> layer;
3952
Cody Northropbc755282017-03-31 12:00:08 -06003953 String8 uniqueName = getUniqueLayerName(name);
3954
Mathias Agopian3165cc22012-08-08 19:42:09 -07003955 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003956 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003957 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3958 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003959
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003960 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003961 case ISurfaceComposerClient::eFXSurfaceBufferState:
3962 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3963 break;
chaviw13fdc492017-06-27 12:40:18 -07003964 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003965 // check if buffer size is set for color layer.
3966 if (w > 0 || h > 0) {
3967 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3968 int(w), int(h));
3969 return BAD_VALUE;
3970 }
3971
chaviw13fdc492017-06-27 12:40:18 -07003972 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003973 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003974 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003975 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003976 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003977 // check if buffer size is set for container layer.
3978 if (w > 0 || h > 0) {
3979 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3980 int(w), int(h));
3981 return BAD_VALUE;
3982 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003983 result = createContainerLayer(client,
3984 uniqueName, w, h, flags,
3985 handle, &layer);
3986 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003987 default:
3988 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 break;
3990 }
3991
Dan Stoza7d89d062015-04-30 13:29:25 -07003992 if (result != NO_ERROR) {
3993 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003995
Chia-I Wuab0c3192017-08-01 11:29:00 -07003996 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3997 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003998 if (metadata.has(METADATA_WINDOW_TYPE)) {
3999 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4000 if (windowType == 441731) {
4001 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4002 layer->setPrimaryDisplayOnly();
4003 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004004 }
4005
Evan Roskyef876c92019-01-25 17:46:06 -08004006 layer->setMetadata(metadata);
Albert Chaulk479c60c2017-01-27 14:21:34 -05004007
Robert Carrb89ea9d2018-12-10 13:01:14 -08004008 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4009 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4010 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004011 if (result != NO_ERROR) {
4012 return result;
4013 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004014 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004015
4016 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018}
4019
Cody Northropbc755282017-03-31 12:00:08 -06004020String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4021{
4022 bool matchFound = true;
4023 uint32_t dupeCounter = 0;
4024
4025 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4026 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4027
Dan Stoza436ccf32018-06-21 12:10:12 -07004028 // Grab the state lock since we're accessing mCurrentState
4029 Mutex::Autolock lock(mStateLock);
4030
Cody Northropbc755282017-03-31 12:00:08 -06004031 // Loop over layers until we're sure there is no matching name
4032 while (matchFound) {
4033 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004034 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004035 if (layer->getName() == uniqueName) {
4036 matchFound = true;
4037 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4038 }
4039 });
4040 }
4041
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004042 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4043 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004044
4045 return uniqueName;
4046}
4047
Marissa Wallfd668622018-05-10 10:21:13 -07004048status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4049 uint32_t w, uint32_t h, uint32_t flags,
4050 PixelFormat& format, sp<IBinder>* handle,
4051 sp<IGraphicBufferProducer>* gbp,
4052 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004054 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 case PIXEL_FORMAT_TRANSPARENT:
4056 case PIXEL_FORMAT_TRANSLUCENT:
4057 format = PIXEL_FORMAT_RGBA_8888;
4058 break;
4059 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004060 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 break;
4062 }
4063
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004064 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004065 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004066 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004067 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004068 *handle = layer->getHandle();
4069 *gbp = layer->getProducer();
4070 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072
Marissa Wallfd668622018-05-10 10:21:13 -07004073 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Marissa Wall61c58622018-07-18 10:12:20 -07004077status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4078 uint32_t w, uint32_t h, uint32_t flags,
4079 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004080 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004081 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004082 *handle = layer->getHandle();
4083 *outLayer = layer;
4084
4085 return NO_ERROR;
4086}
4087
chaviw13fdc492017-06-27 12:40:18 -07004088status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004090 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004092 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004093 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004095}
4096
Robert Carr6b3f6c52018-08-13 13:05:17 -07004097status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4098 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4099 sp<IBinder>* handle, sp<Layer>* outLayer)
4100{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004101 *outLayer =
4102 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004103 *handle = (*outLayer)->getHandle();
4104 return NO_ERROR;
4105}
4106
4107
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004108void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004109 mLayersPendingRemoval.add(layer);
4110 mLayersRemoved = true;
4111 setTransactionFlags(eTransactionNeeded);
4112}
4113
Robert Carr695d5282018-12-18 15:27:58 -08004114void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004115{
Robert Carr2e102c92018-10-23 12:11:15 -07004116 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004117 // If a layer has a parent, we allow it to out-live it's handle
4118 // with the idea that the parent holds a reference and will eventually
4119 // be cleaned up. However no one cleans up the top-level so we do so
4120 // here.
4121 if (layer->getParent() == nullptr) {
4122 mCurrentState.layersSortedByZ.remove(layer);
4123 }
4124 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004125 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004126}
4127
Mathias Agopianb60314a2012-04-10 22:09:54 -07004128// ---------------------------------------------------------------------------
4129
Andy McFadden13a082e2012-08-24 10:16:42 -07004130void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004131 const auto display = getDefaultDisplayDeviceLocked();
4132 if (!display) return;
4133
4134 const sp<IBinder> token = display->getDisplayToken().promote();
4135 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004136
Jesse Hall01e29052013-02-19 16:13:35 -08004137 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004138 Vector<ComposerState> state;
4139 Vector<DisplayState> displays;
4140 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004141 d.what = DisplayState::eDisplayProjectionChanged |
4142 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004143 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004144 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004145 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004146 d.frame.makeInvalid();
4147 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004148 d.width = 0;
4149 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004150 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004151 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004152
Dominik Laskowskie9774092018-12-11 10:04:24 -08004153 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004154
Dominik Laskowski83b88212018-12-11 13:34:06 -08004155 const nsecs_t vsyncPeriod = getVsyncPeriod();
4156 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004157
Brian Andersond0010582017-03-07 13:20:31 -08004158 // Use phase of 0 since phase is not known.
4159 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004160 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004161 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004162}
4163
4164void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004165 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004166 postMessageAsync(
4167 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004168}
4169
Dominik Laskowskie9774092018-12-11 10:04:24 -08004170void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004171 if (display->isVirtual()) {
4172 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004173 return;
4174 }
4175
Dominik Laskowski075d3172018-05-24 15:50:06 -07004176 const auto displayId = display->getId();
4177 LOG_ALWAYS_FATAL_IF(!displayId);
4178
Dominik Laskowski34157762018-10-31 13:07:19 -07004179 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004180
4181 int currentMode = display->getPowerMode();
4182 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004183 return;
4184 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004186 display->setPowerMode(mode);
4187
Lloyd Pique4dccc412018-01-22 17:21:36 -08004188 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004189 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004190 }
4191
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004192 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004193 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004194 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004196 mScheduler->onScreenAcquired(mAppConnectionHandle);
4197 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004198 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004199
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004200 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004201 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004202 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004203
4204 struct sched_param param = {0};
4205 param.sched_priority = 1;
4206 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4207 ALOGW("Couldn't set SCHED_FIFO on display on");
4208 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004209 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004210 // Turn off the display
4211 struct sched_param param = {0};
4212 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4213 ALOGW("Couldn't set SCHED_OTHER on display off");
4214 }
4215
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004216 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004217 mScheduler->disableHardwareVsync(true);
4218 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004219 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004220
Dominik Laskowski075d3172018-05-24 15:50:06 -07004221 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004222 mVisibleRegionsDirty = true;
4223 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004224 } else if (mode == HWC_POWER_MODE_DOZE ||
4225 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004226 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004227 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004228 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004229 mScheduler->onScreenAcquired(mAppConnectionHandle);
4230 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004231 }
4232 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4233 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004234 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004235 mScheduler->disableHardwareVsync(true);
4236 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004237 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004238 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004239 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004240 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004244 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004245 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004246 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004247 // Update refresh rate stats.
4248 mRefreshRateStats->setPowerMode(mode);
4249 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004250 }
4251
Dominik Laskowski34157762018-10-31 13:07:19 -07004252 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004253}
4254
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004255void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004256 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004257 const auto display = getDisplayDevice(displayToken);
4258 if (!display) {
4259 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4260 displayToken.get());
4261 } else if (display->isVirtual()) {
4262 ALOGW("Attempt to set power mode %d for virtual display", mode);
4263 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004264 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004265 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004266 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004267}
4268
4269// ---------------------------------------------------------------------------
4270
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4272 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004273 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004274
Mathias Agopianbd115332013-04-18 16:41:04 -07004275 IPCThreadState* ipc = IPCThreadState::self();
4276 const int pid = ipc->getCallingPid();
4277 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004278
Mathias Agopianbd115332013-04-18 16:41:04 -07004279 if ((uid != AID_SHELL) &&
4280 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004281 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4282 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004284 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004285 // (this would indicate SF is stuck, but we want to be able to
4286 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004287 status_t err = mStateLock.timedLock(s2ns(1));
4288 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004289 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004290 StringAppendF(&result,
4291 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4292 "(no locks held)\n",
4293 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004294 }
4295
Dominik Laskowskic2867142019-01-21 11:33:38 -08004296 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004297
Dominik Laskowskic2867142019-01-21 11:33:38 -08004298 static const std::unordered_map<std::string, Dumper> dumpers = {
4299 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4300 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4301 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004302 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004303 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004304 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004305 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4306 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004307 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4308 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4309 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4310 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4311 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4312 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004313 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004314 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4315 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004316
Dominik Laskowskic2867142019-01-21 11:33:38 -08004317 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318
Dominik Laskowskic2867142019-01-21 11:33:38 -08004319 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4320 (it->second)(args, asProto, result);
4321 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004322 if (asProto) {
4323 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4324 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4325 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004327 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004328 }
4329
Mathias Agopian9795c422009-08-26 16:36:26 -07004330 if (locked) {
4331 mStateLock.unlock();
4332 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004333 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004334 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004335 return NO_ERROR;
4336}
4337
Dominik Laskowskic2867142019-01-21 11:33:38 -08004338void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339 mCurrentState.traverseInZOrder(
4340 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004341}
4342
Dominik Laskowskic2867142019-01-21 11:33:38 -08004343void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004344 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004345
Dominik Laskowskic2867142019-01-21 11:33:38 -08004346 if (args.size() > 1) {
4347 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004348 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004349 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004350 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004351 }
Robert Carr2047fae2016-11-28 14:09:09 -08004352 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004353 } else {
4354 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355 }
4356}
4357
Dominik Laskowskic2867142019-01-21 11:33:38 -08004358void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004359 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004361 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004362 }
Robert Carr2047fae2016-11-28 14:09:09 -08004363 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004364
Svetoslavd85084b2014-03-20 10:28:31 -07004365 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004366}
4367
Dominik Laskowskic2867142019-01-21 11:33:38 -08004368void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4369 mTimeStats->parseArgs(asProto, args, result);
4370}
4371
Jamie Gennis6547ff42013-07-16 20:12:42 -07004372// This should only be called from the main thread. Otherwise it would need
4373// the lock and should use mCurrentState rather than mDrawingState.
4374void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004375 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004376 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004377 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004378
4379 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4380}
4381
Yiwei Zhang5434a782018-12-05 18:06:32 -08004382void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004383 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004384
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004385 if (isLayerTripleBufferingDisabled())
4386 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004387
Yiwei Zhang5434a782018-12-05 18:06:32 -08004388 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4389 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4390 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4391 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4392 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4393 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004394 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004395}
4396
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004397void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004398 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004399 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004400 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004401 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004402
Ady Abraham97d04232019-03-05 19:48:12 -08004403 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004404 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4405 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004406 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004407}
4408
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4410 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004411 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4412 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004413 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004414 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004416 }
David Sodman4a36e932017-11-07 14:29:47 -08004417 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004418 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004419 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4421 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004422}
4423
Dan Stozae77c7662016-05-13 11:37:28 -07004424void SurfaceFlinger::recordBufferingStats(const char* layerName,
4425 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004426 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4427 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004428 for (const auto& segment : history) {
4429 if (!segment.usedThirdBuffer) {
4430 stats.twoBufferTime += segment.totalTime;
4431 }
4432 if (segment.occupancyAverage < 1.0f) {
4433 stats.doubleBufferedTime += segment.totalTime;
4434 } else if (segment.occupancyAverage < 2.0f) {
4435 stats.tripleBufferedTime += segment.totalTime;
4436 }
4437 ++stats.numSegments;
4438 stats.totalTime += segment.totalTime;
4439 }
4440}
4441
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4443 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004444
4445 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4446 const size_t count = currentLayers.size();
4447 for (size_t i=0 ; i<count ; i++) {
4448 currentLayers[i]->dumpFrameEvents(result);
4449 }
4450}
4451
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004453 result.append("Buffering stats:\n");
4454 result.append(" [Layer name] <Active time> <Two buffer> "
4455 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004456 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004457 typedef std::tuple<std::string, float, float, float> BufferTuple;
4458 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004459 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004460 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004461 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004462 if (stats.numSegments == 0) {
4463 continue;
4464 }
4465 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4466 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4467 stats.totalTime;
4468 float doubleBufferRatio = static_cast<float>(
4469 stats.doubleBufferedTime) / stats.totalTime;
4470 float tripleBufferRatio = static_cast<float>(
4471 stats.tripleBufferedTime) / stats.totalTime;
4472 sorted.insert({activeTime, {name, twoBufferRatio,
4473 doubleBufferRatio, tripleBufferRatio}});
4474 }
4475 for (const auto& sortedPair : sorted) {
4476 float activeTime = sortedPair.first;
4477 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4479 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004480 }
4481 result.append("\n");
4482}
4483
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004485 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004486 const auto displayId = display->getId();
4487 if (!displayId) {
4488 continue;
4489 }
4490 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004491 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004492 continue;
4493 }
4494
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495 StringAppendF(&result,
4496 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4497 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004498 uint8_t port;
4499 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004500 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004501 result.append("no identification data\n");
4502 continue;
4503 }
4504
4505 if (!isEdid(data)) {
4506 result.append("unknown identification data: ");
4507 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004509 }
4510 result.append("\n");
4511 continue;
4512 }
4513
4514 const auto edid = parseEdid(data);
4515 if (!edid) {
4516 result.append("invalid EDID: ");
4517 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004519 }
4520 result.append("\n");
4521 continue;
4522 }
4523
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004525 result.append(edid->displayName.data(), edid->displayName.length());
4526 result.append("\"\n");
4527 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004528}
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4531 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4532 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4533 StringAppendF(&result, "DisplayColorSetting: %s\n",
4534 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004535
4536 // TODO: print out if wide-color mode is active or not
4537
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004538 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004539 const auto displayId = display->getId();
4540 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004541 continue;
4542 }
4543
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004545 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004546 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004548 }
4549
Lloyd Pique32cbe282018-10-19 13:09:22 -07004550 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, " Current color mode: %s (%d)\n",
4552 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004553 }
4554 result.append("\n");
4555}
4556
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004557LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004558 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004559 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4560 const State& state = useDrawing ? mDrawingState : mCurrentState;
4561 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004562 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004563 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004564 });
4565
4566 return layersProto;
4567}
4568
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004569LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4570 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004571 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004572
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004573 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004574 resolution->set_w(displayDevice->getWidth());
4575 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004576
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004577 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004578 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004579
Lloyd Pique32cbe282018-10-19 13:09:22 -07004580 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4581 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4582 layersProto.set_global_transform(displayState.orientation);
4583
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004584 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004586 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004587 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004588 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004589 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004590 }
4591 });
4592
4593 return layersProto;
4594}
4595
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4597 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004598 Colorizer colorizer(colorize);
4599
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004600 // figure out if we're stuck somewhere
4601 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004602 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004603 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4604
4605 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004606 * Dump library configuration.
4607 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608
4609 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004610 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004611 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004612 appendSfConfigString(result);
4613 appendUiConfigString(result);
4614 appendGuiConfigString(result);
4615 result.append("\n");
4616
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004617 result.append("\nDisplay identification data:\n");
4618 dumpDisplayIdentificationData(result);
4619
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004620 result.append("\nWide-Color information:\n");
4621 dumpWideColorInfo(result);
4622
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004623 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004624 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004625 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004626 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004627 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004628
Andy McFadden41d67d72014-04-25 16:58:34 -07004629 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004630 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004631 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004632 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004633 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004634
Dan Stozab90cf072015-03-05 11:05:59 -08004635 dumpStaticScreenStats(result);
4636 result.append("\n");
4637
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004639
Dan Stozae77c7662016-05-13 11:37:28 -07004640 dumpBufferingStats(result);
4641
Andy McFadden4803b742012-09-24 19:07:20 -07004642 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643 * Dump the visible layer list
4644 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004645 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4647 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4648 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004649 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004650
Chia-I Wu2f884132018-09-13 15:17:58 -07004651 {
4652 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4653 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004655 result.append("\n");
4656 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004657
4658 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004659 * Dump Display state
4660 */
4661
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004662 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004664 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004665 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004666 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004667 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004668 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004669
4670 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 * Dump SurfaceFlinger global state
4672 */
4673
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004674 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004675 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004678 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679
Dominik Laskowski075d3172018-05-24 15:50:06 -07004680 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004681 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4682 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4684 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004685 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004686 StringAppendF(&result,
4687 " transaction-flags : %08x\n"
4688 " gpu_to_cpu_unsupported : %d\n",
4689 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004690
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004691 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004692 displayId && getHwComposer().isConnected(*displayId)) {
4693 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 StringAppendF(&result,
4695 " refresh-rate : %f fps\n"
4696 " x-dpi : %f\n"
4697 " y-dpi : %f\n",
4698 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4699 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004700 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703
Dan Stozae22aec72016-08-01 13:20:59 -07004704 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004705 * Tracing state
4706 */
4707 mTracing.dump(result);
4708 result.append("\n");
4709
4710 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004711 * HWC layer minidump
4712 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004713 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004714 const auto displayId = display->getId();
4715 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004716 continue;
4717 }
4718
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004720 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004721 const sp<DisplayDevice> displayDevice = display;
4722 mCurrentState.traverseInZOrder(
4723 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004724 result.append("\n");
4725 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726
4727 /*
4728 * Dump HWComposer state
4729 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004730 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004731 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004732 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004733 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004734 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004735 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004736
4737 /*
4738 * Dump gralloc state
4739 */
4740 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4741 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004742
4743 /*
4744 * Dump VrFlinger state if in use.
4745 */
4746 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4747 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004749 result.append("\n");
4750 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004751
4752 /**
4753 * Scheduler dump state.
4754 */
Ana Krulecc2870422019-01-29 19:00:58 -08004755 result.append("\nScheduler state:\n");
4756 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004757 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004758 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759}
4760
Dominik Laskowski075d3172018-05-24 15:50:06 -07004761const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004762 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004763 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004764 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004765 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004766 }
4767 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004768
Dominik Laskowski34157762018-10-31 13:07:19 -07004769 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004770 static const Vector<sp<Layer>> empty;
4771 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004772}
4773
Chia-I Wu28f320b2018-05-03 11:02:56 -07004774void SurfaceFlinger::updateColorMatrixLocked() {
4775 mat4 colorMatrix;
4776 if (mGlobalSaturationFactor != 1.0f) {
4777 // Rec.709 luma coefficients
4778 float3 luminance{0.213f, 0.715f, 0.072f};
4779 luminance *= 1.0f - mGlobalSaturationFactor;
4780 mat4 saturationMatrix = mat4(
4781 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4782 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4783 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4784 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4785 );
4786 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4787 } else {
4788 colorMatrix = mClientColorMatrix * mDaltonizer();
4789 }
4790
4791 if (mCurrentState.colorMatrix != colorMatrix) {
4792 mCurrentState.colorMatrix = colorMatrix;
4793 mCurrentState.colorMatrixChanged = true;
4794 setTransactionFlags(eTransactionNeeded);
4795 }
4796}
4797
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004798status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799#pragma clang diagnostic push
4800#pragma clang diagnostic error "-Wswitch-enum"
4801 switch (static_cast<ISurfaceComposerTag>(code)) {
4802 // These methods should at minimum make sure that the client requested
4803 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004804 case BOOT_FINISHED:
4805 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806 case CREATE_DISPLAY:
4807 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004808 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004809 case GET_ACTIVE_COLOR_MODE:
4810 case GET_ANIMATION_FRAME_STATS:
4811 case GET_HDR_CAPABILITIES:
4812 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004813 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004814 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004816 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004817 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004818 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004819 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4820 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004821 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4822 IPCThreadState* ipc = IPCThreadState::self();
4823 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4824 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004825 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004826 }
Robert Carr1db73f62016-12-21 12:58:51 -08004827 return OK;
4828 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004829 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004830 IPCThreadState* ipc = IPCThreadState::self();
4831 const int pid = ipc->getCallingPid();
4832 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4834 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004835 return PERMISSION_DENIED;
4836 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004837 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 // Used by apps to hook Choreographer to SurfaceFlinger.
4840 case CREATE_DISPLAY_EVENT_CONNECTION:
4841 // The following calls are currently used by clients that do not
4842 // request necessary permissions. However, they do not expose any secret
4843 // information, so it is OK to pass them.
4844 case AUTHENTICATE_SURFACE:
4845 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004846 case GET_PHYSICAL_DISPLAY_IDS:
4847 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004849 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850 case GET_DISPLAY_CONFIGS:
4851 case GET_DISPLAY_STATS:
4852 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4853 // Calling setTransactionState is safe, because you need to have been
4854 // granted a reference to Client* and Handle* to do anything with it.
4855 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004856 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004857 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004858 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004859 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004860 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 return OK;
4862 }
4863 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004864 case CAPTURE_SCREEN:
4865 case ADD_REGION_SAMPLING_LISTENER:
4866 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004867 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004868 IPCThreadState* ipc = IPCThreadState::self();
4869 const int pid = ipc->getCallingPid();
4870 const int uid = ipc->getCallingUid();
4871 if ((uid != AID_GRAPHICS) &&
4872 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4873 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4874 return PERMISSION_DENIED;
4875 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876 return OK;
4877 }
4878 // The following codes are deprecated and should never be allowed to access SF.
4879 case CONNECT_DISPLAY_UNUSED:
4880 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4881 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4882 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885
4886 // These codes are used for the IBinder protocol to either interrogate the recipient
4887 // side of the transaction for its canonical interface descriptor or to dump its state.
4888 // We let them pass by default.
4889 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4890 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4891 code == IBinder::SYSPROPS_TRANSACTION) {
4892 return OK;
4893 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08004894 // Numbers from 1000 to 1032 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004895 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08004896 if (code >= 1000 && code <= 1032) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4898 return OK;
4899 }
4900 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4901 return PERMISSION_DENIED;
4902#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004903}
4904
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4906 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004907 status_t credentialCheck = CheckTransactCodeCredentials(code);
4908 if (credentialCheck != OK) {
4909 return credentialCheck;
4910 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004911
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4913 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004914 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004915 IPCThreadState* ipc = IPCThreadState::self();
4916 const int uid = ipc->getCallingUid();
4917 if (CC_UNLIKELY(uid != AID_SYSTEM
4918 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004919 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004920 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004921 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 return PERMISSION_DENIED;
4923 }
4924 int n;
4925 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004926 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004927 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 return NO_ERROR;
4929 case 1002: // SHOW_UPDATES
4930 n = data.readInt32();
4931 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004932 invalidateHwcGeometry();
4933 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004936 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004937 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004939 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004940 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004941 setTransactionFlags(
4942 eTransactionNeeded|
4943 eDisplayTransactionNeeded|
4944 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004945 return NO_ERROR;
4946 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004947 case 1006:{ // send empty update
4948 signalRefresh();
4949 return NO_ERROR;
4950 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004951 case 1008: // toggle use of hw composer
4952 n = data.readInt32();
4953 mDebugDisableHWC = n ? 1 : 0;
4954 invalidateHwcGeometry();
4955 repaintEverything();
4956 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004957 case 1009: // toggle use of transform hint
4958 n = data.readInt32();
4959 mDebugDisableTransformHint = n ? 1 : 0;
4960 invalidateHwcGeometry();
4961 repaintEverything();
4962 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004964 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 reply->writeInt32(0);
4966 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004967 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004968 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004969 return NO_ERROR;
4970 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004971 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004972 if (!display) {
4973 return NAME_NOT_FOUND;
4974 }
4975
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004976 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004977 return NO_ERROR;
4978 }
4979 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004980 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004981 // daltonize
4982 n = data.readInt32();
4983 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004984 case 1:
4985 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4986 break;
4987 case 2:
4988 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4989 break;
4990 case 3:
4991 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4992 break;
4993 default:
4994 mDaltonizer.setType(ColorBlindnessType::None);
4995 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004996 }
4997 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004998 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004999 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005000 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005001 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005002
5003 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005004 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005006 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005007 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005008 // apply a color matrix
5009 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005010 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005011 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005012 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005013 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005014 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005015 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005016 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005017 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005018 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005019 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005020
5021 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5022 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005023 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005024 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5025 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5026 }
5027
Chia-I Wu28f320b2018-05-03 11:02:56 -07005028 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005029 return NO_ERROR;
5030 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005031 // This is an experimental interface
5032 // Needs to be shifted to proper binder interface when we productize
5033 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005034 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005035 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005036 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005037 return NO_ERROR;
5038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005039 case 1017: {
5040 n = data.readInt32();
5041 mForceFullDamage = static_cast<bool>(n);
5042 return NO_ERROR;
5043 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005044 case 1018: { // Modify Choreographer's phase offset
5045 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005046 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005047 return NO_ERROR;
5048 }
5049 case 1019: { // Modify SurfaceFlinger's phase offset
5050 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005051 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005052 return NO_ERROR;
5053 }
Irvel468051e2016-06-13 16:44:44 -07005054 case 1020: { // Layer updates interceptor
5055 n = data.readInt32();
5056 if (n) {
5057 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005058 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005059 }
5060 else{
5061 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005062 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005063 }
5064 return NO_ERROR;
5065 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005066 case 1021: { // Disable HWC virtual displays
5067 n = data.readInt32();
5068 mUseHwcVirtualDisplays = !n;
5069 return NO_ERROR;
5070 }
Romain Guy0147a172017-06-01 13:53:56 -07005071 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005073 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005074
Chia-I Wu28f320b2018-05-03 11:02:56 -07005075 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005076 return NO_ERROR;
5077 }
Romain Guy54f154a2017-10-24 21:40:32 +01005078 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005079 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005080 invalidateHwcGeometry();
5081 repaintEverything();
5082 return NO_ERROR;
5083 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005084 // Deprecate, use 1030 to check whether the device is color managed.
5085 case 1024: {
5086 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005087 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005088 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005089 n = data.readInt32();
5090 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005091 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005092 mTracing.enable();
5093 doTracing("tracing.enable");
5094 reply->writeInt32(NO_ERROR);
5095 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005096 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005097 status_t err = mTracing.disable();
5098 reply->writeInt32(err);
5099 }
5100 return NO_ERROR;
5101 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005102 case 1026: { // Get layer tracing status
5103 reply->writeBool(mTracing.isEnabled());
5104 return NO_ERROR;
5105 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005106 // Is a DisplayColorSetting supported?
5107 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005108 const auto display = getDefaultDisplayDevice();
5109 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005110 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005111 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005112
5113 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5114 switch (setting) {
5115 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005116 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005117 break;
5118 case DisplayColorSetting::UNMANAGED:
5119 reply->writeBool(true);
5120 break;
5121 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005122 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005123 break;
5124 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005125 reply->writeBool(
5126 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 break;
5128 }
5129 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005130 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005131 // Is VrFlinger active?
5132 case 1028: {
5133 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005134 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005135 return NO_ERROR;
5136 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005137 // Is device color managed?
5138 case 1030: {
5139 reply->writeBool(useColorManagement);
5140 return NO_ERROR;
5141 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005142 // Override default composition data space
5143 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5144 // && adb shell stop zygote && adb shell start zygote
5145 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5146 // adb shell stop zygote && adb shell start zygote
5147 case 1031: {
5148 Mutex::Autolock _l(mStateLock);
5149 n = data.readInt32();
5150 if (n) {
5151 n = data.readInt32();
5152 if (n) {
5153 Dataspace dataspace = static_cast<Dataspace>(n);
5154 if (!validateCompositionDataspace(dataspace)) {
5155 return BAD_VALUE;
5156 }
5157 mDefaultCompositionDataspace = dataspace;
5158 }
5159 n = data.readInt32();
5160 if (n) {
5161 Dataspace dataspace = static_cast<Dataspace>(n);
5162 if (!validateCompositionDataspace(dataspace)) {
5163 return BAD_VALUE;
5164 }
5165 mWideColorGamutCompositionDataspace = dataspace;
5166 }
5167 } else {
5168 // restore composition data space.
5169 mDefaultCompositionDataspace = defaultCompositionDataspace;
5170 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5171 }
5172 return NO_ERROR;
5173 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005174 case 1032: {
5175 n = data.readInt32();
5176 mDebugEnableProtectedContent = n;
5177 return NO_ERROR;
5178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005179 }
5180 }
5181 return err;
5182}
5183
Steven Thomas6d8110b2017-08-31 18:24:21 -07005184void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005185 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005186 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005187}
5188
Ana Krulec7d1d6832018-12-27 11:10:09 -08005189void SurfaceFlinger::repaintEverythingForHWC() {
5190 mRepaintEverything = true;
5191 mEventQueue->invalidateForHWC();
5192}
5193
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005194// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5195class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005196public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005197 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5198 ~WindowDisconnector() {
5199 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005200 }
5201
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202private:
5203 ANativeWindow* mWindow;
5204 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005205};
5206
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005207status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005208 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5209 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005210 uint32_t reqWidth, uint32_t reqHeight,
5211 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005212 ISurfaceComposer::Rotation rotation,
5213 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005214 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005215
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005216 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005217
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005218 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5219
Chia-I Wu20261cb2018-08-23 12:55:44 -07005220 sp<DisplayDevice> display;
5221 {
5222 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005223
Chia-I Wu20261cb2018-08-23 12:55:44 -07005224 display = getDisplayDeviceLocked(displayToken);
5225 if (!display) return BAD_VALUE;
5226
Chia-I Wucb023152018-08-28 12:57:23 -07005227 // set the requested width/height to the logical display viewport size
5228 // by default
5229 if (reqWidth == 0 || reqHeight == 0) {
5230 reqWidth = uint32_t(display->getViewport().width());
5231 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005232 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005233 }
5234
Peiyong Lin0e003c92018-09-17 11:09:51 -07005235 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005236 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005237
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005238 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5239 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005240 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5241 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005242}
5243
5244status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005245 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5246 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005247 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005248 ATRACE_CALL();
5249
5250 class LayerRenderArea : public RenderArea {
5251 public:
Robert Carr578038f2018-03-09 12:25:24 -08005252 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005253 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5254 bool childrenOnly)
5255 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005256 mLayer(layer),
5257 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005258 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005259 mFlinger(flinger),
5260 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005261 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005262 Rect getBounds() const override {
5263 const Layer::State& layerState(mLayer->getDrawingState());
5264 return mLayer->getBufferSize(layerState);
5265 }
Marissa Wall61c58622018-07-18 10:12:20 -07005266 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005267 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005268 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005269 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005270 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005271 }
chaviwa76b2712017-09-20 12:02:26 -07005272 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005273 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005274 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005275 Rect getSourceCrop() const override {
5276 if (mCrop.isEmpty()) {
5277 return getBounds();
5278 } else {
5279 return mCrop;
5280 }
5281 }
Robert Carr578038f2018-03-09 12:25:24 -08005282 class ReparentForDrawing {
5283 public:
5284 const sp<Layer>& oldParent;
5285 const sp<Layer>& newParent;
5286
Vishnu Nair4351ad52019-02-11 14:13:02 -08005287 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5288 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005289 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005290 // Compute and cache the bounds for the new parent layer.
5291 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005292 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005293 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005294 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005295 };
5296
5297 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005298 const Rect sourceCrop = getSourceCrop();
5299 // no need to check rotation because there is none
5300 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5301 sourceCrop.height() != getReqHeight();
5302
Robert Carr578038f2018-03-09 12:25:24 -08005303 if (!mChildrenOnly) {
5304 mTransform = mLayer->getTransform().inverse();
5305 drawLayers();
5306 } else {
5307 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005308 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005309 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5310 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005311
Vishnu Nair4351ad52019-02-11 14:13:02 -08005312 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005313 drawLayers();
5314 }
5315 }
chaviwa76b2712017-09-20 12:02:26 -07005316
chaviwa76b2712017-09-20 12:02:26 -07005317 private:
chaviw7206d492017-11-10 16:16:12 -08005318 const sp<Layer> mLayer;
5319 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005320
5321 // In the "childrenOnly" case we reparent the children to a screenshot
5322 // layer which has no properties set and which does not draw.
5323 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005324 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005325 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005326
5327 SurfaceFlinger* mFlinger;
5328 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005329 };
5330
5331 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5332 auto parent = layerHandle->owner.promote();
5333
Robert Carr2e102c92018-10-23 12:11:15 -07005334 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005335 ALOGE("captureLayers called with a removed parent");
5336 return NAME_NOT_FOUND;
5337 }
5338
Robert Carr578038f2018-03-09 12:25:24 -08005339 const int uid = IPCThreadState::self()->getCallingUid();
5340 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005341 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005342 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5343 return PERMISSION_DENIED;
5344 }
5345
chaviw7206d492017-11-10 16:16:12 -08005346 Rect crop(sourceCrop);
5347 if (sourceCrop.width() <= 0) {
5348 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005349 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005350 }
5351
5352 if (sourceCrop.height() <= 0) {
5353 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005354 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005355 }
5356
5357 int32_t reqWidth = crop.width() * frameScale;
5358 int32_t reqHeight = crop.height() * frameScale;
5359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 // really small crop or frameScale
5361 if (reqWidth <= 0) {
5362 reqWidth = 1;
5363 }
5364 if (reqHeight <= 0) {
5365 reqHeight = 1;
5366 }
5367
Peiyong Lin0e003c92018-09-17 11:09:51 -07005368 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005369
Robert Carr578038f2018-03-09 12:25:24 -08005370 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005371 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5372 if (!layer->isVisible()) {
5373 return;
Robert Carr578038f2018-03-09 12:25:24 -08005374 } else if (childrenOnly && layer == parent.get()) {
5375 return;
chaviwa76b2712017-09-20 12:02:26 -07005376 }
5377 visitor(layer);
5378 });
5379 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005380 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005381}
5382
5383status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5384 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005385 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005386 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005387 bool useIdentityTransform) {
5388 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005389
Peiyong Lin0e003c92018-09-17 11:09:51 -07005390 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005391 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5392 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005393 *outBuffer =
5394 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5395 static_cast<android_pixel_format>(reqPixelFormat), 1,
5396 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005398 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005399}
5400
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005401status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5402 TraverseLayersFunction traverseLayers,
5403 const sp<GraphicBuffer>& buffer,
5404 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 // This mutex protects syncFd and captureResult for communication of the return values from the
5406 // main thread back to this Binder thread
5407 std::mutex captureMutex;
5408 std::condition_variable captureCondition;
5409 std::unique_lock<std::mutex> captureLock(captureMutex);
5410 int syncFd = -1;
5411 std::optional<status_t> captureResult;
5412
Robert Carr03480e22018-01-04 16:02:06 -08005413 const int uid = IPCThreadState::self()->getCallingUid();
5414 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5415
Dominik Laskowski8c001672018-05-30 16:52:06 -07005416 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005417 // If there is a refresh pending, bug out early and tell the binder thread to try again
5418 // after the refresh.
5419 if (mRefreshPending) {
5420 ATRACE_NAME("Skipping screenshot for now");
5421 std::unique_lock<std::mutex> captureLock(captureMutex);
5422 captureResult = std::make_optional<status_t>(EAGAIN);
5423 captureCondition.notify_one();
5424 return;
5425 }
5426
5427 status_t result = NO_ERROR;
5428 int fd = -1;
5429 {
5430 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005431 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005432 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005433 useIdentityTransform, forSystem, &fd);
5434 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005435 }
5436
5437 {
5438 std::unique_lock<std::mutex> captureLock(captureMutex);
5439 syncFd = fd;
5440 captureResult = std::make_optional<status_t>(result);
5441 captureCondition.notify_one();
5442 }
5443 });
5444
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005445 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005446 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005447 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005448 while (*captureResult == EAGAIN) {
5449 captureResult.reset();
5450 result = postMessageAsync(message);
5451 if (result != NO_ERROR) {
5452 return result;
5453 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005454 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005455 }
5456 result = *captureResult;
5457 }
5458
5459 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005460 sync_wait(syncFd, -1);
5461 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005462 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005463
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005464 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005465}
5466
chaviwa76b2712017-09-20 12:02:26 -07005467void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005468 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005469 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5470 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005471 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005472
chaviwa76b2712017-09-20 12:02:26 -07005473 const auto reqWidth = renderArea.getReqWidth();
5474 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005475 const auto sourceCrop = renderArea.getSourceCrop();
5476 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005477
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005478 renderengine::DisplaySettings clientCompositionDisplay;
5479 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005480
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005481 // assume that bounds are never offset, and that they are the same as the
5482 // buffer bounds.
5483 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5484 ui::Transform transform = renderArea.getTransform();
5485 mat4 m;
5486 m[0][0] = transform[0][0];
5487 m[0][1] = transform[0][1];
5488 m[0][3] = transform[0][2];
5489 m[1][0] = transform[1][0];
5490 m[1][1] = transform[1][1];
5491 m[1][3] = transform[1][2];
5492 m[3][0] = transform[2][0];
5493 m[3][1] = transform[2][1];
5494 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005495
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005496 clientCompositionDisplay.globalTransform = m;
5497 mat4 rotMatrix;
5498 // Displacement for repositioning the clipping rectangle after rotating it
5499 // with the rotation hint.
5500 int displacementX = 0;
5501 int displacementY = 0;
5502 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5503 switch (rotation) {
5504 case ui::Transform::ROT_90:
5505 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5506 displacementX = reqWidth;
5507 break;
5508 case ui::Transform::ROT_180:
5509 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5510 displacementX = reqWidth;
5511 displacementY = reqHeight;
5512 break;
5513 case ui::Transform::ROT_270:
5514 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5515 displacementY = reqHeight;
5516 break;
5517 default:
5518 break;
5519 }
5520 // We need to transform the clipping window into the right spot.
5521 // First, rotate the clipping rectangle by the rotation hint to get the
5522 // right orientation
5523 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5524 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5525 const vec4 rotClipTL = rotMatrix * clipTL;
5526 const vec4 rotClipBR = rotMatrix * clipBR;
5527 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5528 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5529 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5530 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5531
5532 // Now reposition the clipping rectangle with the displacement vector
5533 // computed above.
5534 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5535
5536 clientCompositionDisplay.clip =
5537 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5538 newClipRight + displacementX, newClipBottom + displacementY);
5539
5540 // We need to perform the same transformation in layer space, so propagate
5541 // it to the global transform.
5542 mat4 clipTransform = displacementMat * rotMatrix;
5543 clientCompositionDisplay.globalTransform *= clipTransform;
5544 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5545 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005546
chaviw50da5042018-04-09 13:49:37 -07005547 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005548
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 renderengine::LayerSettings fillLayer;
5550 fillLayer.source.buffer.buffer = nullptr;
5551 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5552 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5553 fillLayer.alpha = half(alpha);
5554 clientCompositionLayers.push_back(fillLayer);
5555
5556 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005557 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005558 renderengine::LayerSettings layerSettings;
5559 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005560 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005561 if (prepared) {
5562 clientCompositionLayers.push_back(layerSettings);
5563 }
chaviwa76b2712017-09-20 12:02:26 -07005564 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005565
5566 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005567 // Use an empty fence for the buffer fence, since we just created the buffer so
5568 // there is no need for synchronization with the GPU.
5569 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005570 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005571 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005573 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005574
5575 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005576}
5577
chaviwa76b2712017-09-20 12:02:26 -07005578status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5579 TraverseLayersFunction traverseLayers,
5580 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005581 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005582 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005583 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005584 ATRACE_CALL();
5585
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005586 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005587
5588 traverseLayers([&](Layer* layer) {
5589 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5590 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005591
Robert Carr03480e22018-01-04 16:02:06 -08005592 // We allow the system server to take screenshots of secure layers for
5593 // use in situations like the Screen-rotation animation and place
5594 // the impetus on WindowManager to not persist them.
5595 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005596 ALOGW("FB is protected: PERMISSION_DENIED");
5597 return PERMISSION_DENIED;
5598 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005599 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005601}
5602
chaviw95ef3c42019-02-14 10:55:09 -08005603void SurfaceFlinger::setInputWindowsFinished() {
5604 Mutex::Autolock _l(mStateLock);
5605
5606 mPendingSyncInputWindows = false;
5607 mTransactionCV.broadcast();
5608}
chaviw5f21a5e2019-02-14 10:00:34 -08005609
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005610// ---------------------------------------------------------------------------
5611
Dan Stoza412903f2017-04-27 13:42:17 -07005612void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5613 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005614}
5615
Dan Stoza412903f2017-04-27 13:42:17 -07005616void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5617 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005618}
5619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005620void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005621 const LayerVector::Visitor& visitor) {
5622 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005623 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005624 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005625 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005626 continue;
5627 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005628 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005629 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005630 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005631 return;
5632 }
chaviwa76b2712017-09-20 12:02:26 -07005633 if (!layer->isVisible()) {
5634 return;
5635 }
5636 visitor(layer);
5637 });
5638 }
5639}
5640
Ady Abraham838de062019-02-04 10:24:03 -08005641void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5642 const android::sp<android::IBinder>& displayToken,
5643 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5644 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5645 if (!displayId) {
5646 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5647 return;
5648 }
5649
5650 ALOGV("Updating allowed configs");
5651 {
5652 std::lock_guard lock(mAllowedConfigsLock);
5653 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5654 }
5655
5656 // make sure that the current config is still allowed
5657 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5658 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005659 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
5660 if (isConfigAllowed(*displayId, config.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005661 // TODO: we switch to the first allowed config. In the future
5662 // we may want to enhance this logic to pick a similar config
5663 // to the current one
Ady Abraham1902d072019-03-01 17:18:59 -08005664 ALOGV("Old config is not allowed - switching to config %d", config.configId);
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005665 setDesiredActiveConfig(displayToken, config.configId,
5666 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005667 break;
5668 }
5669 }
5670 }
Ady Abraham97d04232019-03-05 19:48:12 -08005671
5672 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5673 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5674 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
5675 const auto performanceRefreshRate =
5676 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
5677 if (isConfigAllowed(*displayId, performanceRefreshRate.configId)) {
5678 mPhaseOffsets->setRefreshRateType(
5679 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
5680 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5681 }
5682 }
Ady Abraham838de062019-02-04 10:24:03 -08005683}
5684
5685status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5686 const std::vector<int32_t>& allowedConfigs) {
5687 ATRACE_CALL();
5688
5689 if (!displayToken) {
5690 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5691 return BAD_VALUE;
5692 }
5693
5694 if (!allowedConfigs.size()) {
5695 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5696 return BAD_VALUE;
5697 }
5698
5699 {
5700 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5701 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5702 if (!displayId) {
5703 ALOGE("setAllowedDisplayConfigs: display not found");
5704 return NAME_NOT_FOUND;
5705 }
5706 }
5707
5708 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5709 for (int config : allowedConfigs) {
5710 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5711 allowedDisplayConfigsBuilder.addConfig(config);
5712 }
5713 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5714 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5715 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5716 }));
5717 return NO_ERROR;
5718}
5719
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005720status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5721 std::vector<int32_t>* outAllowedConfigs) {
5722 ATRACE_CALL();
5723
5724 if (!displayToken) {
5725 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5726 return BAD_VALUE;
5727 }
5728
5729 if (!outAllowedConfigs) {
5730 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5731 return BAD_VALUE;
5732 }
5733
5734 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5735 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5736 if (!displayId) {
5737 ALOGE("getAllowedDisplayConfigs: display not found");
5738 return NAME_NOT_FOUND;
5739 }
5740
5741 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5742 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5743 if (allowedConfigIterator != mAllowedConfigs.end()) {
5744 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5745 }
5746
5747 return NO_ERROR;
5748}
5749
chaviw291d88a2019-02-14 10:33:58 -08005750// ----------------------------------------------------------------------------
5751
5752void SetInputWindowsListener::onSetInputWindowsFinished() {
5753 mFlinger->setInputWindowsFinished();
5754}
5755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005756}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005757
Lloyd Pique074e8122018-07-26 12:57:23 -07005758
Mathias Agopian3f844832013-08-07 21:24:32 -07005759#if defined(__gl_h_)
5760#error "don't include gl/gl.h in this file"
5761#endif
5762
5763#if defined(__gl2_h_)
5764#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005765#endif