blob: 3c98349eb94a57f3221cda610af4c9923b7378e4 [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),
Nataniel Borges2b796da2019-02-15 13:32:18 -0800277 mTracing(*this),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800278 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800279 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800280 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800281 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700282 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700283 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800284 mCompositionEngine{getFactory().createCompositionEngine()} {
285 mSetInputWindowsListener = new SetInputWindowsListener(this);
286}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800287
Lloyd Pique90c115d2018-09-18 21:39:42 -0700288SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
289 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800299
Steven Thomas050b2c82017-03-06 11:45:16 -0800300 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 mDefaultCompositionDataspace =
310 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
311 mWideColorGamutCompositionDataspace =
312 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
313 defaultCompositionDataspace = mDefaultCompositionDataspace;
314 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
315 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
316 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
317 wideColorGamutCompositionPixelFormat =
318 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800321
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
323 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
324 switch (tmpPrimaryDisplayOrientation) {
325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
334 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800339
Sundong Ahn85131bd2019-02-18 15:51:53 +0900340 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 // debugging stuff...
343 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700346 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 property_get("debug.sf.showupdates", value, "0");
349 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000352
353 // DDMS debugging deprecated (b/120782499)
354 property_get("debug.sf.ddms", value, "0");
355 int debugDdms = atoi(value);
356 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700357
358 property_get("debug.sf.disable_backpressure", value, "0");
359 mPropagateBackpressure = !atoi(value);
360 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700361
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800362 property_get("debug.sf.enable_hwc_vds", value, "0");
363 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800364 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800366 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800368 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700369
Yiwei Zhang243b3782018-05-15 17:40:04 -0700370 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Ana Krulece5a06e02019-03-06 17:09:03 -0800374 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800375 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800376
377 int int_value = atoi(value);
378 if (int_value) {
379 mUseSmart90ForVideo = true;
380 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800381
Dan Stozaec460082018-12-17 15:35:09 -0800382 property_get("debug.sf.luma_sampling", value, "1");
383 mLumaSampling = atoi(value);
384
Ana Krulec757f63a2019-01-25 10:46:18 -0800385 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
386 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700387
Romain Guy11d63f42017-07-20 12:47:14 -0700388 // We should be reading 'persist.sys.sf.color_saturation' here
389 // but since /data may be encrypted, we need to wait until after vold
390 // comes online to attempt to read the property. The property is
391 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800392
393 if (useTrebleTestingOverride()) {
394 // Without the override SurfaceFlinger cannot connect to HIDL
395 // services that are not listed in the manifests. Considered
396 // deriving the setting from the set service name, but it
397 // would be brittle if the name that's not 'default' is used
398 // for production purposes later on.
399 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
400 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401}
402
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403void SurfaceFlinger::onFirstRef()
404{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800405 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406}
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408SurfaceFlinger::~SurfaceFlinger()
409{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Dan Stozac7014012014-02-14 15:03:43 -0800412void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413{
414 // the window manager died on us. prepare its eulogy.
415
Andy McFadden13a082e2012-08-24 10:16:42 -0700416 // restore initial conditions (default device unblank, etc)
417 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418
419 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700420 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421}
422
Robert Carr1db73f62016-12-21 12:58:51 -0800423static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700424 status_t err = client->initCheck();
425 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 }
Robert Carr1db73f62016-12-21 12:58:51 -0800428 return nullptr;
429}
430
431sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
432 return initClient(new Client(this));
433}
434
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700435sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
436 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437{
438 class DisplayToken : public BBinder {
439 sp<SurfaceFlinger> flinger;
440 virtual ~DisplayToken() {
441 // no more references, this display must be terminated
442 Mutex::Autolock _l(flinger->mStateLock);
443 flinger->mCurrentState.displays.removeItem(this);
444 flinger->setTransactionFlags(eDisplayTransactionNeeded);
445 }
446 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700447 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448 : flinger(flinger) {
449 }
450 };
451
452 sp<BBinder> token = new DisplayToken(this);
453
454 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 // Display ID is assigned when virtual display is allocated by HWC.
456 DisplayDeviceState state;
457 state.isSecure = secure;
458 state.displayName = displayName;
459 mCurrentState.displays.add(token, state);
460 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461 return token;
462}
463
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700464void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 Mutex::Autolock _l(mStateLock);
466
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
468 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700469 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 return;
471 }
472
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
474 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 ALOGE("destroyDisplay called for non-virtual display");
476 return;
477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478 mInterceptor->saveDisplayDeletion(state.sequenceId);
479 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 setTransactionFlags(eDisplayTransactionNeeded);
481}
482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
484 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486 const auto internalDisplayId = getInternalDisplayIdLocked();
487 if (!internalDisplayId) {
488 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 }
490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 std::vector<PhysicalDisplayId> displayIds;
492 displayIds.reserve(mPhysicalDisplayTokens.size());
493 displayIds.push_back(internalDisplayId->value);
494
495 for (const auto& [id, token] : mPhysicalDisplayTokens) {
496 if (id != *internalDisplayId) {
497 displayIds.push_back(id.value);
498 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800501 return displayIds;
502}
503
504sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
505 Mutex::Autolock lock(mStateLock);
506 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507}
508
Ady Abraham37965d42018-11-01 13:43:32 -0700509status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
510 if (!outGetColorManagement) {
511 return BAD_VALUE;
512 }
513 *outGetColorManagement = useColorManagement;
514 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700515}
516
Lloyd Pique441d5042018-10-18 16:49:51 -0700517HWComposer& SurfaceFlinger::getHwComposer() const {
518 return mCompositionEngine->getHwComposer();
519}
520
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700521renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
522 return mCompositionEngine->getRenderEngine();
523}
524
Lloyd Pique70d91362018-10-18 16:02:55 -0700525compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
526 return *mCompositionEngine.get();
527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529void SurfaceFlinger::bootFinished()
530{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
538 // wait patiently for the window manager death
539 const String16 name("window");
540 sp<IBinder> window(defaultServiceManager()->getService(name));
541 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700542 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
Robert Carr720e5062018-07-30 17:45:14 -0700544 sp<IBinder> input(defaultServiceManager()->getService(
545 String16("inputflinger")));
546 if (input == nullptr) {
547 ALOGE("Failed to link to input service");
548 } else {
549 mInputFlinger = interface_cast<IInputFlinger>(input);
550 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
Steven Thomas050b2c82017-03-06 11:45:16 -0800552 if (mVrFlinger) {
553 mVrFlinger->OnBootFinished();
554 }
555
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700557 // formerly we would just kill the process, but we now ask it to exit so it
558 // can choose where to stop the animation.
559 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700560
561 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
562 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
563 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700564
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 readPersistentProperties();
567 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568
Ady Abraham97d04232019-03-05 19:48:12 -0800569 // set the refresh rate according to the policy
570 const auto displayId = getInternalDisplayIdLocked();
571 LOG_ALWAYS_FATAL_IF(!displayId);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800572
Alec Mouri0a1cc962019-03-14 12:33:02 -0700573 const auto& performanceRefreshRate =
Ady Abraham97d04232019-03-05 19:48:12 -0800574 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
575
Alec Mouri0a1cc962019-03-14 12:33:02 -0700576 if (performanceRefreshRate &&
577 isConfigAllowed(*displayId, performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800578 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800579 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800580 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800581 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800582 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583}
584
Dan Stoza436ccf32018-06-21 12:10:12 -0700585uint32_t SurfaceFlinger::getNewTexture() {
586 {
587 std::lock_guard lock(mTexturePoolMutex);
588 if (!mTexturePool.empty()) {
589 uint32_t name = mTexturePool.back();
590 mTexturePool.pop_back();
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
592 return name;
593 }
594
595 // The pool was too small, so increase it for the future
596 ++mTexturePoolSize;
597 }
598
599 // The pool was empty, so we need to get a new texture name directly using a
600 // blocking call to the main thread
601 uint32_t name = 0;
602 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
603 return name;
604}
605
Mathias Agopian3f844832013-08-07 21:24:32 -0700606void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700607 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700608}
609
Wei Wangf9b05ee2017-07-19 20:59:39 -0700610// Do not call property_set on main thread which will be blocked by init
611// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700613 ALOGI( "SurfaceFlinger's main thread ready to run. "
614 "Initializing graphics H/W...");
615
Ana Krulec757f63a2019-01-25 10:46:18 -0800616 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800620 mScheduler =
621 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
622 auto resyncCallback =
623 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800624
Ana Krulecc2870422019-01-29 19:00:58 -0800625 mAppConnectionHandle =
626 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
627 resyncCallback,
628 impl::EventThread::InterceptVSyncsCallback());
629 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
630 resyncCallback, [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
633
634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
635 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
636 mSfConnectionHandle.get());
637
Kevin DuBois413287f2019-02-25 08:46:47 -0800638 mRegionSamplingThread =
639 new RegionSamplingThread(*this, *mScheduler,
640 RegionSamplingThread::EnvironmentTimingTunables());
641
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700643 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700644 renderEngineFeature |= (useColorManagement ?
645 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700646 renderEngineFeature |= (useContextPriority ?
647 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700648
649 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800650 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700651 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700652 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800653 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700654
655 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
656 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700657 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
658 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800659 // Process any initial hotplug and resulting display changes.
660 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 const auto display = getDefaultDisplayDeviceLocked();
662 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700663 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800665
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700667 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700668 // This callback is called from the vr flinger dispatch thread. We
669 // need to call signalTransaction(), which requires holding
670 // mStateLock when we're not on the main thread. Acquiring
671 // mStateLock from the vr flinger dispatch thread might trigger a
672 // deadlock in surface flinger (see b/66916578), so post a message
673 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
676 mVrFlingerRequestsDisplay = requestDisplay;
677 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
681 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 .value_or(0),
684 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (!mVrFlinger) {
686 ALOGE("Failed to start vrflinger");
687 }
688 }
689
Mathias Agopian92a979a2012-08-02 18:32:23 -0700690 // initialize our drawing state
691 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700692
Andy McFadden13a082e2012-08-24 10:16:42 -0700693 // set initial conditions (e.g. unblank default device)
694 initializeDisplays();
695
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700696 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699
700 const bool presentFenceReliable =
701 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
702 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703
704 if (mStartPropertySetThread->Start() != NO_ERROR) {
705 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707
Ady Abraham97d04232019-03-05 19:48:12 -0800708 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800709 mScheduler->setChangeRefreshRateCallback(
710 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
711 Mutex::Autolock lock(mStateLock);
712 setRefreshRateTo(type, event);
713 });
Kevin DuBois36233132019-02-19 14:08:55 -0800714 }
Ady Abraham1902d072019-03-01 17:18:59 -0800715 mRefreshRateConfigs[*display->getId()] = std::make_shared<scheduler::RefreshRateConfigs>(
716 getHwComposer().getConfigs(*display->getId()));
717 mRefreshRateStats =
718 std::make_unique<scheduler::RefreshRateStats>(mRefreshRateConfigs[*display->getId()],
719 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800736
737 property_get("persist.sys.sf.color_mode", value, "0");
738 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700752 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700756 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800794status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
795 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800800 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700801 if (!displayId) {
802 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700803 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804
Mathias Agopian8b736f12012-08-13 17:54:26 -0700805 // TODO: Not sure if display density should handled by SF any longer
806 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700809 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 }
813 return density;
814 }
815 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("ro.sf.lcd_density"); }
820 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 DisplayInfo info = DisplayInfo();
826
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 float xdpi = hwConfig->getDpiX();
828 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830 info.w = hwConfig->getWidth();
831 info.h = hwConfig->getHeight();
832 // Default display viewport to display width and height
833 info.viewportW = info.w;
834 info.viewportH = info.h;
835
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800836 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 // The density of the device is provided by a build property
838 float density = Density::getBuildDensity() / 160.0f;
839 if (density == 0) {
840 // the build doesn't provide a density -- this is wrong!
841 // use xdpi instead
842 ALOGE("ro.sf.lcd_density must be defined as a build property");
843 density = xdpi / 160.0f;
844 }
845 if (Density::getEmuDensity()) {
846 // if "qemu.sf.lcd_density" is specified, it overrides everything
847 xdpi = ydpi = density = Density::getEmuDensity();
848 density /= 160.0f;
849 }
850 info.density = density;
851
852 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700853 const auto display = getDefaultDisplayDeviceLocked();
854 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855
856 // This is for screenrecord
857 const Rect viewport = display->getViewport();
858 if (viewport.isValid()) {
859 info.viewportW = uint32_t(viewport.getWidth());
860 info.viewportH = uint32_t(viewport.getHeight());
861 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 } else {
863 // TODO: where should this value come from?
864 static const int TV_DENSITY = 213;
865 info.density = TV_DENSITY / 160.0f;
866 info.orientation = 0;
867 }
868
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800872 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800886 info.presentationDeadline =
887 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800892 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700893 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800894 std::swap(info.w, info.h);
895 }
896
Michael Wright28f24d02016-07-12 13:30:53 -0700897 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700898 }
899
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 return NO_ERROR;
901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
904 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 return BAD_VALUE;
906 }
907
Ana Krulecc2870422019-01-29 19:00:58 -0800908 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700909 return NO_ERROR;
910}
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Ady Abraham447052e2019-02-13 16:07:27 -0800922void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800923 Scheduler::ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 // Lock is acquired by setRefreshRateTo.
927 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928 if (!display) {
929 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
930 displayToken.get());
931 return;
932 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700933 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800934 ALOGW("Attempt to set active config %d for virtual display", mode);
935 return;
936 }
937 int currentDisplayPowerMode = display->getPowerMode();
938 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
939 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 return;
941 }
942
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800944 // config twice. However event generation config might have changed so we need to update it
945 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800946 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800947 const Scheduler::ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
Ady Abraham9360a222019-02-27 17:05:30 -0800948 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949
950 if (!mDesiredActiveConfigChanged) {
951 // This is the first time we set the desired
952 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
953
954 // This will trigger HWC refresh without resetting the idle timer.
955 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800957 mDesiredActiveConfigChanged = true;
958 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800959}
960
961status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
962 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800963
964 std::vector<int32_t> allowedConfig;
965 allowedConfig.push_back(mode);
966
967 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800968}
969
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970void SurfaceFlinger::setActiveConfigInternal() {
971 ATRACE_CALL();
972
973 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800974 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975
976 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
977 display->setActiveConfig(mUpcomingActiveConfig.configId);
978
Ana Krulecc2870422019-01-29 19:00:58 -0800979 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800980 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
981 mVsyncModulator.setPhaseOffsets(early, gl, late);
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 if (mCheckPendingFence) {
992 if (mPreviousPresentFence != Fence::NO_FENCE &&
993 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
994 // fence has not signaled yet. wait for the next invalidate
995 repaintEverythingForHWC();
996 return true;
997 }
998
999 // We received the present fence from the HWC, so we assume it successfully updated
1000 // the config, hence we update SF.
1001 mCheckPendingFence = false;
1002 setActiveConfigInternal();
1003 }
1004
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 // Store the local variable to release the lock.
1006 ActiveConfigInfo desiredActiveConfig;
1007 {
1008 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (!mDesiredActiveConfigChanged) {
1010 return false;
1011 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 desiredActiveConfig = mDesiredActiveConfig;
1013 }
1014
1015 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1017 // display is not valid or we are already in the requested mode
1018 // on both cases there is nothing left to do
1019 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1020 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1021 mDesiredActiveConfigChanged = false;
1022 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1023 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025
Ady Abraham838de062019-02-04 10:24:03 -08001026 // Desired active config was set, it is different than the config currently in use, however
1027 // allowed configs might have change by the time we process the refresh.
1028 // Make sure the desired config is still allowed
1029 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1030 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1031 mDesiredActiveConfig.configId = display->getActiveConfig();
1032 return false;
1033 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 mUpcomingActiveConfig = desiredActiveConfig;
1035 const auto displayId = display->getId();
1036 LOG_ALWAYS_FATAL_IF(!displayId);
1037
1038 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1039 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1040
1041 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001042 mCheckPendingFence = true;
1043
1044 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001045}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1048 Vector<ColorMode>* outColorModes) {
1049 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001050 return BAD_VALUE;
1051 }
1052
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001054 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001055 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1056
1057 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1058 if (!displayId) {
1059 return NAME_NOT_FOUND;
1060 }
1061
Dominik Laskowski075d3172018-05-24 15:50:06 -07001062 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001063 }
Michael Wright28f24d02016-07-12 13:30:53 -07001064 outColorModes->clear();
1065 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1066
1067 return NO_ERROR;
1068}
1069
Daniel Solomon42d04562019-01-20 21:03:19 -08001070status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1071 ui::DisplayPrimaries &primaries) {
1072 if (!displayToken) {
1073 return BAD_VALUE;
1074 }
1075
1076 // Currently we only support this API for a single internal display.
1077 if (getInternalDisplayToken() != displayToken) {
1078 return BAD_VALUE;
1079 }
1080
1081 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001087 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 Vector<ColorMode> modes;
1095 getDisplayColorModes(displayToken, &modes);
1096 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1097 if (mode < ColorMode::NATIVE || !exists) {
1098 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1099 decodeColorMode(mode).c_str(), mode, displayToken.get());
1100 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDevice(displayToken);
1103 if (!display) {
1104 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1105 decodeColorMode(mode).c_str(), mode, displayToken.get());
1106 } else if (display->isVirtual()) {
1107 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1108 decodeColorMode(mode).c_str(), mode);
1109 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001110 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1111 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 }
1113 }));
1114
Michael Wright28f24d02016-07-12 13:30:53 -07001115 return NO_ERROR;
1116}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001117
Svetoslavd85084b2014-03-20 10:28:31 -07001118status_t SurfaceFlinger::clearAnimationFrameStats() {
1119 Mutex::Autolock _l(mStateLock);
1120 mAnimFrameTracker.clearStats();
1121 return NO_ERROR;
1122}
1123
1124status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1125 Mutex::Autolock _l(mStateLock);
1126 mAnimFrameTracker.getStats(outStats);
1127 return NO_ERROR;
1128}
1129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1131 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001132 Mutex::Autolock _l(mStateLock);
1133
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001134 const auto display = getDisplayDeviceLocked(displayToken);
1135 if (!display) {
1136 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001137 return BAD_VALUE;
1138 }
1139
Peiyong Linfb069302018-04-25 14:34:31 -07001140 // At this point the DisplayDeivce should already be set up,
1141 // meaning the luminance information is already queried from
1142 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001144 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1145 capabilities.getDesiredMaxLuminance(),
1146 capabilities.getDesiredMaxAverageLuminance(),
1147 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001148
1149 return NO_ERROR;
1150}
1151
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001152status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1153 ui::PixelFormat* outFormat,
1154 ui::Dataspace* outDataspace,
1155 uint8_t* outComponentMask) const {
1156 if (!outFormat || !outDataspace || !outComponentMask) {
1157 return BAD_VALUE;
1158 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001159 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001160 if (!display || !display->getId()) {
1161 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1162 return BAD_VALUE;
1163 }
1164 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1165 outDataspace, outComponentMask);
1166}
1167
Kevin DuBois74e53772018-11-19 10:52:38 -08001168status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1169 bool enable, uint8_t componentMask,
1170 uint64_t maxFrames) const {
1171 const auto display = getDisplayDevice(displayToken);
1172 if (!display || !display->getId()) {
1173 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1174 return BAD_VALUE;
1175 }
1176
1177 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1178 componentMask, maxFrames);
1179}
1180
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001181status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1182 uint64_t maxFrames, uint64_t timestamp,
1183 DisplayedFrameStats* outStats) const {
1184 const auto display = getDisplayDevice(displayToken);
1185 if (!display || !display->getId()) {
1186 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1187 return BAD_VALUE;
1188 }
1189
1190 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1191 outStats);
1192}
1193
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001194status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1195 if (!outSupported) {
1196 return BAD_VALUE;
1197 }
1198 *outSupported = getRenderEngine().supportsProtectedContent();
1199 return NO_ERROR;
1200}
1201
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001202status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1203 bool* outIsWideColorDisplay) const {
1204 if (!displayToken || !outIsWideColorDisplay) {
1205 return BAD_VALUE;
1206 }
1207 Mutex::Autolock _l(mStateLock);
1208 const auto display = getDisplayDeviceLocked(displayToken);
1209 if (!display) {
1210 return BAD_VALUE;
1211 }
1212 *outIsWideColorDisplay = display->hasWideColorGamut();
1213 return NO_ERROR;
1214}
1215
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001216status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001217 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001219
Chia-I Wu90f669f2017-10-05 14:24:41 -07001220 if (mInjectVSyncs == enable) {
1221 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001222 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001223
Ana Krulecc2870422019-01-29 19:00:58 -08001224 auto resyncCallback =
1225 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001226
Ana Krulec98b5b242018-08-10 15:03:23 -07001227 // TODO(akrulec): Part of the Injector should be refactored, so that it
1228 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001229 if (enable) {
1230 ALOGV("VSync Injections enabled");
1231 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001232 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001233 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001234 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001235 impl::EventThread::InterceptVSyncsCallback(),
1236 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001237 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001238 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239 } else {
1240 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001241 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1242 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243 }
1244
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001245 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001246 }));
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248 return NO_ERROR;
1249}
1250
1251status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 Mutex::Autolock _l(mStateLock);
1253
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254 if (!mInjectVSyncs) {
1255 ALOGE("VSync Injections not enabled");
1256 return BAD_VALUE;
1257 }
1258 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1259 ALOGV("Injecting VSync inside SurfaceFlinger");
1260 mVSyncInjector->onInjectSyncEvent(when);
1261 }
1262 return NO_ERROR;
1263}
1264
Lloyd Pique755e3192018-01-31 16:46:15 -08001265status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1266 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001267 // Try to acquire a lock for 1s, fail gracefully
1268 const status_t err = mStateLock.timedLock(s2ns(1));
1269 const bool locked = (err == NO_ERROR);
1270 if (!locked) {
1271 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1272 return TIMED_OUT;
1273 }
1274
1275 outLayers->clear();
1276 mCurrentState.traverseInZOrder([&](Layer* layer) {
1277 outLayers->push_back(layer->getLayerDebugInfo());
1278 });
1279
1280 mStateLock.unlock();
1281 return NO_ERROR;
1282}
1283
Peiyong Linc6780972018-10-28 15:24:08 -07001284status_t SurfaceFlinger::getCompositionPreference(
1285 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1286 Dataspace* outWideColorGamutDataspace,
1287 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001288 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001289 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001290 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001291 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001292 return NO_ERROR;
1293}
1294
Dan Stozaec460082018-12-17 15:35:09 -08001295status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1296 const sp<IBinder>& stopLayerHandle,
1297 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001298 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001299 return BAD_VALUE;
1300 }
1301 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001302 return NO_ERROR;
1303}
1304
Dan Stozaec460082018-12-17 15:35:09 -08001305status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001306 if (!listener) {
1307 return BAD_VALUE;
1308 }
Dan Stozaec460082018-12-17 15:35:09 -08001309 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001310 return NO_ERROR;
1311}
Dan Gittik57e63c52019-01-18 16:37:54 +00001312
1313status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1314 bool* outSupport) const {
1315 if (!displayToken || !outSupport) {
1316 return BAD_VALUE;
1317 }
1318 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1319 if (!displayId) {
1320 return NAME_NOT_FOUND;
1321 }
1322 *outSupport =
1323 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1324 return NO_ERROR;
1325}
1326
1327status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1328 float brightness) const {
1329 if (!displayToken) {
1330 return BAD_VALUE;
1331 }
1332 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1333 if (!displayId) {
1334 return NAME_NOT_FOUND;
1335 }
1336 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1337}
1338
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001339// ----------------------------------------------------------------------------
1340
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001341sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1342 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001343 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001344 Mutex::Autolock lock(mStateLock);
1345 return getVsyncPeriod();
1346 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001347
Ana Krulecc2870422019-01-29 19:00:58 -08001348 const auto& handle =
1349 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001350
Ana Krulecc2870422019-01-29 19:00:58 -08001351 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001352}
1353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001355
1356void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001361 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362}
1363
1364void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001365 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001366}
1367
1368void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001369 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001370 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371}
1372
1373status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001374 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001375 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376}
1377
1378status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001379 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381 if (res == NO_ERROR) {
1382 msg->wait();
1383 }
1384 return res;
1385}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001386
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001387void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001388 do {
1389 waitForEvent();
1390 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001391}
1392
Dominik Laskowski83b88212018-12-11 13:34:06 -08001393nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001394 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001395 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1396 return 0;
1397 }
1398
1399 const auto config = getHwComposer().getActiveConfig(*displayId);
1400 return config ? config->getVsyncPeriod() : 0;
1401}
1402
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001403void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1404 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001405 ATRACE_NAME("SF onVsync");
1406
Steven Thomas3cfac282017-02-06 12:29:30 -08001407 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001409 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 return;
1411 }
1412
Dominik Laskowski075d3172018-05-24 15:50:06 -07001413 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001414 return;
1415 }
1416
Dominik Laskowski075d3172018-05-24 15:50:06 -07001417 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001418 // For now, we don't do anything with external display vsyncs.
1419 return;
1420 }
1421
Ana Krulecc2870422019-01-29 19:00:58 -08001422 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001423}
1424
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001426 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1427 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001428}
1429
Ady Abraham838de062019-02-04 10:24:03 -08001430bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1431 std::lock_guard lock(mAllowedConfigsLock);
1432
1433 // if allowed configs are not set yet for this display, every config is considered allowed
1434 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1435 return true;
1436 }
1437
1438 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1439}
1440
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001441void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001442 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001443 return;
1444 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001445 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001446
Ana Krulec7d1d6832018-12-27 11:10:09 -08001447 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001448 const auto displayId = getInternalDisplayIdLocked();
1449 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham1902d072019-03-01 17:18:59 -08001450 const auto displayToken = getInternalDisplayTokenLocked();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001451
Alec Mouri0a1cc962019-03-14 12:33:02 -07001452 const auto& refreshRateConfig = mRefreshRateConfigs[*displayId]->getRefreshRate(refreshRate);
1453 if (!refreshRateConfig) {
1454 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001455 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 }
Ady Abraham1902d072019-03-01 17:18:59 -08001457
Alec Mouri0a1cc962019-03-14 12:33:02 -07001458 const int desiredConfigId = refreshRateConfig->configId;
1459
Ady Abraham1902d072019-03-01 17:18:59 -08001460 if (!isConfigAllowed(*displayId, desiredConfigId)) {
1461 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1462 return;
1463 }
1464
Alec Mouri0a1cc962019-03-14 12:33:02 -07001465 const auto display = getDisplayDeviceLocked(displayToken);
1466 if (desiredConfigId == display->getActiveConfig()) {
1467 return;
1468 }
1469
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001470 mPhaseOffsets->setRefreshRateType(refreshRate);
Ady Abraham1902d072019-03-01 17:18:59 -08001471 setDesiredActiveConfig(getInternalDisplayTokenLocked(), desiredConfigId, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001472}
1473
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001474void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001475 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001476 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001477 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478
Lloyd Piqueba04e622017-12-14 17:11:26 -08001479 // Ignore events that do not have the right sequenceId.
1480 if (sequenceId != getBE().mComposerSequenceId) {
1481 return;
1482 }
1483
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 // Only lock if we're not on the main thread. This function is normally
1485 // called on a hwbinder thread, but for the primary display it's called on
1486 // the main thread with the state lock already held, so don't attempt to
1487 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001488 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001489
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001490 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001491
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001492 if (std::this_thread::get_id() == mMainThreadId) {
1493 // Process all pending hot plug events immediately if we are on the main thread.
1494 processDisplayHotplugEventsLocked();
1495 }
1496
Lloyd Piqueba04e622017-12-14 17:11:26 -08001497 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001498}
1499
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001500void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001501 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001502 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001504 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001505 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001506}
1507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001508void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001509 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001511 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001512 getHwComposer().setVsyncEnabled(*displayId,
1513 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1514 }
Mathias Agopian86303202012-07-24 22:46:10 -07001515}
1516
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001517// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001518void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001519 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001520 // Clear the drawing state so that the logic inside of
1521 // handleTransactionLocked will fire. It will determine the delta between
1522 // mCurrentState and mDrawingState and re-apply all changes when we make the
1523 // transition.
1524 mDrawingState.displays.clear();
1525 mDisplays.clear();
1526}
1527
Steven Thomas050b2c82017-03-06 11:45:16 -08001528void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001529 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001530 if (!mVrFlinger)
1531 return;
1532 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001533 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001534 return;
1535 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536
Lloyd Pique441d5042018-10-18 16:49:51 -07001537 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001538 ALOGE("Vr flinger is only supported for remote hardware composer"
1539 " service connections. Ignoring request to transition to vr"
1540 " flinger.");
1541 mVrFlingerRequestsDisplay = false;
1542 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001543 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001546
Steven Thomas0123ac62018-07-12 11:32:34 -07001547 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001548 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001549
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001550 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001551
1552 // Clear out all the output layers from the composition engine for all
1553 // displays before destroying the hardware composer interface. This ensures
1554 // any HWC layers are destroyed through that interface before it becomes
1555 // invalid.
1556 for (const auto& [token, displayDevice] : mDisplays) {
1557 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1558 compositionengine::Output::OutputLayers());
1559 }
1560
Steven Thomas0123ac62018-07-12 11:32:34 -07001561 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1562 // called below. Clear the reference now so we don't accidentally use it
1563 // later.
1564 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001565
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001568 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001571 // Delete the current instance before creating the new one
1572 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1573 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1574 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1575 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001576
Lloyd Pique441d5042018-10-18 16:49:51 -07001577 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001578 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001579
1580 if (vrFlingerRequestsDisplay) {
1581 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001582 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583
1584 mVisibleRegionsDirty = true;
1585 invalidateHwcGeometry();
1586
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001587 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001588 display = getDefaultDisplayDeviceLocked();
1589 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001590 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001591
Steven Thomasb02664d2017-07-26 18:48:28 -07001592 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001593 const nsecs_t vsyncPeriod = getVsyncPeriod();
1594 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001595
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001596 // The present fences returned from vr_hwc are not an accurate
1597 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001598 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001599
Steven Thomasb02664d2017-07-26 18:48:28 -07001600 // Use phase of 0 since phase is not known.
1601 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001602 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001603 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001604
Ana Krulecc2870422019-01-29 19:00:58 -08001605 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001606
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001607 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001608 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001609}
1610
Mathias Agopian4fec8732012-06-29 14:12:52 -07001611void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001612 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001613 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001614 case MessageQueue::INVALIDATE: {
Alec Mouricc0fc602019-02-26 21:45:19 -08001615 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
1616 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
1617 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1618 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1619 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1620 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1621 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1622 if (frameMissed) {
1623 mFrameMissedCount++;
1624 mTimeStats->incrementMissedFrames();
1625 }
1626
Alec Mouri40189b02019-03-05 15:07:54 -08001627 if (hwcFrameMissed) {
1628 mHwcFrameMissedCount++;
1629 }
1630
1631 if (gpuFrameMissed) {
1632 mGpuFrameMissedCount++;
1633 }
1634
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001635 if (mUseSmart90ForVideo) {
1636 // This call is made each time SF wakes up and creates a new frame. It is part
1637 // of video detection feature.
1638 mScheduler->updateFpsBasedOnNativeWindowApi();
1639 }
1640
Ady Abrahamb838aed2019-02-12 15:30:16 -08001641 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001642 break;
1643 }
1644
Alec Mourife3dc942019-02-12 14:19:18 -08001645 // For now, only propagate backpressure when missing a hwc frame.
1646 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001647 if (mPropagateBackpressure) {
1648 signalLayerUpdate();
1649 break;
1650 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001651 }
Dan Stoza50182882016-07-08 12:02:20 -07001652
Steven Thomas050b2c82017-03-06 11:45:16 -08001653 // Now that we're going to make it to the handleMessageTransaction()
1654 // call below it's safe to call updateVrFlinger(), which will
1655 // potentially trigger a display handoff.
1656 updateVrFlinger();
1657
Dan Stoza6b9454d2014-11-07 16:00:59 -08001658 bool refreshNeeded = handleMessageTransaction();
1659 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001660
1661 updateCursorAsync();
1662 updateInputFlinger();
1663
Dan Stoza58784442014-12-02 16:58:17 -08001664 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001665 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001666 // Signal a refresh if a transaction modified the window state,
1667 // a new buffer was latched, or if HWC has requested a full
1668 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001669 signalRefresh();
1670 }
1671 break;
1672 }
1673 case MessageQueue::REFRESH: {
1674 handleMessageRefresh();
1675 break;
1676 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001677 }
1678}
1679
Dan Stoza6b9454d2014-11-07 16:00:59 -08001680bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001681 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001682 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001683
1684 // Apply any ready transactions in the queues if there are still transactions that have not been
1685 // applied, wake up during the next vsync period and check again
1686 bool transactionNeeded = false;
1687 if (!flushTransactionQueues()) {
1688 transactionNeeded = true;
1689 }
1690
Mathias Agopian4fec8732012-06-29 14:12:52 -07001691 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001692 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001693 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001694
1695 if (transactionNeeded) {
1696 setTransactionFlags(eTransactionNeeded);
1697 }
1698
1699 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700}
1701
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001704
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001705 mRefreshPending = false;
1706
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001707 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001708 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001709 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001710 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711 for (const auto& [token, display] : mDisplays) {
1712 beginFrame(display);
1713 prepareFrame(display);
1714 doDebugFlashRegions(display, repaintEverything);
1715 doComposition(display, repaintEverything);
1716 }
1717
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001718 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719
1720 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001721 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001722
Dan Stozabfbffeb2016-07-21 14:49:33 -07001723 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001724 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 for (const auto& [token, displayDevice] : mDisplays) {
1726 auto display = displayDevice->getCompositionDisplay();
1727 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001728 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001730 mHadDeviceComposition =
1731 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001732 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001733
Jorim Jaggi90535212018-05-23 23:44:06 +02001734 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001735
David Sodman7e4ae112018-02-09 15:02:28 -08001736 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001738
David Sodmanfa9b2af2017-12-24 13:28:59 -08001739
1740bool SurfaceFlinger::handleMessageInvalidate() {
1741 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001742 bool refreshNeeded = handlePageFlip();
1743
Vishnu Nair4351ad52019-02-11 14:13:02 -08001744 if (mVisibleRegionsDirty) {
1745 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001746 if (mTracingEnabled) {
1747 mTracing.notify("visibleRegionsDirty");
1748 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001749 }
1750
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001751 for (auto& layer : mLayersPendingRefresh) {
1752 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001753 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001754 invalidateLayerStack(layer, visibleReg);
1755 }
1756 mLayersPendingRefresh.clear();
1757 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001758}
1759
David Sodman79bba0e2018-08-05 18:07:49 -07001760void SurfaceFlinger::calculateWorkingSet() {
1761 ATRACE_CALL();
1762 ALOGV(__FUNCTION__);
1763
David Sodman79bba0e2018-08-05 18:07:49 -07001764 // build the h/w work list
1765 if (CC_UNLIKELY(mGeometryInvalid)) {
1766 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001767 for (const auto& [token, displayDevice] : mDisplays) {
1768 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001769
Lloyd Piquea83776c2019-01-29 18:42:32 -08001770 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001771
Lloyd Piquea83776c2019-01-29 18:42:32 -08001772 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1773 auto& compositionState = layer->editState();
1774 compositionState.forceClientComposition = false;
1775 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1776 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001777 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778
Lloyd Piquea83776c2019-01-29 18:42:32 -08001779 // The output Z order is set here based on a simple counter.
1780 compositionState.z = zOrder++;
1781
1782 // Update the display independent composition state. This goes
1783 // to the general composition layer state structure.
1784 // TODO: Do this once per compositionengine::CompositionLayer.
1785 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1786 true);
1787
1788 // Recalculate the geometry state of the output layer.
1789 layer->updateCompositionState(true);
1790
1791 // Write the updated geometry state to the HWC
1792 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 }
1794 }
1795 }
1796
1797 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 for (const auto& [token, displayDevice] : mDisplays) {
1799 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001800 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001802 continue;
1803 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001804 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001805
1806 if (mDrawingState.colorMatrixChanged) {
1807 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001809 Dataspace targetDataspace = Dataspace::UNKNOWN;
1810 if (useColorManagement) {
1811 ColorMode colorMode;
1812 RenderIntent renderIntent;
1813 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1814 display->setColorMode(colorMode, targetDataspace, renderIntent);
1815 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001816 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001817 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001818 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001819 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1820 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001821 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001822 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001823 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1824 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001825 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001826 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001827 }
1828
Peiyong Lind3788632018-09-18 16:01:31 -07001829 // TODO(b/111562338) remove when composer 2.3 is shipped.
1830 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001831 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001832 }
1833
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001834 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001835 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001836 }
1837
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001838 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001839 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001840 layer->setCompositionType(displayDevice,
1841 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 continue;
1843 }
1844
Lloyd Pique32cbe282018-10-19 13:09:22 -07001845 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001846 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Linc502cb72019-03-01 15:00:23 -08001847 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001848 }
1849 }
1850
1851 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001852
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001853 for (const auto& [token, displayDevice] : mDisplays) {
1854 auto display = displayDevice->getCompositionDisplay();
1855 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001856 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1857 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1858 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001859 }
1860 }
David Sodman79bba0e2018-08-05 18:07:49 -07001861}
1862
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1864 bool repaintEverything) {
1865 auto display = displayDevice->getCompositionDisplay();
1866 const auto& displayState = display->getState();
1867
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868 // is debugging enabled
1869 if (CC_LIKELY(!mDebugRegion))
1870 return;
1871
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001873 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001874 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001875 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001876 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001878 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001880 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881 }
1882 }
1883
Lloyd Pique32cbe282018-10-19 13:09:22 -07001884 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885
1886 if (mDebugRegion > 1) {
1887 usleep(mDebugRegion * 1000);
1888 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001889
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891}
1892
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001893void SurfaceFlinger::logLayerStats() {
1894 ATRACE_CALL();
1895 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001896 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001898 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001899 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001900 }
1901 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001902
1903 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001904 }
1905}
1906
David Sodman2b406362017-12-15 13:33:47 -08001907void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001908{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 ATRACE_CALL();
1910 ALOGV("preComposition");
1911
David Sodman2b406362017-12-15 13:33:47 -08001912 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1913
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001915 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001916 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001917 needExtraInvalidate = true;
1918 }
Robert Carr2047fae2016-11-28 14:09:09 -08001919 });
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 if (needExtraInvalidate) {
1922 signalLayerUpdate();
1923 }
1924}
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1927 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 // Update queue of past composite+present times and determine the
1929 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001930 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001932 while (!getBE().mCompositePresentTimes.empty()) {
1933 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 // Cached values should have been updated before calling this method,
1935 // which helps avoid duplicate syscalls.
1936 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1937 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1938 break;
1939 }
1940 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001941 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 }
1943
1944 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001945 while (getBE().mCompositePresentTimes.size() > 16) {
1946 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 }
1948
Ana Krulece588e312018-09-18 12:32:24 -07001949 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001950}
1951
Ana Krulece588e312018-09-18 12:32:24 -07001952void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1953 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Integer division and modulo round toward 0 not -inf, so we need to
1955 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001956 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1957 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1958 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959
Ana Krulec757f63a2019-01-25 10:46:18 -08001960 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001961 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001962 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001963 }
1964
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965 // Snap the latency to a value that removes scheduling jitter from the
1966 // composition and present times, which often have >1ms of jitter.
1967 // Reducing jitter is important if an app attempts to extrapolate
1968 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001971 nsecs_t bias = stats.vsyncPeriod / 2;
1972 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1973 nsecs_t snappedCompositeToPresentLatency =
1974 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
David Sodman99974d22017-11-28 12:04:33 -08001976 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001977 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1978 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001979 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980}
1981
David Sodman2b406362017-12-15 13:33:47 -08001982void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001983{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 ATRACE_CALL();
1985 ALOGV("postComposition");
1986
Brian Anderson3546a3f2016-07-14 11:51:14 -07001987 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001988 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001989 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001990 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001991 }
1992
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001993 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001994 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995
David Sodman73beded2017-11-15 11:56:06 -08001996 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001997 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001998 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002000 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2001 ->getRenderSurface()
2002 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002003 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002004 } else {
2005 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2006 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007
David Sodman73beded2017-11-15 11:56:06 -08002008 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002009 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2010 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002011 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08002012 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002013
Ana Krulece588e312018-09-18 12:32:24 -07002014 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002015 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016
David Sodman2b406362017-12-15 13:33:47 -08002017 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // when we started doing work for this frame, but that should be okay
2019 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002020 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002021 CompositorTiming compositorTiming;
2022 {
David Sodman99974d22017-11-28 12:04:33 -08002023 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2024 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002025 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002026
Robert Carr2047fae2016-11-28 14:09:09 -08002027 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002028 bool frameLatched =
2029 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2030 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002031 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002032 recordBufferingStats(layer->getName().string(),
2033 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002034 }
Robert Carr2047fae2016-11-28 14:09:09 -08002035 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002036
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002037 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002038 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002039 }
2040
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002041 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002042 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2043 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002044 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002045 }
2046 }
2047
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002048 if (mAnimCompositionPending) {
2049 mAnimCompositionPending = false;
2050
Brian Anderson4e606e32017-03-16 15:34:57 -07002051 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002052 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002053 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002055 // The HWC doesn't support present fences, so use the refresh
2056 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002057 const nsecs_t presentTime =
2058 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002059 mAnimFrameTracker.setActualPresentTime(presentTime);
2060 }
2061 mAnimFrameTracker.advanceFrame();
2062 }
Dan Stozab90cf072015-03-05 11:05:59 -08002063
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002064 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002065 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002066 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002067 }
2068
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002069 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002070
Lloyd Pique32cbe282018-10-19 13:09:22 -07002071 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2072 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002073 return;
2074 }
2075
2076 nsecs_t currentTime = systemTime();
2077 if (mHasPoweredOff) {
2078 mHasPoweredOff = false;
2079 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002080 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002081 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002082 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2083 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002084 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002085 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002086 }
David Sodman4a36e932017-11-07 14:29:47 -08002087 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002088 }
David Sodman4a36e932017-11-07 14:29:47 -08002089 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002090
2091 {
2092 std::lock_guard lock(mTexturePoolMutex);
2093 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2094 if (refillCount > 0) {
2095 const size_t offset = mTexturePool.size();
2096 mTexturePool.resize(mTexturePoolSize);
2097 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2098 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2099 }
2100 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002101
Marissa Wallfda30bb2018-10-12 11:34:28 -07002102 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002103 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002104
Kevin DuBois413287f2019-02-25 08:46:47 -08002105 if (mLumaSampling && mRegionSamplingThread) {
2106 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002107 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002108}
2109
Vishnu Nair4351ad52019-02-11 14:13:02 -08002110void SurfaceFlinger::computeLayerBounds() {
2111 for (const auto& pair : mDisplays) {
2112 const auto& displayDevice = pair.second;
2113 const auto display = displayDevice->getCompositionDisplay();
2114 for (const auto& layer : mDrawingState.layersSortedByZ) {
2115 // only consider the layers on the given layer stack
2116 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002117 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002118 }
2119
2120 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2121 }
2122 }
2123}
2124
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 ATRACE_CALL();
2127 ALOGV("rebuildLayerStacks");
2128
Mathias Agopiancd60f992012-08-16 16:28:27 -07002129 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002130 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002131 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002132 mVisibleRegionsDirty = false;
2133 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002134
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002135 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002136 const auto& displayDevice = pair.second;
2137 auto display = displayDevice->getCompositionDisplay();
2138 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002139 Region opaqueRegion;
2140 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002141 compositionengine::Output::OutputLayers layersSortedByZ;
2142 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002143 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002144 const ui::Transform& tr = displayState.transform;
2145 const Rect bounds = displayState.bounds;
2146 if (displayState.isEnabled) {
2147 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002148
Jeff Sharkey76488112017-02-27 14:15:18 -07002149 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002150 auto compositionLayer = layer->getCompositionLayer();
2151 if (compositionLayer == nullptr) {
2152 return;
2153 }
2154
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002156 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2157 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2158
Lloyd Pique07e33212018-12-18 16:33:37 -08002159 bool needsOutputLayer = false;
2160
Lloyd Piqueef36b002019-01-23 17:52:04 -08002161 if (display->belongsInOutput(layer->getLayerStack(),
2162 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002163 Region drawRegion(tr.transform(
2164 layer->visibleNonTransparentRegion));
2165 drawRegion.andSelf(bounds);
2166 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002167 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002168 }
Chia-I Wu83806892017-11-16 10:50:20 -08002169 }
2170
Lloyd Pique07e33212018-12-18 16:33:37 -08002171 if (needsOutputLayer) {
2172 layersSortedByZ.emplace_back(
2173 display->getOrCreateOutputLayer(displayId, compositionLayer,
2174 layerFE));
2175 deprecated_layersSortedByZ.add(layer);
2176
2177 auto& outputLayerState = layersSortedByZ.back()->editState();
2178 outputLayerState.visibleRegion =
2179 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2180 } else if (displayId) {
2181 // For layers that are being removed from a HWC display,
2182 // and that have queued frames, add them to a a list of
2183 // released layers so we can properly set a fence.
2184 bool hasExistingOutputLayer =
2185 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2186 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2187 mLayersWithQueuedFrames.cend(),
2188 layer) != mLayersWithQueuedFrames.cend();
2189
2190 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002191 layersNeedingFences.add(layer);
2192 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002193 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002194 });
2195 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002196
2197 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2198
2199 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 displayDevice->setLayersNeedingFences(layersNeedingFences);
2201
2202 Region undefinedRegion{bounds};
2203 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2204
2205 display->editState().undefinedRegion = undefinedRegion;
2206 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002207 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002208 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002209}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002210
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002211// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002212// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002213// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002214// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002215// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002216// The returned HDR data space is one of
2217// - Dataspace::UNKNOWN
2218// - Dataspace::BT2020_HLG
2219// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002220Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2221 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002222 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002223 *outHdrDataSpace = Dataspace::UNKNOWN;
2224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002225 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002226 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002227 case Dataspace::V0_SCRGB:
2228 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002229 case Dataspace::BT2020:
2230 case Dataspace::BT2020_ITU:
2231 case Dataspace::BT2020_LINEAR:
2232 case Dataspace::DISPLAY_BT2020:
2233 bestDataSpace = Dataspace::DISPLAY_BT2020;
2234 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002235 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002236 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002237 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238 case Dataspace::BT2020_PQ:
2239 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002240 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002241 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002242 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002243 case Dataspace::BT2020_HLG:
2244 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002245 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246 // When there's mixed PQ content and HLG content, we set the HDR
2247 // data space to be BT2020_PQ and convert HLG to PQ.
2248 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2249 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002250 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251 break;
2252 default:
2253 break;
2254 }
Romain Guy54f154a2017-10-24 21:40:32 +01002255 }
2256
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002257 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002258}
2259
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2262 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2264 *outMode = ColorMode::NATIVE;
2265 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002266 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002268 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002269
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002273 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2274
Peiyong Lina3ea5592019-02-10 14:45:00 -08002275 switch (mForceColorMode) {
2276 case ColorMode::SRGB:
2277 bestDataSpace = Dataspace::V0_SRGB;
2278 break;
2279 case ColorMode::DISPLAY_P3:
2280 bestDataSpace = Dataspace::DISPLAY_P3;
2281 break;
2282 default:
2283 break;
2284 }
2285
Peiyong Lindfde5112018-06-05 10:58:41 -07002286 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002287 const bool isHdr =
2288 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002289 if (isHdr) {
2290 bestDataSpace = hdrDataSpace;
2291 }
2292
Chia-I Wu0d711262018-05-21 15:19:35 -07002293 RenderIntent intent;
2294 switch (mDisplayColorSetting) {
2295 case DisplayColorSetting::MANAGED:
2296 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002297 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002298 break;
2299 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002300 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002301 break;
2302 default: // vendor display color setting
2303 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2304 break;
2305 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002306
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002307 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002308}
2309
Lloyd Pique32cbe282018-10-19 13:09:22 -07002310void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2311 auto display = displayDevice->getCompositionDisplay();
2312 const auto& displayState = display->getState();
2313
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002314 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002315 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2316 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002317
David Sodmanfa9b2af2017-12-24 13:28:59 -08002318 // If nothing has changed (!dirty), don't recompose.
2319 // If something changed, but we don't currently have any visible layers,
2320 // and didn't when we last did a composition, then skip it this time.
2321 // The second rule does two things:
2322 // - When all layers are removed from a display, we'll emit one black
2323 // frame, then nothing more until we get new layers.
2324 // - When a display is created with a private layer stack, we won't
2325 // emit any black frames until a layer is added to the layer stack.
2326 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 const char flagPrefix[] = {'-', '+'};
2329 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002330 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2331 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2332 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2333 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002334
Lloyd Pique31cb2942018-10-19 17:23:03 -07002335 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002336
David Sodmanfa9b2af2017-12-24 13:28:59 -08002337 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002338 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002339 }
2340}
2341
Lloyd Pique32cbe282018-10-19 13:09:22 -07002342void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2343 auto display = displayDevice->getCompositionDisplay();
2344 const auto& displayState = display->getState();
2345
2346 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002347 return;
David Sodman2b406362017-12-15 13:33:47 -08002348 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002349
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002350 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002351 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002352 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002353}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002354
Lloyd Pique32cbe282018-10-19 13:09:22 -07002355void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002356 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357 ALOGV("doComposition");
2358
Lloyd Pique32cbe282018-10-19 13:09:22 -07002359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
2361
2362 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002363 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002364 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002365
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002367 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002368
Lloyd Pique32cbe282018-10-19 13:09:22 -07002369 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002370 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002371 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002373}
2374
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375void SurfaceFlinger::postFrame()
2376{
2377 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378 const auto display = getDefaultDisplayDeviceLocked();
2379 if (display && getHwComposer().isConnected(*display->getId())) {
2380 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002381 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2382 logFrameStats();
2383 }
2384 }
2385}
2386
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002388 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002390
Lloyd Pique32cbe282018-10-19 13:09:22 -07002391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393 const auto displayId = display->getId();
2394
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002396
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 if (displayId) {
2399 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002400 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002401 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002402 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002403 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002404 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002405
Chia-I Wu7b549592017-11-15 09:14:57 -08002406 // The layer buffer from the previous frame (if any) is released
2407 // by HWC only when the release fence from this frame (if any) is
2408 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002409 if (layer->getState().hwc) {
2410 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002411 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002412 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2413 usedClientComposition =
2414 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002415 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002416
2417 // If the layer was client composited in the previous frame, we
2418 // need to merge with the previous client target acquire fence.
2419 // Since we do not track that, always merge with the current
2420 // client target acquire fence when it is available, even though
2421 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002422 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002423 releaseFence =
2424 Fence::merge("LayerRelease", releaseFence,
2425 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002426 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002427
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002428 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 }
Chia-I Wu83806892017-11-16 10:50:20 -08002430
2431 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002433 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002436 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002438 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002439 }
2440 }
2441
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 if (displayId) {
2443 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002444 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446}
2447
Mathias Agopian87baae12012-07-31 12:38:26 -07002448void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449{
Mathias Agopian841cde52012-03-01 15:44:37 -08002450 ATRACE_CALL();
2451
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002452 // here we keep a copy of the drawing state (that is the state that's
2453 // going to be overwritten by handleTransactionLocked()) outside of
2454 // mStateLock so that the side-effects of the State assignment
2455 // don't happen with mStateLock held (which can cause deadlocks).
2456 State drawingState(mDrawingState);
2457
Mathias Agopianca4d3602011-05-19 15:38:14 -07002458 Mutex::Autolock _l(mStateLock);
2459 const nsecs_t now = systemTime();
2460 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461
Mathias Agopianca4d3602011-05-19 15:38:14 -07002462 // Here we're guaranteed that some transaction flags are set
2463 // so we can call handleTransactionLocked() unconditionally.
2464 // We call getTransactionFlags(), which will also clear the flags,
2465 // with mStateLock held to guarantee that mCurrentState won't change
2466 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002467
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002468 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002470 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002471
Mathias Agopianca4d3602011-05-19 15:38:14 -07002472 mLastTransactionTime = systemTime() - now;
2473 mDebugInTransaction = 0;
2474 invalidateHwcGeometry();
2475 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002476}
2477
Lloyd Piqueba04e622017-12-14 17:11:26 -08002478void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2479 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 const std::optional<DisplayIdentificationInfo> info =
2481 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002482
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002484 continue;
2485 }
2486
Lloyd Piqueba04e622017-12-14 17:11:26 -08002487 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002489 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 mPhysicalDisplayTokens[info->id] = new BBinder();
2491 DisplayDeviceState state;
2492 state.displayId = info->id;
2493 state.isSecure = true; // All physical displays are currently considered secure.
2494 state.displayName = info->name;
2495 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2496 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002497 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002499 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002500
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2502 if (index >= 0) {
2503 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2504 mInterceptor->saveDisplayDeletion(state.sequenceId);
2505 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002506 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002508 }
2509
2510 processDisplayChangesLocked();
2511 }
2512
2513 mPendingHotplugEvents.clear();
2514}
2515
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002516void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002517 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2518 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002519}
2520
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002523 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 const sp<IGraphicBufferProducer>& producer) {
2525 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002526 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002528 creationArgs.isSecure = state.isSecure;
2529 creationArgs.displaySurface = dispSurface;
2530 creationArgs.hasWideColorGamut = false;
2531 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002532
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002533 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 creationArgs.isPrimary = isInternalDisplay;
2535
2536 if (useColorManagement && displayId) {
2537 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002539 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002540 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002541 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002542
Dominik Laskowski7e045462018-05-30 13:02:02 -07002543 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002545 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546 }
tangrobin6753a022018-08-10 10:58:54 +08002547 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 if (displayId) {
2550 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002551 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002553 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554
Lloyd Pique90c115d2018-09-18 21:39:42 -07002555 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002557 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559 // Make sure that composition can never be stalled by a virtual display
2560 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002561 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002562 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2564 }
2565
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 creationArgs.displayInstallOrientation =
2567 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002568
Lloyd Pique99d3da52018-01-22 17:48:03 -08002569 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002570 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571
Lloyd Pique90c115d2018-09-18 21:39:42 -07002572 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
2574 if (maxFrameBufferAcquiredBuffers >= 3) {
2575 nativeWindowSurface->preallocateBuffers();
2576 }
2577
2578 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002579 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002580 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002582 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002583 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002584 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2585 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 if (!state.isVirtual()) {
2587 LOG_ALWAYS_FATAL_IF(!displayId);
2588 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002589 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002591 display->setLayerStack(state.layerStack);
2592 display->setProjection(state.orientation, state.viewport, state.frame);
2593 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002595 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596}
2597
Lloyd Pique347200f2017-12-14 17:00:15 -08002598void SurfaceFlinger::processDisplayChangesLocked() {
2599 // here we take advantage of Vector's copy-on-write semantics to
2600 // improve performance by skipping the transaction entirely when
2601 // know that the lists are identical
2602 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2603 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2604 if (!curr.isIdenticalTo(draw)) {
2605 mVisibleRegionsDirty = true;
2606 const size_t cc = curr.size();
2607 size_t dc = draw.size();
2608
2609 // find the displays that were removed
2610 // (ie: in drawing state but not in current state)
2611 // also handle displays that changed
2612 // (ie: displays that are in both lists)
2613 for (size_t i = 0; i < dc;) {
2614 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2615 if (j < 0) {
2616 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002617 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002618 // Save display ID before disconnecting.
2619 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002620 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002621
2622 if (!display->isVirtual()) {
2623 LOG_ALWAYS_FATAL_IF(!displayId);
2624 dispatchDisplayHotplugEvent(displayId->value, false);
2625 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002626 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002627
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002628 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002629 } else {
2630 // this display is in both lists. see if something changed.
2631 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2634 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2635 if (state_binder != draw_binder) {
2636 // changing the surface is like destroying and
2637 // recreating the DisplayDevice, so we just remove it
2638 // from the drawing state, so that it get re-added
2639 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002641 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002642 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002643 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002644 mDrawingState.displays.removeItemsAt(i);
2645 dc--;
2646 // at this point we must loop to the next item
2647 continue;
2648 }
2649
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002650 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 }
2654 if ((state.orientation != draw[i].orientation) ||
2655 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002657 }
2658 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002659 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 }
2661 }
2662 }
2663 ++i;
2664 }
2665
2666 // find displays that were added
2667 // (ie: in current state but not in drawing state)
2668 for (size_t i = 0; i < cc; i++) {
2669 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2670 const DisplayDeviceState& state(curr[i]);
2671
Lloyd Pique542307f2018-10-19 13:24:08 -07002672 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 sp<IGraphicBufferProducer> producer;
2674 sp<IGraphicBufferProducer> bqProducer;
2675 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002676 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677
Dominik Laskowski075d3172018-05-24 15:50:06 -07002678 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002679 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 // Virtual displays without a surface are dormant:
2681 // they have external state (layer stack, projection,
2682 // etc.) but no internal state (i.e. a DisplayDevice).
2683 if (state.surface != nullptr) {
2684 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002685 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 int width = 0;
2687 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2688 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2689 int height = 0;
2690 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2691 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2692 int intFormat = 0;
2693 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2694 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002695 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696
Dominik Laskowski075d3172018-05-24 15:50:06 -07002697 displayId =
2698 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699 }
2700
2701 // TODO: Plumb requested format back up to consumer
2702
2703 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002704 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 bqProducer, bqConsumer,
2706 state.displayName);
2707
2708 dispSurface = vds;
2709 producer = vds;
2710 }
2711 } else {
2712 ALOGE_IF(state.surface != nullptr,
2713 "adding a supported display, but rendering "
2714 "surface is provided (%p), ignoring it",
2715 state.surface.get());
2716
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 displayId = state.displayId;
2718 LOG_ALWAYS_FATAL_IF(!displayId);
2719 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 producer = bqProducer;
2721 }
2722
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002725 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002726 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002727 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002728 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002730 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 }
2732 }
2733 }
2734 }
2735 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002736
2737 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002738}
2739
Mathias Agopian87baae12012-07-31 12:38:26 -07002740void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002741{
Dan Stoza7dde5992015-05-22 09:51:44 -07002742 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002743 mCurrentState.traverseInZOrder([](Layer* layer) {
2744 layer->notifyAvailableFrames();
2745 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 /*
2748 * Traversal of the children
2749 * (perform the transaction for each of them if needed)
2750 */
2751
Mathias Agopian3559b072012-08-15 13:46:03 -07002752 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002753 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002755 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756
2757 const uint32_t flags = layer->doTransaction(0);
2758 if (flags & Layer::eVisibleRegion)
2759 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002760
2761 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002762 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002763 }
Robert Carr2047fae2016-11-28 14:09:09 -08002764 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 }
2766
2767 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002768 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 */
2770
Mathias Agopiane57f2922012-08-09 16:29:12 -07002771 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002773 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002776 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002777 // The transform hint might have changed for some layers
2778 // (either because a display has changed, or because a layer
2779 // as changed).
2780 //
2781 // Walk through all the layers in currentLayers,
2782 // and update their transform hint.
2783 //
2784 // If a layer is visible only on a single display, then that
2785 // display is used to calculate the hint, otherwise we use the
2786 // default display.
2787 //
2788 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2789 // the hint is set before we acquire a buffer from the surface texture.
2790 //
2791 // NOTE: layer transactions have taken place already, so we use their
2792 // drawing state. However, SurfaceFlinger's own transaction has not
2793 // happened yet, so we must use the current state layer list
2794 // (soon to become the drawing state list).
2795 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002797 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002798 bool first = true;
2799 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002800 // NOTE: we rely on the fact that layers are sorted by
2801 // layerStack first (so we don't have to traverse the list
2802 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002804 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002805 currentlayerStack = layerStack;
2806 // figure out if this layerstack is mirrored
2807 // (more than one display) if so, pick the default display,
2808 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 hintDisplay = nullptr;
2810 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002811 if (display->getCompositionDisplay()
2812 ->belongsInOutput(layer->getLayerStack(),
2813 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 if (hintDisplay) {
2815 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002816 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002819 }
2820 }
2821 }
2822 }
Chet Haase91d25932013-04-11 15:24:55 -07002823
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002825 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2826 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002827
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002828 // could be null when this layer is using a layerStack
2829 // that is not visible on any display. Also can occur at
2830 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002832 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002835 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 if (hintDisplay) {
2837 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839
2840 first = false;
2841 });
Mathias Agopian84300952012-11-21 16:02:13 -08002842 }
2843
2844
Mathias Agopian3559b072012-08-15 13:46:03 -07002845 /*
2846 * Perform our own transaction if needed
2847 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848
2849 if (mLayersAdded) {
2850 mLayersAdded = false;
2851 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002852 mVisibleRegionsDirty = true;
2853 }
2854
2855 // some layers might have been removed, so
2856 // we need to update the regions they're exposing.
2857 if (mLayersRemoved) {
2858 mLayersRemoved = false;
2859 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002860 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002861 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002862 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002863 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002864 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002865 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002866 }
Robert Carr2047fae2016-11-28 14:09:09 -08002867 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 }
2869
Vishnu Nairec0ab382019-02-13 15:32:56 -08002870 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002872}
2873
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002874void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002875 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002876 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002877 return;
2878 }
2879
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880 if (mVisibleRegionsDirty || mInputInfoChanged) {
2881 mInputInfoChanged = false;
2882 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002883 } else if (mInputWindowCommands.syncInputWindows) {
2884 // If the caller requested to sync input windows, but there are no
2885 // changes to input windows, notify immediately.
2886 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002887 }
2888
2889 executeInputWindowCommands();
2890}
2891
2892void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002893 Vector<InputWindowInfo> inputHandles;
2894
2895 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2896 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002897 // When calculating the screen bounds we ignore the transparent region since it may
2898 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002899 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002900 }
2901 });
chaviw291d88a2019-02-14 10:33:58 -08002902
2903 mInputFlinger->setInputWindows(inputHandles,
2904 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2905 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002906}
2907
Vishnu Nairec0ab382019-02-13 15:32:56 -08002908void SurfaceFlinger::commitInputWindowCommands() {
2909 mInputWindowCommands.merge(mPendingInputWindowCommands);
2910 mPendingInputWindowCommands.clear();
2911}
2912
chaviwfbe5d9c2018-12-26 12:23:37 -08002913void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002914 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2915 if (transferTouchFocusCommand.fromToken != nullptr &&
2916 transferTouchFocusCommand.toToken != nullptr &&
2917 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2918 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2919 transferTouchFocusCommand.toToken);
2920 }
2921 }
2922
2923 mInputWindowCommands.clear();
2924}
2925
Riley Andrews03414a12014-07-01 14:22:59 -07002926void SurfaceFlinger::updateCursorAsync()
2927{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002928 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002929 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002930 continue;
2931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2934 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002935 }
2936 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002937}
2938
chaviw61626f22018-11-15 16:26:27 -08002939void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2940 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002941 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002942 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002943 }
2944 layer->releasePendingBuffer(systemTime());
2945}
2946
Mathias Agopian4fec8732012-06-29 14:12:52 -07002947void SurfaceFlinger::commitTransaction()
2948{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002949 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002950 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 for (const auto& l : mLayersPendingRemoval) {
2952 recordBufferingStats(l->getName().string(),
2953 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002954
Lloyd Pique07e33212018-12-18 16:33:37 -08002955 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002956 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002957 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002958 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 }
2960 mLayersPendingRemoval.clear();
2961 }
2962
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002963 // If this transaction is part of a window animation then the next frame
2964 // we composite should be considered an animation as well.
2965 mAnimCompositionPending = mAnimTransactionPending;
2966
Nataniel Borges2b796da2019-02-15 13:32:18 -08002967 withTracingLock([&]() {
2968 mDrawingState = mCurrentState;
2969 // clear the "changed" flags in current state
2970 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002971
Nataniel Borges2b796da2019-02-15 13:32:18 -08002972 mDrawingState.traverseInZOrder([](Layer* layer) { layer->commitChildList(); });
Robert Carr1f0a16a2016-10-24 16:27:39 -07002973 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002974
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002975 mTransactionPending = false;
2976 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002977 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978}
2979
Nataniel Borges2b796da2019-02-15 13:32:18 -08002980void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2981 if (mTracingEnabledChanged) {
2982 mTracingEnabled = mTracing.isEnabled();
2983 mTracingEnabledChanged = false;
2984 }
2985
2986 // Synchronize with Tracing thread
2987 std::unique_lock<std::mutex> lock;
2988 if (mTracingEnabled) {
2989 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2990 }
2991
2992 lockedOperation();
2993
2994 // Synchronize with Tracing thread
2995 if (mTracingEnabled) {
2996 lock.unlock();
2997 }
2998}
2999
Lloyd Pique32cbe282018-10-19 13:09:22 -07003000void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003002 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003004
Lloyd Pique32cbe282018-10-19 13:09:22 -07003005 auto display = displayDevice->getCompositionDisplay();
3006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007 Region aboveOpaqueLayers;
3008 Region aboveCoveredLayers;
3009 Region dirty;
3010
Mathias Agopian87baae12012-07-31 12:38:26 -07003011 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012
Robert Carr2047fae2016-11-28 14:09:09 -08003013 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003014 // start with the whole surface at its current location
3015 const Layer::State& s(layer->getDrawingState());
3016
Jesse Hall01e29052013-02-19 16:13:35 -08003017 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003018 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003019 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003021
Mathias Agopianab028732010-03-16 16:41:46 -07003022 /*
3023 * opaqueRegion: area of a surface that is fully opaque.
3024 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003026
3027 /*
3028 * visibleRegion: area of a surface that is visible on screen
3029 * and not fully transparent. This is essentially the layer's
3030 * footprint minus the opaque regions above it.
3031 * Areas covered by a translucent surface are considered visible.
3032 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003034
3035 /*
3036 * coveredRegion: area of a surface that is covered by all
3037 * visible regions above it (which includes the translucent areas).
3038 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003040
Jesse Halla8026d22012-09-25 13:25:04 -07003041 /*
3042 * transparentRegion: area of a surface that is hinted to be completely
3043 * transparent. This is only used to tell when the layer has no visible
3044 * non-transparent regions and can be removed from the layer list. It
3045 * does not affect the visibleRegion of this layer or any layers
3046 * beneath it. The hint may not be correct if apps don't respect the
3047 * SurfaceView restrictions (which, sadly, some don't).
3048 */
3049 Region transparentRegion;
3050
Mathias Agopianab028732010-03-16 16:41:46 -07003051
3052 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003053 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003054 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003055 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003058 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003059 if (!visibleRegion.isEmpty()) {
3060 // Remove the transparent area from the visible region
3061 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003062 if (tr.preserveRects()) {
3063 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003064 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003066 // transformation too complex, can't do the
3067 // transparent region optimization.
3068 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003069 }
Mathias Agopianab028732010-03-16 16:41:46 -07003070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071
Mathias Agopianab028732010-03-16 16:41:46 -07003072 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003074 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003075 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003076 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003077 // the opaque region is the layer's footprint
3078 opaqueRegion = visibleRegion;
3079 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 }
3081 }
3082
Robert Carre5f4f692018-01-12 13:12:28 -08003083 if (visibleRegion.isEmpty()) {
3084 layer->clearVisibilityRegions();
3085 return;
3086 }
3087
Mathias Agopianab028732010-03-16 16:41:46 -07003088 // Clip the covered region to the visible region
3089 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3090
3091 // Update aboveCoveredLayers for next (lower) layer
3092 aboveCoveredLayers.orSelf(visibleRegion);
3093
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 // subtract the opaque region covered by the layers above us
3095 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096
3097 // compute this layer's dirty region
3098 if (layer->contentDirty) {
3099 // we need to invalidate the whole region
3100 dirty = visibleRegion;
3101 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003102 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 layer->contentDirty = false;
3104 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003105 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003106 * the exposed region consists of two components:
3107 * 1) what's VISIBLE now and was COVERED before
3108 * 2) what's EXPOSED now less what was EXPOSED before
3109 *
3110 * note that (1) is conservative, we start with the whole
3111 * visible region but only keep what used to be covered by
3112 * something -- which mean it may have been exposed.
3113 *
3114 * (2) handles areas that were not covered by anything but got
3115 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003116 */
Mathias Agopianab028732010-03-16 16:41:46 -07003117 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003118 const Region oldVisibleRegion = layer->visibleRegion;
3119 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003120 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3121 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 }
3123 dirty.subtractSelf(aboveOpaqueLayers);
3124
3125 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003126 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127
Mathias Agopianab028732010-03-16 16:41:46 -07003128 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003130
Jesse Halla8026d22012-09-25 13:25:04 -07003131 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 layer->setVisibleRegion(visibleRegion);
3133 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003134 layer->setVisibleNonTransparentRegion(
3135 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003136 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137
Mathias Agopian87baae12012-07-31 12:38:26 -07003138 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139}
3140
Chia-I Wuab0c3192017-08-01 11:29:00 -07003141void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003142 for (const auto& [token, displayDevice] : mDisplays) {
3143 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003144 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003145 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003146 }
3147 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003148}
3149
Dan Stoza6b9454d2014-11-07 16:00:59 -08003150bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003152 ALOGV("handlePageFlip");
3153
Brian Andersond6927fb2016-07-23 23:37:30 -07003154 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Mathias Agopian4fec8732012-06-29 14:12:52 -07003156 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003157 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003158 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003159
3160 // Store the set of layers that need updates. This set must not change as
3161 // buffers are being latched, as this could result in a deadlock.
3162 // Example: Two producers share the same command stream and:
3163 // 1.) Layer 0 is latched
3164 // 2.) Layer 0 gets a new frame
3165 // 2.) Layer 1 gets a new frame
3166 // 3.) Layer 1 is latched.
3167 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3168 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003169 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003170 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003171 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003172 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003173 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003174 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003175 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003176 } else {
3177 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003178 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003179 } else {
3180 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003181 }
Robert Carr2047fae2016-11-28 14:09:09 -08003182 });
3183
Lloyd Piquef2c79392018-12-20 16:23:33 -08003184 if (!mLayersWithQueuedFrames.empty()) {
3185 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3186 // writes to Layer current state. See also b/119481871
3187 Mutex::Autolock lock(mStateLock);
3188
3189 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003190 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003191 mLayersPendingRefresh.push_back(layer);
3192 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003193 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003194 if (layer->isBufferLatched()) {
3195 newDataLatched = true;
3196 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003197 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003198 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003199
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003200 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003201
3202 // If we will need to wake up at some time in the future to deal with a
3203 // queued frame that shouldn't be displayed during this vsync period, wake
3204 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003205 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003206 signalLayerUpdate();
3207 }
3208
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003209 // enter boot animation on first buffer latch
3210 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3211 ALOGI("Enter boot animation");
3212 mBootStage = BootStage::BOOTANIMATION;
3213 }
3214
Dan Stoza6b9454d2014-11-07 16:00:59 -08003215 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003216 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217}
3218
Mathias Agopianad456f92011-01-13 17:53:01 -08003219void SurfaceFlinger::invalidateHwcGeometry()
3220{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003221 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003222}
3223
Lloyd Pique32cbe282018-10-19 13:09:22 -07003224void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003225 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003226 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003227 // We only need to actually compose the display if:
3228 // 1) It is being handled by hardware composer, which may need this to
3229 // keep its virtual display state machine in sync, or
3230 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003231 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003232 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003233 return;
3234 }
3235
Dan Stoza9e56aa02015-11-02 13:00:03 -08003236 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003237 base::unique_fd readyFence;
3238 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003239
3240 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003241 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003244bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3245 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003246 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003247 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003248
Lloyd Pique32cbe282018-10-19 13:09:22 -07003249 auto display = displayDevice->getCompositionDisplay();
3250 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003251 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003252 auto& renderEngine = getRenderEngine();
3253 const bool supportProtectedContent =
3254 mDebugEnableProtectedContent && renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003255
3256 const Region bounds(displayState.bounds);
3257 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003258 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003259 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003260
Peiyong Lind3788632018-09-18 16:01:31 -07003261 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003262 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003263
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003264 renderengine::DisplaySettings clientCompositionDisplay;
3265 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3266 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003267 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003268
Dan Stoza9e56aa02015-11-02 13:00:03 -08003269 if (hasClientComposition) {
3270 ALOGV("hasClientComposition");
3271
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003272 if (displayDevice->isPrimary() && supportProtectedContent) {
3273 bool needsProtected = false;
3274 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3275 // If the layer is a protected layer, mark protected context is needed.
3276 if (layer->isProtected()) {
3277 needsProtected = true;
3278 break;
3279 }
3280 }
3281 if (needsProtected != renderEngine.isProtected() &&
3282 renderEngine.useProtectedContext(needsProtected)) {
3283 display->getRenderSurface()->setProtected(needsProtected);
3284 }
3285 }
3286
Alec Mouri6338c9d2019-02-07 16:57:51 -08003287 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003288
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003289 if (buf == nullptr) {
3290 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3291 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003292 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003293 return false;
3294 }
3295
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003296 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3297 clientCompositionDisplay.clip = displayState.scissor;
3298 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003299 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003300
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003301 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003302 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003303 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003304 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003305 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003306 clientCompositionDisplay.outputDataspace = outputDataspace;
3307 clientCompositionDisplay.maxLuminance =
3308 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003309
Lloyd Pique441d5042018-10-18 16:49:51 -07003310 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003311 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 getHwComposer()
3313 .hasDisplayCapability(displayId,
3314 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003315
Peiyong Lind3788632018-09-18 16:01:31 -07003316 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003317 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3318 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003319 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003320 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003321 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003322
Mathias Agopian85d751c2012-08-29 16:59:24 -07003323 /*
3324 * and then, render the layers targeted at the framebuffer
3325 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003326
Dan Stoza9e56aa02015-11-02 13:00:03 -08003327 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003328 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003329 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003331 const Region viewportRegion(displayState.viewport);
3332 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003333 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003334 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003335 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003336 switch (layer->getCompositionType(displayDevice)) {
3337 case Hwc2::IComposerClient::Composition::CURSOR:
3338 case Hwc2::IComposerClient::Composition::DEVICE:
3339 case Hwc2::IComposerClient::Composition::SIDEBAND:
3340 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003341 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003342 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003343 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003344 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003345 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003346 // never clear the very first layer since we're
3347 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003348 renderengine::LayerSettings layerSettings;
3349 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003350 bool prepared =
3351 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3352 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003353
3354 if (prepared) {
3355 layerSettings.source.buffer.buffer = nullptr;
3356 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3357 layerSettings.alpha = half(0.0);
3358 layerSettings.disableBlending = true;
3359 clientCompositionLayers.push_back(layerSettings);
3360 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003361 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003362 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003363 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003364 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003365 renderengine::LayerSettings layerSettings;
3366 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003367 layer->prepareClientLayer(renderArea, clip, clearRegion,
3368 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003369 if (prepared) {
3370 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003371 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003372 break;
3373 }
3374 default:
3375 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003376 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003377 } else {
3378 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003379 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003380 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003381 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003382
Alec Mouri820c7402019-01-23 13:02:39 -08003383 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003384 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003386
3387 // We boost GPU frequency here because there will be color spaces conversion
3388 // and it's expensive. We boost the GPU frequency so that GPU composition can
3389 // finish in time. We must reset GPU frequency afterwards, because high frequency
3390 // consumes extra battery.
3391 const bool expensiveRenderingExpected =
3392 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3393 if (expensiveRenderingExpected && displayId) {
3394 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3395 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003396 if (!debugRegion.isEmpty()) {
3397 Region::const_iterator it = debugRegion.begin();
3398 Region::const_iterator end = debugRegion.end();
3399 while (it != end) {
3400 const Rect& rect = *it++;
3401 renderengine::LayerSettings layerSettings;
3402 layerSettings.source.buffer.buffer = nullptr;
3403 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3404 layerSettings.geometry.boundaries = rect.toFloatRect();
3405 layerSettings.alpha = half(1.0);
3406 clientCompositionLayers.push_back(layerSettings);
3407 }
3408 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003409 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3410 buf->getNativeBuffer(), std::move(fd), readyFence);
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003411 if (expensiveRenderingExpected && displayId) {
3412 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3413 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003415 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003416}
3417
Chia-I Wu28e3a252018-09-07 12:05:02 -07003418void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003419 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003420 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003421}
3422
Dan Stoza7d89d062015-04-30 13:29:25 -07003423status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003424 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003425 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003426 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003427 const sp<Layer>& parent,
3428 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003429{
Dan Stoza7d89d062015-04-30 13:29:25 -07003430 // add this layer to the current state list
3431 {
3432 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003433 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003434 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3435 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003436 return NO_MEMORY;
3437 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003438 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003439 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003440 } else if (parent == nullptr) {
3441 lbc->onRemovedFromCurrentState();
3442 } else if (parent->isRemovedFromCurrentState()) {
3443 parent->addChild(lbc);
3444 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003445 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003446 parent->addChild(lbc);
3447 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003448
Yiwei Zhang243b3782018-05-15 17:40:04 -07003449 if (gbc != nullptr) {
3450 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3451 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3452 mMaxGraphicBufferProducerListSize,
3453 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3454 mGraphicBufferProducerList.size(),
3455 mMaxGraphicBufferProducerListSize, mNumLayers);
3456 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003457 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003458 }
3459
Mathias Agopian96f08192010-06-02 23:28:45 -07003460 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003461 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003462
Dan Stoza7d89d062015-04-30 13:29:25 -07003463 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003464}
3465
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003466uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003467 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003468}
3469
Mathias Agopian3f844832013-08-07 21:24:32 -07003470uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003471 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472}
3473
Mathias Agopian3f844832013-08-07 21:24:32 -07003474uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003475 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003476}
3477
3478uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003479 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003480 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003481 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003483 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 }
3485 return old;
3486}
3487
Marissa Wall713b63f2018-10-17 15:42:43 -07003488bool SurfaceFlinger::flushTransactionQueues() {
3489 Mutex::Autolock _l(mStateLock);
3490 auto it = mTransactionQueues.begin();
3491 while (it != mTransactionQueues.end()) {
3492 auto& [applyToken, transactionQueue] = *it;
3493
3494 while (!transactionQueue.empty()) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003495 const auto& [states, displays, flags, desiredPresentTime, postTime, privileged] =
Robert Carr14167e02019-02-13 13:50:55 -08003496 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003497 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003498 break;
3499 }
Valerie Haubc6ddb12019-03-08 11:10:15 -08003500 applyTransactionState(states, displays, flags, mPendingInputWindowCommands,
3501 desiredPresentTime, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003502 transactionQueue.pop();
3503 }
3504
3505 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3506 }
3507 return mTransactionQueues.empty();
3508}
3509
chaviwca27f252018-02-06 16:46:39 -08003510bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3511 for (const ComposerState& state : states) {
3512 // Here we need to check that the interface we're given is indeed
3513 // one of our own. A malicious client could give us a nullptr
3514 // IInterface, or one of its own or even one of our own but a
3515 // different type. All these situations would cause us to crash.
3516 if (state.client == nullptr) {
3517 return true;
3518 }
3519
3520 sp<IBinder> binder = IInterface::asBinder(state.client);
3521 if (binder == nullptr) {
3522 return true;
3523 }
3524
3525 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3526 return true;
3527 }
3528 }
3529 return false;
3530}
3531
Marissa Wall17b4e452018-12-26 16:32:34 -08003532bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3533 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003534 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003535 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3536 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3537 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3538 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3539 return false;
3540 }
3541
Marissa Wall713b63f2018-10-17 15:42:43 -07003542 for (const ComposerState& state : states) {
3543 const layer_state_t& s = state.state;
3544 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3545 continue;
3546 }
3547 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003548 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003549 }
3550 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003551 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003552}
3553
3554void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3555 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003556 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003557 const InputWindowCommands& inputWindowCommands,
3558 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003559 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003560
Valerie Haubc6ddb12019-03-08 11:10:15 -08003561 const int64_t postTime = systemTime();
3562
Robert Carr14167e02019-02-13 13:50:55 -08003563 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3564
Mathias Agopian698c0872011-06-28 19:09:31 -07003565 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003566
chaviwca27f252018-02-06 16:46:39 -08003567 if (containsAnyInvalidClientState(states)) {
3568 return;
3569 }
3570
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 // If its TransactionQueue already has a pending TransactionState or if it is pending
3572 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003574 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003575 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003576 setTransactionFlags(eTransactionNeeded);
3577 return;
3578 }
3579
Valerie Haubc6ddb12019-03-08 11:10:15 -08003580 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
3581 postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003582}
3583
3584void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003585 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003586 const InputWindowCommands& inputWindowCommands,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003587 const int64_t desiredPresentTime, const int64_t postTime,
Robert Carr14167e02019-02-13 13:50:55 -08003588 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003589 uint32_t transactionFlags = 0;
3590
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003591 if (flags & eAnimation) {
3592 // For window updates that are part of an animation we must wait for
3593 // previous animation "frames" to be handled.
3594 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003595 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003596 if (CC_UNLIKELY(err != NO_ERROR)) {
3597 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003598 // caller after a few seconds.
3599 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3600 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003601 mAnimTransactionPending = false;
3602 break;
3603 }
3604 }
3605 }
3606
chaviwca27f252018-02-06 16:46:39 -08003607 for (const DisplayState& display : displays) {
3608 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003609 }
3610
Marissa Walle2ffb422018-10-12 11:33:52 -07003611 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003612 for (const ComposerState& state : states) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003613 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged);
chaviwca27f252018-02-06 16:46:39 -08003614 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003615 // If the state doesn't require a traversal and there are callbacks, send them now
3616 if (!(clientStateFlags & eTraversalNeeded)) {
3617 mTransactionCompletedThread.sendCallbacks();
3618 }
3619 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003620
chaviw273171b2018-12-26 11:46:30 -08003621 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3622
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003623 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3624 // anyway. This can be used as a flush mechanism for previous async transactions.
3625 // Empty animation transaction can be used to simulate back-pressure, so also force a
3626 // transaction for empty animation transactions.
3627 if (transactionFlags == 0 &&
3628 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003629 transactionFlags = eTransactionNeeded;
3630 }
3631
Mathias Agopian386aa982011-11-07 21:58:03 -08003632 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003633 if (mInterceptor->isEnabled()) {
3634 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003635 }
Irvel468051e2016-06-13 16:44:44 -07003636
Mathias Agopian386aa982011-11-07 21:58:03 -08003637 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003638 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3639 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003640 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003641
3642 // if this is a synchronous transaction, wait for it to take effect
3643 // before returning.
3644 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003645 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003646 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003647 if (flags & eAnimation) {
3648 mAnimTransactionPending = true;
3649 }
chaviw95ef3c42019-02-14 10:55:09 -08003650
3651 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3652 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003653 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3654 if (CC_UNLIKELY(err != NO_ERROR)) {
3655 // just in case something goes wrong in SF, return to the
3656 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003657 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3658 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003659 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003660 break;
3661 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663 }
3664}
3665
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003666uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3667 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3668 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003669
Mathias Agopiane57f2922012-08-09 16:29:12 -07003670 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003671 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3672
3673 const uint32_t what = s.what;
3674 if (what & DisplayState::eSurfaceChanged) {
3675 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3676 state.surface = s.surface;
3677 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003678 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003680 if (what & DisplayState::eLayerStackChanged) {
3681 if (state.layerStack != s.layerStack) {
3682 state.layerStack = s.layerStack;
3683 flags |= eDisplayTransactionNeeded;
3684 }
3685 }
3686 if (what & DisplayState::eDisplayProjectionChanged) {
3687 if (state.orientation != s.orientation) {
3688 state.orientation = s.orientation;
3689 flags |= eDisplayTransactionNeeded;
3690 }
3691 if (state.frame != s.frame) {
3692 state.frame = s.frame;
3693 flags |= eDisplayTransactionNeeded;
3694 }
3695 if (state.viewport != s.viewport) {
3696 state.viewport = s.viewport;
3697 flags |= eDisplayTransactionNeeded;
3698 }
3699 }
3700 if (what & DisplayState::eDisplaySizeChanged) {
3701 if (state.width != s.width) {
3702 state.width = s.width;
3703 flags |= eDisplayTransactionNeeded;
3704 }
3705 if (state.height != s.height) {
3706 state.height = s.height;
3707 flags |= eDisplayTransactionNeeded;
3708 }
3709 }
3710
Mathias Agopiane57f2922012-08-09 16:29:12 -07003711 return flags;
3712}
3713
Robert Carr14167e02019-02-13 13:50:55 -08003714bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003715 IPCThreadState* ipc = IPCThreadState::self();
3716 const int pid = ipc->getCallingPid();
3717 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003718 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003719 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003720 return false;
3721 }
3722 return true;
3723}
3724
Robert Carr14167e02019-02-13 13:50:55 -08003725uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
Valerie Haubc6ddb12019-03-08 11:10:15 -08003726 int64_t desiredPresentTime, int64_t postTime,
3727 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003728 const layer_state_t& s = composerState.state;
3729 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3730
Mathias Agopian13127d82013-03-05 17:47:11 -08003731 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003732 if (layer == nullptr) {
3733 return 0;
3734 }
3735
chaviw8b3871a2017-11-01 17:41:01 -07003736 uint32_t flags = 0;
3737
Garfield Tan8a3083e2018-12-03 13:21:07 -08003738 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003739 bool geometryAppliesWithResize =
3740 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003741
3742 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3743 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003744 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003745 layer->pushPendingState();
3746 }
3747
chaviw8b3871a2017-11-01 17:41:01 -07003748 if (what & layer_state_t::ePositionChanged) {
3749 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3750 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003751 }
chaviw8b3871a2017-11-01 17:41:01 -07003752 }
3753 if (what & layer_state_t::eLayerChanged) {
3754 // NOTE: index needs to be calculated before we update the state
3755 const auto& p = layer->getParent();
3756 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003757 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003758 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 mCurrentState.layersSortedByZ.removeAt(idx);
3760 mCurrentState.layersSortedByZ.add(layer);
3761 // we need traversal (state changed)
3762 // AND transaction (list changed)
3763 flags |= eTransactionNeeded|eTraversalNeeded;
3764 }
chaviw8b3871a2017-11-01 17:41:01 -07003765 } else {
3766 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003767 flags |= eTransactionNeeded|eTraversalNeeded;
3768 }
3769 }
chaviw8b3871a2017-11-01 17:41:01 -07003770 }
3771 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003772 // NOTE: index needs to be calculated before we update the state
3773 const auto& p = layer->getParent();
3774 if (p == nullptr) {
3775 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3776 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3777 mCurrentState.layersSortedByZ.removeAt(idx);
3778 mCurrentState.layersSortedByZ.add(layer);
3779 // we need traversal (state changed)
3780 // AND transaction (list changed)
3781 flags |= eTransactionNeeded|eTraversalNeeded;
3782 }
3783 } else {
3784 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3785 flags |= eTransactionNeeded|eTraversalNeeded;
3786 }
chaviw8b3871a2017-11-01 17:41:01 -07003787 }
3788 }
3789 if (what & layer_state_t::eSizeChanged) {
3790 if (layer->setSize(s.w, s.h)) {
3791 flags |= eTraversalNeeded;
3792 }
3793 }
3794 if (what & layer_state_t::eAlphaChanged) {
3795 if (layer->setAlpha(s.alpha))
3796 flags |= eTraversalNeeded;
3797 }
3798 if (what & layer_state_t::eColorChanged) {
3799 if (layer->setColor(s.color))
3800 flags |= eTraversalNeeded;
3801 }
Peiyong Lind3788632018-09-18 16:01:31 -07003802 if (what & layer_state_t::eColorTransformChanged) {
3803 if (layer->setColorTransform(s.colorTransform)) {
3804 flags |= eTraversalNeeded;
3805 }
3806 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003807 if (what & layer_state_t::eBackgroundColorChanged) {
3808 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3809 flags |= eTraversalNeeded;
3810 }
3811 }
chaviw8b3871a2017-11-01 17:41:01 -07003812 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003813 // TODO: b/109894387
3814 //
3815 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3816 // rotation. To see the problem observe that if we have a square parent, and a child
3817 // of the same size, then we rotate the child 45 degrees around it's center, the child
3818 // must now be cropped to a non rectangular 8 sided region.
3819 //
3820 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3821 // private API, and the WindowManager only uses rotation in one case, which is on a top
3822 // level layer in which cropping is not an issue.
3823 //
3824 // However given that abuse of rotation matrices could lead to surfaces extending outside
3825 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3826 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3827 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003828 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003829 flags |= eTraversalNeeded;
3830 }
3831 if (what & layer_state_t::eTransparentRegionChanged) {
3832 if (layer->setTransparentRegionHint(s.transparentRegion))
3833 flags |= eTraversalNeeded;
3834 }
3835 if (what & layer_state_t::eFlagsChanged) {
3836 if (layer->setFlags(s.flags, s.mask))
3837 flags |= eTraversalNeeded;
3838 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003839 if (what & layer_state_t::eCropChanged_legacy) {
3840 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003841 flags |= eTraversalNeeded;
3842 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003843 if (what & layer_state_t::eCornerRadiusChanged) {
3844 if (layer->setCornerRadius(s.cornerRadius))
3845 flags |= eTraversalNeeded;
3846 }
chaviw8b3871a2017-11-01 17:41:01 -07003847 if (what & layer_state_t::eLayerStackChanged) {
3848 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3849 // We only allow setting layer stacks for top level layers,
3850 // everything else inherits layer stack from its parent.
3851 if (layer->hasParent()) {
3852 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3853 layer->getName().string());
3854 } else if (idx < 0) {
3855 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3856 "that also does not appear in the top level layer list. Something"
3857 " has gone wrong.", layer->getName().string());
3858 } else if (layer->setLayerStack(s.layerStack)) {
3859 mCurrentState.layersSortedByZ.removeAt(idx);
3860 mCurrentState.layersSortedByZ.add(layer);
3861 // we need traversal (state changed)
3862 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003863 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003864 }
3865 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003866 if (what & layer_state_t::eDeferTransaction_legacy) {
3867 if (s.barrierHandle_legacy != nullptr) {
3868 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3869 } else if (s.barrierGbp_legacy != nullptr) {
3870 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (authenticateSurfaceTextureLocked(gbp)) {
3872 const auto& otherLayer =
3873 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003874 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003875 } else {
3876 ALOGE("Attempt to defer transaction to to an"
3877 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003878 }
3879 }
chaviw8b3871a2017-11-01 17:41:01 -07003880 // We don't trigger a traversal here because if no other state is
3881 // changed, we don't want this to cause any more work
3882 }
3883 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003884 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003885 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003886 if (!hadParent) {
3887 mCurrentState.layersSortedByZ.remove(layer);
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003890 }
chaviw8b3871a2017-11-01 17:41:01 -07003891 }
3892 if (what & layer_state_t::eReparentChildren) {
3893 if (layer->reparentChildren(s.reparentHandle)) {
3894 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003895 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003896 }
chaviw8b3871a2017-11-01 17:41:01 -07003897 if (what & layer_state_t::eDetachChildren) {
3898 layer->detachChildren();
3899 }
3900 if (what & layer_state_t::eOverrideScalingModeChanged) {
3901 layer->setOverrideScalingMode(s.overrideScalingMode);
3902 // We don't trigger a traversal here because if no other state is
3903 // changed, we don't want this to cause any more work
3904 }
Marissa Wall61c58622018-07-18 10:12:20 -07003905 if (what & layer_state_t::eTransformChanged) {
3906 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3907 }
3908 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3909 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3910 flags |= eTraversalNeeded;
3911 }
3912 if (what & layer_state_t::eCropChanged) {
3913 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3914 }
Marissa Wall861616d2018-10-22 12:52:23 -07003915 if (what & layer_state_t::eFrameChanged) {
3916 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3917 }
Marissa Wall61c58622018-07-18 10:12:20 -07003918 if (what & layer_state_t::eAcquireFenceChanged) {
3919 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eDataspaceChanged) {
3922 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3923 }
3924 if (what & layer_state_t::eHdrMetadataChanged) {
3925 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3926 }
3927 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3928 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3929 }
3930 if (what & layer_state_t::eApiChanged) {
3931 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eSidebandStreamChanged) {
3934 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3935 }
Robert Carr720e5062018-07-30 17:45:14 -07003936 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003937 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003938 layer->setInputInfo(s.inputInfo);
3939 flags |= eTraversalNeeded;
3940 } else {
3941 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3942 }
Robert Carr720e5062018-07-30 17:45:14 -07003943 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003944 if (what & layer_state_t::eMetadataChanged) {
3945 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3946 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003947 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3948 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3949 flags |= eTraversalNeeded;
3950 }
3951 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003952 std::vector<sp<CallbackHandle>> callbackHandles;
3953 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3954 mTransactionCompletedThread.run();
3955 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3956 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3957 }
3958 }
Marissa Wall73411622019-01-25 10:45:41 -08003959
3960 if (what & layer_state_t::eBufferChanged) {
3961 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3962 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3963 s.buffer);
3964 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003965 if (what & layer_state_t::eCachedBufferChanged) {
3966 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003967 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3968 s.cachedBuffer.bufferId);
Valerie Haubc6ddb12019-03-08 11:10:15 -08003969 if (layer->setBuffer(buffer)) {
3970 flags |= eTraversalNeeded;
3971 layer->setPostTime(postTime);
3972 layer->setDesiredPresentTime(desiredPresentTime);
3973 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003974 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003975 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3976 // Do not put anything that updates layer state or modifies flags after
3977 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003978 return flags;
3979}
3980
chaviw273171b2018-12-26 11:46:30 -08003981uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3982 uint32_t flags = 0;
3983 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3984 flags |= eTraversalNeeded;
3985 }
3986
chaviwa911b102019-02-14 10:18:33 -08003987 if (inputWindowCommands.syncInputWindows) {
3988 flags |= eTraversalNeeded;
3989 }
3990
Vishnu Nairec0ab382019-02-13 15:32:56 -08003991 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003992 return flags;
3993}
3994
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003995status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3996 uint32_t h, PixelFormat format, uint32_t flags,
3997 LayerMetadata metadata, sp<IBinder>* handle,
3998 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003999 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004000 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004001 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004002 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004003 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004004
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004005 status_t result = NO_ERROR;
4006
4007 sp<Layer> layer;
4008
Cody Northropbc755282017-03-31 12:00:08 -06004009 String8 uniqueName = getUniqueLayerName(name);
4010
Evan Roskya1f1e152019-01-24 16:17:46 -08004011 bool primaryDisplayOnly = false;
4012
4013 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4014 // TODO b/64227542
4015 if (metadata.has(METADATA_WINDOW_TYPE)) {
4016 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4017 if (windowType == 441731) {
4018 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4019 primaryDisplayOnly = true;
4020 }
4021 }
4022
Mathias Agopian3165cc22012-08-08 19:42:09 -07004023 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004024 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004025 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4026 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004027
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004029 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004030 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4031 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004032 break;
chaviw13fdc492017-06-27 12:40:18 -07004033 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004034 // check if buffer size is set for color layer.
4035 if (w > 0 || h > 0) {
4036 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4037 int(w), int(h));
4038 return BAD_VALUE;
4039 }
4040
Evan Roskya1f1e152019-01-24 16:17:46 -08004041 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4042 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004043 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004044 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004045 // check if buffer size is set for container layer.
4046 if (w > 0 || h > 0) {
4047 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4048 int(w), int(h));
4049 return BAD_VALUE;
4050 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004051 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4052 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004053 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004054 default:
4055 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004056 break;
4057 }
4058
Dan Stoza7d89d062015-04-30 13:29:25 -07004059 if (result != NO_ERROR) {
4060 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004062
Evan Roskya1f1e152019-01-24 16:17:46 -08004063 if (primaryDisplayOnly) {
4064 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004065 }
4066
Robert Carrb89ea9d2018-12-10 13:01:14 -08004067 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4068 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4069 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004070 if (result != NO_ERROR) {
4071 return result;
4072 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004073 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004074
4075 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077}
4078
Cody Northropbc755282017-03-31 12:00:08 -06004079String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4080{
4081 bool matchFound = true;
4082 uint32_t dupeCounter = 0;
4083
4084 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4085 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4086
Dan Stoza436ccf32018-06-21 12:10:12 -07004087 // Grab the state lock since we're accessing mCurrentState
4088 Mutex::Autolock lock(mStateLock);
4089
Cody Northropbc755282017-03-31 12:00:08 -06004090 // Loop over layers until we're sure there is no matching name
4091 while (matchFound) {
4092 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004093 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004094 if (layer->getName() == uniqueName) {
4095 matchFound = true;
4096 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4097 }
4098 });
4099 }
4100
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004101 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4102 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004103
4104 return uniqueName;
4105}
4106
Marissa Wallfd668622018-05-10 10:21:13 -07004107status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4108 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004109 LayerMetadata metadata, PixelFormat& format,
4110 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004111 sp<IGraphicBufferProducer>* gbp,
4112 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004114 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004115 case PIXEL_FORMAT_TRANSPARENT:
4116 case PIXEL_FORMAT_TRANSLUCENT:
4117 format = PIXEL_FORMAT_RGBA_8888;
4118 break;
4119 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004120 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 break;
4122 }
4123
Evan Roskya1f1e152019-01-24 16:17:46 -08004124 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4125 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004126 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004127 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004128 *handle = layer->getHandle();
4129 *gbp = layer->getProducer();
4130 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004132
Marissa Wallfd668622018-05-10 10:21:13 -07004133 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135}
4136
Marissa Wall61c58622018-07-18 10:12:20 -07004137status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004139 LayerMetadata metadata, sp<IBinder>* handle,
4140 sp<Layer>* outLayer) {
4141 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4142 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004143 *handle = layer->getHandle();
4144 *outLayer = layer;
4145
4146 return NO_ERROR;
4147}
4148
Evan Roskya1f1e152019-01-24 16:17:46 -08004149status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4150 uint32_t h, uint32_t flags, LayerMetadata metadata,
4151 sp<IBinder>* handle, sp<Layer>* outLayer) {
4152 *outLayer = getFactory().createColorLayer(
4153 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004155 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004156}
4157
Evan Roskya1f1e152019-01-24 16:17:46 -08004158status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4159 uint32_t w, uint32_t h, uint32_t flags,
4160 LayerMetadata metadata, sp<IBinder>* handle,
4161 sp<Layer>* outLayer) {
4162 *outLayer = getFactory().createContainerLayer(
4163 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004164 *handle = (*outLayer)->getHandle();
4165 return NO_ERROR;
4166}
4167
4168
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004169void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004170 mLayersPendingRemoval.add(layer);
4171 mLayersRemoved = true;
4172 setTransactionFlags(eTransactionNeeded);
4173}
4174
Robert Carr695d5282018-12-18 15:27:58 -08004175void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004176{
Robert Carr2e102c92018-10-23 12:11:15 -07004177 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004178 // If a layer has a parent, we allow it to out-live it's handle
4179 // with the idea that the parent holds a reference and will eventually
4180 // be cleaned up. However no one cleans up the top-level so we do so
4181 // here.
4182 if (layer->getParent() == nullptr) {
4183 mCurrentState.layersSortedByZ.remove(layer);
4184 }
4185 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004186 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004187}
4188
Mathias Agopianb60314a2012-04-10 22:09:54 -07004189// ---------------------------------------------------------------------------
4190
Andy McFadden13a082e2012-08-24 10:16:42 -07004191void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004192 const auto display = getDefaultDisplayDeviceLocked();
4193 if (!display) return;
4194
4195 const sp<IBinder> token = display->getDisplayToken().promote();
4196 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004197
Jesse Hall01e29052013-02-19 16:13:35 -08004198 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004199 Vector<ComposerState> state;
4200 Vector<DisplayState> displays;
4201 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004202 d.what = DisplayState::eDisplayProjectionChanged |
4203 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004204 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004205 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004206 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004207 d.frame.makeInvalid();
4208 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004209 d.width = 0;
4210 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004211 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004212 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004213
Dominik Laskowskie9774092018-12-11 10:04:24 -08004214 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004215
Dominik Laskowski83b88212018-12-11 13:34:06 -08004216 const nsecs_t vsyncPeriod = getVsyncPeriod();
4217 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004218
Brian Andersond0010582017-03-07 13:20:31 -08004219 // Use phase of 0 since phase is not known.
4220 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004221 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004222 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004223}
4224
4225void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004226 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004227 postMessageAsync(
4228 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004229}
4230
Dominik Laskowskie9774092018-12-11 10:04:24 -08004231void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004232 if (display->isVirtual()) {
4233 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004234 return;
4235 }
4236
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237 const auto displayId = display->getId();
4238 LOG_ALWAYS_FATAL_IF(!displayId);
4239
Dominik Laskowski34157762018-10-31 13:07:19 -07004240 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241
4242 int currentMode = display->getPowerMode();
4243 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004244 return;
4245 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004246
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004247 display->setPowerMode(mode);
4248
Lloyd Pique4dccc412018-01-22 17:21:36 -08004249 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004250 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004251 }
4252
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004253 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004254 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004255 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004256 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004257 mScheduler->onScreenAcquired(mAppConnectionHandle);
4258 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004262 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004263 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004264
4265 struct sched_param param = {0};
4266 param.sched_priority = 1;
4267 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4268 ALOGW("Couldn't set SCHED_FIFO on display on");
4269 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004270 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004271 // Turn off the display
4272 struct sched_param param = {0};
4273 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4274 ALOGW("Couldn't set SCHED_OTHER on display off");
4275 }
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004278 mScheduler->disableHardwareVsync(true);
4279 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004280 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004281
Dominik Laskowski075d3172018-05-24 15:50:06 -07004282 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004283 mVisibleRegionsDirty = true;
4284 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004285 } else if (mode == HWC_POWER_MODE_DOZE ||
4286 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004287 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004290 mScheduler->onScreenAcquired(mAppConnectionHandle);
4291 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004292 }
4293 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4294 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004295 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004296 mScheduler->disableHardwareVsync(true);
4297 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004298 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004299 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004300 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004301 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004303 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004304
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004305 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004306 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004307 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004308 // Update refresh rate stats.
4309 mRefreshRateStats->setPowerMode(mode);
4310 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004311 }
4312
Dominik Laskowski34157762018-10-31 13:07:19 -07004313 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314}
4315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004317 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 const auto display = getDisplayDevice(displayToken);
4319 if (!display) {
4320 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4321 displayToken.get());
4322 } else if (display->isVirtual()) {
4323 ALOGW("Attempt to set power mode %d for virtual display", mode);
4324 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004325 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004326 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004328}
4329
4330// ---------------------------------------------------------------------------
4331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4333 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004334 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004335
Mathias Agopianbd115332013-04-18 16:41:04 -07004336 IPCThreadState* ipc = IPCThreadState::self();
4337 const int pid = ipc->getCallingPid();
4338 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004339
Mathias Agopianbd115332013-04-18 16:41:04 -07004340 if ((uid != AID_SHELL) &&
4341 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004342 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4343 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004344 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004345 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004346 // (this would indicate SF is stuck, but we want to be able to
4347 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004348 status_t err = mStateLock.timedLock(s2ns(1));
4349 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004350 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351 StringAppendF(&result,
4352 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4353 "(no locks held)\n",
4354 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004355 }
4356
Dominik Laskowskic2867142019-01-21 11:33:38 -08004357 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004358
Dominik Laskowskic2867142019-01-21 11:33:38 -08004359 static const std::unordered_map<std::string, Dumper> dumpers = {
4360 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4361 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4362 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004363 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004364 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004365 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004366 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4367 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004368 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4369 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4370 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4371 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4372 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4373 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004374 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4376 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377
Dominik Laskowskic2867142019-01-21 11:33:38 -08004378 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4381 (it->second)(args, asProto, result);
4382 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004383 if (asProto) {
4384 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4385 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4386 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004387 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004388 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004389 }
4390
Mathias Agopian9795c422009-08-26 16:36:26 -07004391 if (locked) {
4392 mStateLock.unlock();
4393 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004395 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004396 return NO_ERROR;
4397}
4398
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004399status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4400 if (asProto && mTracing.isEnabled()) {
4401 mTracing.writeToFileAsync();
4402 }
4403
4404 return doDump(fd, DumpArgs(), asProto);
4405}
4406
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408 mCurrentState.traverseInZOrder(
4409 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004410}
4411
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004413 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004414
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415 if (args.size() > 1) {
4416 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004417 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004418 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004419 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004420 }
Robert Carr2047fae2016-11-28 14:09:09 -08004421 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004422 } else {
4423 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424 }
4425}
4426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004428 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004430 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004431 }
Robert Carr2047fae2016-11-28 14:09:09 -08004432 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004433
Svetoslavd85084b2014-03-20 10:28:31 -07004434 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004435}
4436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4438 mTimeStats->parseArgs(asProto, args, result);
4439}
4440
Jamie Gennis6547ff42013-07-16 20:12:42 -07004441// This should only be called from the main thread. Otherwise it would need
4442// the lock and should use mCurrentState rather than mDrawingState.
4443void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004444 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004445 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004446 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004447
4448 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4449}
4450
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004452 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004453
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004454 if (isLayerTripleBufferingDisabled())
4455 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004456
Yiwei Zhang5434a782018-12-05 18:06:32 -08004457 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4458 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4459 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4460 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4461 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4462 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004463 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004464}
4465
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004466void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004467 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004468 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004469 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004470 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004471
Ady Abraham97d04232019-03-05 19:48:12 -08004472 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004473 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4474 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004475 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004476}
4477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4479 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004480 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4481 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004482 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004483 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004485 }
David Sodman4a36e932017-11-07 14:29:47 -08004486 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004487 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004488 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4490 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004491}
4492
Dan Stozae77c7662016-05-13 11:37:28 -07004493void SurfaceFlinger::recordBufferingStats(const char* layerName,
4494 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004495 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4496 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004497 for (const auto& segment : history) {
4498 if (!segment.usedThirdBuffer) {
4499 stats.twoBufferTime += segment.totalTime;
4500 }
4501 if (segment.occupancyAverage < 1.0f) {
4502 stats.doubleBufferedTime += segment.totalTime;
4503 } else if (segment.occupancyAverage < 2.0f) {
4504 stats.tripleBufferedTime += segment.totalTime;
4505 }
4506 ++stats.numSegments;
4507 stats.totalTime += segment.totalTime;
4508 }
4509}
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4512 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004513
4514 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4515 const size_t count = currentLayers.size();
4516 for (size_t i=0 ; i<count ; i++) {
4517 currentLayers[i]->dumpFrameEvents(result);
4518 }
4519}
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004522 result.append("Buffering stats:\n");
4523 result.append(" [Layer name] <Active time> <Two buffer> "
4524 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004525 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004526 typedef std::tuple<std::string, float, float, float> BufferTuple;
4527 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004528 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004529 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004530 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004531 if (stats.numSegments == 0) {
4532 continue;
4533 }
4534 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4535 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4536 stats.totalTime;
4537 float doubleBufferRatio = static_cast<float>(
4538 stats.doubleBufferedTime) / stats.totalTime;
4539 float tripleBufferRatio = static_cast<float>(
4540 stats.tripleBufferedTime) / stats.totalTime;
4541 sorted.insert({activeTime, {name, twoBufferRatio,
4542 doubleBufferRatio, tripleBufferRatio}});
4543 }
4544 for (const auto& sortedPair : sorted) {
4545 float activeTime = sortedPair.first;
4546 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4548 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004549 }
4550 result.append("\n");
4551}
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004554 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004555 const auto displayId = display->getId();
4556 if (!displayId) {
4557 continue;
4558 }
4559 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004560 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 continue;
4562 }
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result,
4565 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4566 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004567 uint8_t port;
4568 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004569 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004570 result.append("no identification data\n");
4571 continue;
4572 }
4573
4574 if (!isEdid(data)) {
4575 result.append("unknown identification data: ");
4576 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578 }
4579 result.append("\n");
4580 continue;
4581 }
4582
4583 const auto edid = parseEdid(data);
4584 if (!edid) {
4585 result.append("invalid EDID: ");
4586 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004588 }
4589 result.append("\n");
4590 continue;
4591 }
4592
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004594 result.append(edid->displayName.data(), edid->displayName.length());
4595 result.append("\"\n");
4596 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004597}
4598
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4600 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4601 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4602 StringAppendF(&result, "DisplayColorSetting: %s\n",
4603 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604
4605 // TODO: print out if wide-color mode is active or not
4606
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004607 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004608 const auto displayId = display->getId();
4609 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004610 continue;
4611 }
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004614 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004615 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004617 }
4618
Lloyd Pique32cbe282018-10-19 13:09:22 -07004619 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, " Current color mode: %s (%d)\n",
4621 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004622 }
4623 result.append("\n");
4624}
4625
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004626LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004627 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004628 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4629 const State& state = useDrawing ? mDrawingState : mCurrentState;
4630 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004631 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004632 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004633 });
4634
4635 return layersProto;
4636}
4637
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004638LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4639 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004640 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004641
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004642 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004643 resolution->set_w(displayDevice->getWidth());
4644 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004645
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004646 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004647 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004648
Lloyd Pique32cbe282018-10-19 13:09:22 -07004649 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4650 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4651 layersProto.set_global_transform(displayState.orientation);
4652
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004653 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004655 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004656 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004657 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004658 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004659 }
4660 });
4661
4662 return layersProto;
4663}
4664
Dominik Laskowskic2867142019-01-21 11:33:38 -08004665void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4666 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004667 Colorizer colorizer(colorize);
4668
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669 // figure out if we're stuck somewhere
4670 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4673
4674 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004675 * Dump library configuration.
4676 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677
4678 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004679 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004681 appendSfConfigString(result);
4682 appendUiConfigString(result);
4683 appendGuiConfigString(result);
4684 result.append("\n");
4685
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004686 result.append("\nDisplay identification data:\n");
4687 dumpDisplayIdentificationData(result);
4688
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004689 result.append("\nWide-Color information:\n");
4690 dumpWideColorInfo(result);
4691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004693 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004695 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004696 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004697
Andy McFadden41d67d72014-04-25 16:58:34 -07004698 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004699 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004700 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004701 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004702 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004703
Dan Stozab90cf072015-03-05 11:05:59 -08004704 dumpStaticScreenStats(result);
4705 result.append("\n");
4706
Alec Mouri40189b02019-03-05 15:07:54 -08004707 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4708 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4709 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004710
Dan Stozae77c7662016-05-13 11:37:28 -07004711 dumpBufferingStats(result);
4712
Andy McFadden4803b742012-09-24 19:07:20 -07004713 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714 * Dump the visible layer list
4715 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4718 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4719 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004721
Chia-I Wu2f884132018-09-13 15:17:58 -07004722 {
4723 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4724 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004726 result.append("\n");
4727 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728
Lloyd Pique207def92019-02-28 16:09:52 -08004729 {
4730 StringAppendF(&result, "Composition layers\n");
4731 mDrawingState.traverseInZOrder([&](Layer* layer) {
4732 auto compositionLayer = layer->getCompositionLayer();
4733 if (compositionLayer) compositionLayer->dump(result);
4734 });
4735 }
4736
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004738 * Dump Display state
4739 */
4740
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004741 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004742 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004743 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004744 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004745 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004746 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004747 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004748
4749 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750 * Dump SurfaceFlinger global state
4751 */
4752
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004754 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004755 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004757 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758
Dominik Laskowski075d3172018-05-24 15:50:06 -07004759 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004760 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4761 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4763 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004764 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 StringAppendF(&result,
4766 " transaction-flags : %08x\n"
4767 " gpu_to_cpu_unsupported : %d\n",
4768 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004769
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004770 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004771 displayId && getHwComposer().isConnected(*displayId)) {
4772 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773 StringAppendF(&result,
4774 " refresh-rate : %f fps\n"
4775 " x-dpi : %f\n"
4776 " y-dpi : %f\n",
4777 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4778 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004779 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
Yiwei Zhang5434a782018-12-05 18:06:32 -08004781 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782
Dan Stozae22aec72016-08-01 13:20:59 -07004783 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004784 * Tracing state
4785 */
4786 mTracing.dump(result);
4787 result.append("\n");
4788
4789 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004790 * HWC layer minidump
4791 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004792 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004793 const auto displayId = display->getId();
4794 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004795 continue;
4796 }
4797
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004799 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004800 const sp<DisplayDevice> displayDevice = display;
4801 mCurrentState.traverseInZOrder(
4802 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004803 result.append("\n");
4804 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805
4806 /*
4807 * Dump HWComposer state
4808 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004810 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004811 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004812 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004813 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004814 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004815
4816 /*
4817 * Dump gralloc state
4818 */
4819 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4820 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004821
4822 /*
4823 * Dump VrFlinger state if in use.
4824 */
4825 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4826 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004828 result.append("\n");
4829 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004830
4831 /**
4832 * Scheduler dump state.
4833 */
Ana Krulecc2870422019-01-29 19:00:58 -08004834 result.append("\nScheduler state:\n");
4835 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004836 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004837 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004838}
4839
Dominik Laskowski075d3172018-05-24 15:50:06 -07004840const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004841 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004843 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004845 }
4846 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004847
Dominik Laskowski34157762018-10-31 13:07:19 -07004848 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004849 static const Vector<sp<Layer>> empty;
4850 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004851}
4852
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853void SurfaceFlinger::updateColorMatrixLocked() {
4854 mat4 colorMatrix;
4855 if (mGlobalSaturationFactor != 1.0f) {
4856 // Rec.709 luma coefficients
4857 float3 luminance{0.213f, 0.715f, 0.072f};
4858 luminance *= 1.0f - mGlobalSaturationFactor;
4859 mat4 saturationMatrix = mat4(
4860 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4861 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4862 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4863 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4864 );
4865 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4866 } else {
4867 colorMatrix = mClientColorMatrix * mDaltonizer();
4868 }
4869
4870 if (mCurrentState.colorMatrix != colorMatrix) {
4871 mCurrentState.colorMatrix = colorMatrix;
4872 mCurrentState.colorMatrixChanged = true;
4873 setTransactionFlags(eTransactionNeeded);
4874 }
4875}
4876
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004877status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878#pragma clang diagnostic push
4879#pragma clang diagnostic error "-Wswitch-enum"
4880 switch (static_cast<ISurfaceComposerTag>(code)) {
4881 // These methods should at minimum make sure that the client requested
4882 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004883 case BOOT_FINISHED:
4884 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 case CREATE_DISPLAY:
4886 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004887 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 case GET_ANIMATION_FRAME_STATS:
4889 case GET_HDR_CAPABILITIES:
4890 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004891 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004892 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004894 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004895 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004896 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004897 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4898 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004899 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4900 IPCThreadState* ipc = IPCThreadState::self();
4901 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4902 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004903 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 }
Robert Carr1db73f62016-12-21 12:58:51 -08004905 return OK;
4906 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004908 IPCThreadState* ipc = IPCThreadState::self();
4909 const int pid = ipc->getCallingPid();
4910 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4912 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004913 return PERMISSION_DENIED;
4914 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 // Used by apps to hook Choreographer to SurfaceFlinger.
4918 case CREATE_DISPLAY_EVENT_CONNECTION:
4919 // The following calls are currently used by clients that do not
4920 // request necessary permissions. However, they do not expose any secret
4921 // information, so it is OK to pass them.
4922 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004923 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004925 case GET_PHYSICAL_DISPLAY_IDS:
4926 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004928 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case GET_DISPLAY_CONFIGS:
4930 case GET_DISPLAY_STATS:
4931 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4932 // Calling setTransactionState is safe, because you need to have been
4933 // granted a reference to Client* and Handle* to do anything with it.
4934 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004935 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004936 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004937 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004938 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004939 case IS_WIDE_COLOR_DISPLAY:
4940 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4941 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 return OK;
4943 }
4944 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004945 case CAPTURE_SCREEN:
4946 case ADD_REGION_SAMPLING_LISTENER:
4947 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004948 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004949 IPCThreadState* ipc = IPCThreadState::self();
4950 const int pid = ipc->getCallingPid();
4951 const int uid = ipc->getCallingUid();
4952 if ((uid != AID_GRAPHICS) &&
4953 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4954 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4955 return PERMISSION_DENIED;
4956 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957 return OK;
4958 }
4959 // The following codes are deprecated and should never be allowed to access SF.
4960 case CONNECT_DISPLAY_UNUSED:
4961 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4962 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4963 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966
4967 // These codes are used for the IBinder protocol to either interrogate the recipient
4968 // side of the transaction for its canonical interface descriptor or to dump its state.
4969 // We let them pass by default.
4970 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4971 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4972 code == IBinder::SYSPROPS_TRANSACTION) {
4973 return OK;
4974 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08004975 // Numbers from 1000 to 1032 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08004977 if (code >= 1000 && code <= 1032) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4979 return OK;
4980 }
4981 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4982 return PERMISSION_DENIED;
4983#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004984}
4985
Ana Krulec13be8ad2018-08-21 02:43:56 +00004986status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4987 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004988 status_t credentialCheck = CheckTransactCodeCredentials(code);
4989 if (credentialCheck != OK) {
4990 return credentialCheck;
4991 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004992
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4994 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004995 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004996 IPCThreadState* ipc = IPCThreadState::self();
4997 const int uid = ipc->getCallingUid();
4998 if (CC_UNLIKELY(uid != AID_SYSTEM
4999 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005000 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005001 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005002 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return PERMISSION_DENIED;
5004 }
5005 int n;
5006 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005007 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005008 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 return NO_ERROR;
5010 case 1002: // SHOW_UPDATES
5011 n = data.readInt32();
5012 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005013 invalidateHwcGeometry();
5014 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005017 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005018 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005020 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005021 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005022 setTransactionFlags(
5023 eTransactionNeeded|
5024 eDisplayTransactionNeeded|
5025 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005026 return NO_ERROR;
5027 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005028 case 1006:{ // send empty update
5029 signalRefresh();
5030 return NO_ERROR;
5031 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005032 case 1008: // toggle use of hw composer
5033 n = data.readInt32();
5034 mDebugDisableHWC = n ? 1 : 0;
5035 invalidateHwcGeometry();
5036 repaintEverything();
5037 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005038 case 1009: // toggle use of transform hint
5039 n = data.readInt32();
5040 mDebugDisableTransformHint = n ? 1 : 0;
5041 invalidateHwcGeometry();
5042 repaintEverything();
5043 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005045 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 reply->writeInt32(0);
5047 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005048 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005049 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 return NO_ERROR;
5051 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005052 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005053 if (!display) {
5054 return NAME_NOT_FOUND;
5055 }
5056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005058 return NO_ERROR;
5059 }
5060 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005061 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005062 // daltonize
5063 n = data.readInt32();
5064 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005065 case 1:
5066 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5067 break;
5068 case 2:
5069 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5070 break;
5071 case 3:
5072 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5073 break;
5074 default:
5075 mDaltonizer.setType(ColorBlindnessType::None);
5076 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005077 }
5078 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005079 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005080 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005081 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005082 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083
5084 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005086 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005087 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005089 // apply a color matrix
5090 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005091 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005092 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005093 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005101
5102 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5103 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005105 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5106 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5107 }
5108
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 return NO_ERROR;
5111 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005112 // This is an experimental interface
5113 // Needs to be shifted to proper binder interface when we productize
5114 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005115 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005116 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005117 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005118 return NO_ERROR;
5119 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005120 case 1017: {
5121 n = data.readInt32();
5122 mForceFullDamage = static_cast<bool>(n);
5123 return NO_ERROR;
5124 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005125 case 1018: { // Modify Choreographer's phase offset
5126 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005127 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005128 return NO_ERROR;
5129 }
5130 case 1019: { // Modify SurfaceFlinger's phase offset
5131 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005132 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005133 return NO_ERROR;
5134 }
Irvel468051e2016-06-13 16:44:44 -07005135 case 1020: { // Layer updates interceptor
5136 n = data.readInt32();
5137 if (n) {
5138 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005139 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005140 }
5141 else{
5142 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005143 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005144 }
5145 return NO_ERROR;
5146 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005147 case 1021: { // Disable HWC virtual displays
5148 n = data.readInt32();
5149 mUseHwcVirtualDisplays = !n;
5150 return NO_ERROR;
5151 }
Romain Guy0147a172017-06-01 13:53:56 -07005152 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005153 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005154 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005155
Chia-I Wu28f320b2018-05-03 11:02:56 -07005156 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005157 return NO_ERROR;
5158 }
Romain Guy54f154a2017-10-24 21:40:32 +01005159 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005160 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005161 invalidateHwcGeometry();
5162 repaintEverything();
5163 return NO_ERROR;
5164 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005165 // Deprecate, use 1030 to check whether the device is color managed.
5166 case 1024: {
5167 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005168 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005169 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005170 n = data.readInt32();
5171 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005172 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005173 Mutex::Autolock lock(mStateLock);
5174 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005175 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005176 reply->writeInt32(NO_ERROR);
5177 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005178 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005179 bool writeFile = false;
5180 {
5181 Mutex::Autolock lock(mStateLock);
5182 mTracingEnabledChanged = true;
5183 writeFile = mTracing.disable();
5184 }
5185
5186 if (writeFile) {
5187 reply->writeInt32(mTracing.writeToFile());
5188 } else {
5189 reply->writeInt32(NO_ERROR);
5190 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005191 }
5192 return NO_ERROR;
5193 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005194 case 1026: { // Get layer tracing status
5195 reply->writeBool(mTracing.isEnabled());
5196 return NO_ERROR;
5197 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005198 // Is a DisplayColorSetting supported?
5199 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005200 const auto display = getDefaultDisplayDevice();
5201 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005202 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005204
5205 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5206 switch (setting) {
5207 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005208 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005209 break;
5210 case DisplayColorSetting::UNMANAGED:
5211 reply->writeBool(true);
5212 break;
5213 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005214 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005215 break;
5216 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005217 reply->writeBool(
5218 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005219 break;
5220 }
5221 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005222 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005223 // Is VrFlinger active?
5224 case 1028: {
5225 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005226 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005227 return NO_ERROR;
5228 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005229 // Set buffer size for SF tracing (value in KB)
5230 case 1029: {
5231 n = data.readInt32();
5232 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5233 ALOGW("Invalid buffer size: %d KB", n);
5234 reply->writeInt32(BAD_VALUE);
5235 return BAD_VALUE;
5236 }
5237
5238 ALOGD("Updating trace buffer to %d KB", n);
5239 mTracing.setBufferSize(n * 1024);
5240 reply->writeInt32(NO_ERROR);
5241 return NO_ERROR;
5242 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005243 // Is device color managed?
5244 case 1030: {
5245 reply->writeBool(useColorManagement);
5246 return NO_ERROR;
5247 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005248 // Override default composition data space
5249 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5250 // && adb shell stop zygote && adb shell start zygote
5251 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5252 // adb shell stop zygote && adb shell start zygote
5253 case 1031: {
5254 Mutex::Autolock _l(mStateLock);
5255 n = data.readInt32();
5256 if (n) {
5257 n = data.readInt32();
5258 if (n) {
5259 Dataspace dataspace = static_cast<Dataspace>(n);
5260 if (!validateCompositionDataspace(dataspace)) {
5261 return BAD_VALUE;
5262 }
5263 mDefaultCompositionDataspace = dataspace;
5264 }
5265 n = data.readInt32();
5266 if (n) {
5267 Dataspace dataspace = static_cast<Dataspace>(n);
5268 if (!validateCompositionDataspace(dataspace)) {
5269 return BAD_VALUE;
5270 }
5271 mWideColorGamutCompositionDataspace = dataspace;
5272 }
5273 } else {
5274 // restore composition data space.
5275 mDefaultCompositionDataspace = defaultCompositionDataspace;
5276 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5277 }
5278 return NO_ERROR;
5279 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005280 case 1032: {
5281 n = data.readInt32();
5282 mDebugEnableProtectedContent = n;
5283 return NO_ERROR;
5284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005285 }
5286 }
5287 return err;
5288}
5289
Steven Thomas6d8110b2017-08-31 18:24:21 -07005290void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005291 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005292 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005293}
5294
Ana Krulec7d1d6832018-12-27 11:10:09 -08005295void SurfaceFlinger::repaintEverythingForHWC() {
5296 mRepaintEverything = true;
5297 mEventQueue->invalidateForHWC();
5298}
5299
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005300// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5301class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005302public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5304 ~WindowDisconnector() {
5305 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005306 }
5307
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308private:
5309 ANativeWindow* mWindow;
5310 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005311};
5312
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005313status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005314 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5315 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005316 uint32_t reqWidth, uint32_t reqHeight,
5317 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005318 ISurfaceComposer::Rotation rotation,
5319 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005320 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005321
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005322 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005323
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005324 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5325
Chia-I Wu20261cb2018-08-23 12:55:44 -07005326 sp<DisplayDevice> display;
5327 {
5328 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005329
Chia-I Wu20261cb2018-08-23 12:55:44 -07005330 display = getDisplayDeviceLocked(displayToken);
5331 if (!display) return BAD_VALUE;
5332
Chia-I Wucb023152018-08-28 12:57:23 -07005333 // set the requested width/height to the logical display viewport size
5334 // by default
5335 if (reqWidth == 0 || reqHeight == 0) {
5336 reqWidth = uint32_t(display->getViewport().width());
5337 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005338 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005339 }
5340
Peiyong Lin0e003c92018-09-17 11:09:51 -07005341 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005342 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005343
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005344 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5345 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005346 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5347 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005348}
5349
5350status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005351 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5352 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005353 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005354 ATRACE_CALL();
5355
5356 class LayerRenderArea : public RenderArea {
5357 public:
Robert Carr578038f2018-03-09 12:25:24 -08005358 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005359 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5360 bool childrenOnly)
5361 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005362 mLayer(layer),
5363 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005364 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005365 mFlinger(flinger),
5366 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005367 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005368 Rect getBounds() const override {
5369 const Layer::State& layerState(mLayer->getDrawingState());
5370 return mLayer->getBufferSize(layerState);
5371 }
Marissa Wall61c58622018-07-18 10:12:20 -07005372 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005373 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005374 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005375 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005376 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005377 }
chaviwa76b2712017-09-20 12:02:26 -07005378 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005379 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005380 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005381 Rect getSourceCrop() const override {
5382 if (mCrop.isEmpty()) {
5383 return getBounds();
5384 } else {
5385 return mCrop;
5386 }
5387 }
Robert Carr578038f2018-03-09 12:25:24 -08005388 class ReparentForDrawing {
5389 public:
5390 const sp<Layer>& oldParent;
5391 const sp<Layer>& newParent;
5392
Vishnu Nair4351ad52019-02-11 14:13:02 -08005393 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5394 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005395 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005396 // Compute and cache the bounds for the new parent layer.
5397 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005398 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005399 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005400 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005401 };
5402
5403 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005404 const Rect sourceCrop = getSourceCrop();
5405 // no need to check rotation because there is none
5406 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5407 sourceCrop.height() != getReqHeight();
5408
Robert Carr578038f2018-03-09 12:25:24 -08005409 if (!mChildrenOnly) {
5410 mTransform = mLayer->getTransform().inverse();
5411 drawLayers();
5412 } else {
5413 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005414 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005415 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005416 bounds.getWidth(), bounds.getHeight(), 0,
5417 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005418
Vishnu Nair4351ad52019-02-11 14:13:02 -08005419 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005420 drawLayers();
5421 }
5422 }
chaviwa76b2712017-09-20 12:02:26 -07005423
chaviwa76b2712017-09-20 12:02:26 -07005424 private:
chaviw7206d492017-11-10 16:16:12 -08005425 const sp<Layer> mLayer;
5426 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005427
5428 // In the "childrenOnly" case we reparent the children to a screenshot
5429 // layer which has no properties set and which does not draw.
5430 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005431 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005432 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005433
5434 SurfaceFlinger* mFlinger;
5435 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005436 };
5437
5438 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5439 auto parent = layerHandle->owner.promote();
5440
Robert Carr2e102c92018-10-23 12:11:15 -07005441 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005442 ALOGE("captureLayers called with a removed parent");
5443 return NAME_NOT_FOUND;
5444 }
5445
Robert Carr578038f2018-03-09 12:25:24 -08005446 const int uid = IPCThreadState::self()->getCallingUid();
5447 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005448 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005449 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5450 return PERMISSION_DENIED;
5451 }
5452
chaviw7206d492017-11-10 16:16:12 -08005453 Rect crop(sourceCrop);
5454 if (sourceCrop.width() <= 0) {
5455 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005456 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005457 }
5458
5459 if (sourceCrop.height() <= 0) {
5460 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005461 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005462 }
5463
5464 int32_t reqWidth = crop.width() * frameScale;
5465 int32_t reqHeight = crop.height() * frameScale;
5466
Chia-I Wu20261cb2018-08-23 12:55:44 -07005467 // really small crop or frameScale
5468 if (reqWidth <= 0) {
5469 reqWidth = 1;
5470 }
5471 if (reqHeight <= 0) {
5472 reqHeight = 1;
5473 }
5474
Peiyong Lin0e003c92018-09-17 11:09:51 -07005475 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005476
Robert Carr578038f2018-03-09 12:25:24 -08005477 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005478 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5479 if (!layer->isVisible()) {
5480 return;
Robert Carr578038f2018-03-09 12:25:24 -08005481 } else if (childrenOnly && layer == parent.get()) {
5482 return;
chaviwa76b2712017-09-20 12:02:26 -07005483 }
5484 visitor(layer);
5485 });
5486 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005487 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005488}
5489
5490status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5491 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005492 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005493 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005494 bool useIdentityTransform) {
5495 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005496
Peiyong Lin0e003c92018-09-17 11:09:51 -07005497 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005498 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5499 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005500 *outBuffer =
5501 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5502 static_cast<android_pixel_format>(reqPixelFormat), 1,
5503 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005505 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005506}
5507
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005508status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5509 TraverseLayersFunction traverseLayers,
5510 const sp<GraphicBuffer>& buffer,
5511 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005512 // This mutex protects syncFd and captureResult for communication of the return values from the
5513 // main thread back to this Binder thread
5514 std::mutex captureMutex;
5515 std::condition_variable captureCondition;
5516 std::unique_lock<std::mutex> captureLock(captureMutex);
5517 int syncFd = -1;
5518 std::optional<status_t> captureResult;
5519
Robert Carr03480e22018-01-04 16:02:06 -08005520 const int uid = IPCThreadState::self()->getCallingUid();
5521 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5522
Dominik Laskowski8c001672018-05-30 16:52:06 -07005523 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005524 // If there is a refresh pending, bug out early and tell the binder thread to try again
5525 // after the refresh.
5526 if (mRefreshPending) {
5527 ATRACE_NAME("Skipping screenshot for now");
5528 std::unique_lock<std::mutex> captureLock(captureMutex);
5529 captureResult = std::make_optional<status_t>(EAGAIN);
5530 captureCondition.notify_one();
5531 return;
5532 }
5533
5534 status_t result = NO_ERROR;
5535 int fd = -1;
5536 {
5537 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005538 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005539 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005540 useIdentityTransform, forSystem, &fd);
5541 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005542 }
5543
5544 {
5545 std::unique_lock<std::mutex> captureLock(captureMutex);
5546 syncFd = fd;
5547 captureResult = std::make_optional<status_t>(result);
5548 captureCondition.notify_one();
5549 }
5550 });
5551
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005552 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005553 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005554 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005555 while (*captureResult == EAGAIN) {
5556 captureResult.reset();
5557 result = postMessageAsync(message);
5558 if (result != NO_ERROR) {
5559 return result;
5560 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005561 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562 }
5563 result = *captureResult;
5564 }
5565
5566 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005567 sync_wait(syncFd, -1);
5568 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005569 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005570
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005571 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005572}
5573
chaviwa76b2712017-09-20 12:02:26 -07005574void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005575 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005576 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5577 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005578 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005579
chaviwa76b2712017-09-20 12:02:26 -07005580 const auto reqWidth = renderArea.getReqWidth();
5581 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005582 const auto sourceCrop = renderArea.getSourceCrop();
5583 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005584
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005585 renderengine::DisplaySettings clientCompositionDisplay;
5586 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005587
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005588 // assume that bounds are never offset, and that they are the same as the
5589 // buffer bounds.
5590 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5591 ui::Transform transform = renderArea.getTransform();
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005592 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005593 mat4 rotMatrix;
5594 // Displacement for repositioning the clipping rectangle after rotating it
5595 // with the rotation hint.
5596 int displacementX = 0;
5597 int displacementY = 0;
5598 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5599 switch (rotation) {
5600 case ui::Transform::ROT_90:
5601 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5602 displacementX = reqWidth;
5603 break;
5604 case ui::Transform::ROT_180:
5605 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5606 displacementX = reqWidth;
5607 displacementY = reqHeight;
5608 break;
5609 case ui::Transform::ROT_270:
5610 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5611 displacementY = reqHeight;
5612 break;
5613 default:
5614 break;
5615 }
5616 // We need to transform the clipping window into the right spot.
5617 // First, rotate the clipping rectangle by the rotation hint to get the
5618 // right orientation
5619 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5620 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5621 const vec4 rotClipTL = rotMatrix * clipTL;
5622 const vec4 rotClipBR = rotMatrix * clipBR;
5623 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5624 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5625 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5626 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5627
5628 // Now reposition the clipping rectangle with the displacement vector
5629 // computed above.
5630 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5631
5632 clientCompositionDisplay.clip =
5633 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5634 newClipRight + displacementX, newClipBottom + displacementY);
5635
5636 // We need to perform the same transformation in layer space, so propagate
5637 // it to the global transform.
5638 mat4 clipTransform = displacementMat * rotMatrix;
5639 clientCompositionDisplay.globalTransform *= clipTransform;
5640 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5641 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005642
chaviw50da5042018-04-09 13:49:37 -07005643 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005644
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005645 renderengine::LayerSettings fillLayer;
5646 fillLayer.source.buffer.buffer = nullptr;
5647 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5648 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5649 fillLayer.alpha = half(alpha);
5650 clientCompositionLayers.push_back(fillLayer);
5651
5652 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005653 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005654 renderengine::LayerSettings layerSettings;
5655 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005656 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 if (prepared) {
5658 clientCompositionLayers.push_back(layerSettings);
5659 }
chaviwa76b2712017-09-20 12:02:26 -07005660 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661
5662 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005663 // Use an empty fence for the buffer fence, since we just created the buffer so
5664 // there is no need for synchronization with the GPU.
5665 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005667 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005668 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005669 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005670
5671 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672}
5673
chaviwa76b2712017-09-20 12:02:26 -07005674status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5675 TraverseLayersFunction traverseLayers,
5676 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005677 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005678 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005679 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005680 ATRACE_CALL();
5681
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005682 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005683
5684 traverseLayers([&](Layer* layer) {
5685 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5686 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005687
Robert Carr03480e22018-01-04 16:02:06 -08005688 // We allow the system server to take screenshots of secure layers for
5689 // use in situations like the Screen-rotation animation and place
5690 // the impetus on WindowManager to not persist them.
5691 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005692 ALOGW("FB is protected: PERMISSION_DENIED");
5693 return PERMISSION_DENIED;
5694 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005696 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005697}
5698
chaviw95ef3c42019-02-14 10:55:09 -08005699void SurfaceFlinger::setInputWindowsFinished() {
5700 Mutex::Autolock _l(mStateLock);
5701
5702 mPendingSyncInputWindows = false;
5703 mTransactionCV.broadcast();
5704}
chaviw5f21a5e2019-02-14 10:00:34 -08005705
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005706// ---------------------------------------------------------------------------
5707
Dan Stoza412903f2017-04-27 13:42:17 -07005708void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5709 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005710}
5711
Dan Stoza412903f2017-04-27 13:42:17 -07005712void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5713 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005714}
5715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005716void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005717 const LayerVector::Visitor& visitor) {
5718 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005719 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005720 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005721 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005722 continue;
5723 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005724 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005725 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005726 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005727 return;
5728 }
chaviwa76b2712017-09-20 12:02:26 -07005729 if (!layer->isVisible()) {
5730 return;
5731 }
5732 visitor(layer);
5733 });
5734 }
5735}
5736
Ady Abraham838de062019-02-04 10:24:03 -08005737void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5738 const android::sp<android::IBinder>& displayToken,
5739 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5740 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5741 if (!displayId) {
5742 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5743 return;
5744 }
5745
5746 ALOGV("Updating allowed configs");
5747 {
5748 std::lock_guard lock(mAllowedConfigsLock);
5749 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5750 }
5751
5752 // make sure that the current config is still allowed
5753 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5754 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
Ady Abraham1902d072019-03-01 17:18:59 -08005755 for (const auto& [type, config] : mRefreshRateConfigs[*displayId]->getRefreshRates()) {
Alec Mouri0a1cc962019-03-14 12:33:02 -07005756 if (config && isConfigAllowed(*displayId, config->configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08005757 // TODO: we switch to the first allowed config. In the future
5758 // we may want to enhance this logic to pick a similar config
5759 // to the current one
Alec Mouri0a1cc962019-03-14 12:33:02 -07005760 ALOGV("Old config is not allowed - switching to config %d", config->configId);
5761 setDesiredActiveConfig(displayToken, config->configId,
Ana Krulec8d3e4f32019-03-05 10:40:33 -08005762 Scheduler::ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005763 break;
5764 }
5765 }
5766 }
Ady Abraham97d04232019-03-05 19:48:12 -08005767
5768 // If idle timer and fps detection are disabled and we are in RefreshRateType::DEFAULT,
5769 // there is no trigger to move to RefreshRateType::PERFORMANCE, even if it is an allowed.
5770 if (!mScheduler->isIdleTimerEnabled() && !mUseSmart90ForVideo) {
Alec Mouri0a1cc962019-03-14 12:33:02 -07005771 const auto& performanceRefreshRate =
Ady Abraham97d04232019-03-05 19:48:12 -08005772 mRefreshRateConfigs[*displayId]->getRefreshRate(RefreshRateType::PERFORMANCE);
Alec Mouri0a1cc962019-03-14 12:33:02 -07005773 if (performanceRefreshRate &&
5774 isConfigAllowed(*displayId, performanceRefreshRate->configId)) {
Ady Abraham97d04232019-03-05 19:48:12 -08005775 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
5776 }
5777 }
Ady Abraham838de062019-02-04 10:24:03 -08005778}
5779
5780status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5781 const std::vector<int32_t>& allowedConfigs) {
5782 ATRACE_CALL();
5783
5784 if (!displayToken) {
5785 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5786 return BAD_VALUE;
5787 }
5788
5789 if (!allowedConfigs.size()) {
5790 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5791 return BAD_VALUE;
5792 }
5793
5794 {
5795 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5796 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5797 if (!displayId) {
5798 ALOGE("setAllowedDisplayConfigs: display not found");
5799 return NAME_NOT_FOUND;
5800 }
5801 }
5802
5803 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5804 for (int config : allowedConfigs) {
5805 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5806 allowedDisplayConfigsBuilder.addConfig(config);
5807 }
5808 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5809 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5810 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5811 }));
5812 return NO_ERROR;
5813}
5814
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005815status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5816 std::vector<int32_t>* outAllowedConfigs) {
5817 ATRACE_CALL();
5818
5819 if (!displayToken) {
5820 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5821 return BAD_VALUE;
5822 }
5823
5824 if (!outAllowedConfigs) {
5825 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5826 return BAD_VALUE;
5827 }
5828
5829 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5830 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5831 if (!displayId) {
5832 ALOGE("getAllowedDisplayConfigs: display not found");
5833 return NAME_NOT_FOUND;
5834 }
5835
5836 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5837 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5838 if (allowedConfigIterator != mAllowedConfigs.end()) {
5839 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5840 }
5841
5842 return NO_ERROR;
5843}
5844
chaviw291d88a2019-02-14 10:33:58 -08005845// ----------------------------------------------------------------------------
5846
5847void SetInputWindowsListener::onSetInputWindowsFinished() {
5848 mFlinger->setInputWindowsFinished();
5849}
5850
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005851}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005852
Lloyd Pique074e8122018-07-26 12:57:23 -07005853
Mathias Agopian3f844832013-08-07 21:24:32 -07005854#if defined(__gl_h_)
5855#error "don't include gl/gl.h in this file"
5856#endif
5857
5858#if defined(__gl2_h_)
5859#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005860#endif