blob: 0a4688a7458bcfd9e27943aa6e7385e8b179c8cf [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070090#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
David Sodman7e4ae112018-02-09 15:02:28 -080094#include "android-base/stringprintf.h"
95
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070098#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080099#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900100#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101
chaviw1d044282017-09-27 12:19:28 -0700102#include <layerproto/LayerProtoParser.h>
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104#define DISPLAY_COUNT 1
105
Mathias Agopianfee2b462013-07-03 12:34:01 -0700106/*
107 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
108 * black pixels.
109 */
110#define DEBUG_SCREENSHOTS false
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700116using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700117using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700118using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700119using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
Steven Thomasb02664d2017-07-26 18:48:28 -0700121namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700122
123#pragma clang diagnostic push
124#pragma clang diagnostic error "-Wswitch-enum"
125
126bool isWideColorMode(const ColorMode colorMode) {
127 switch (colorMode) {
128 case ColorMode::DISPLAY_P3:
129 case ColorMode::ADOBE_RGB:
130 case ColorMode::DCI_P3:
131 case ColorMode::BT2020:
132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177} // namespace anonymous
178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179// ---------------------------------------------------------------------------
180
Mathias Agopian99b49842011-06-27 16:05:52 -0700181const String16 sHardwareTest("android.permission.HARDWARE_TEST");
182const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
183const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
184const String16 sDump("android.permission.DUMP");
185
186// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800187int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
188int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700189int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700190bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800191uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800192bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800193bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800194int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800195// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600196bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700197int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700198bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700199bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700200Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
201ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700202
Kalle Raitaa099a242017-01-11 11:17:29 -0800203std::string getHwcServiceName() {
204 char value[PROPERTY_VALUE_MAX] = {};
205 property_get("debug.sf.hwc_service_name", value, "default");
206 ALOGI("Using HWComposer service: '%s'", value);
207 return std::string(value);
208}
209
210bool useTrebleTestingOverride() {
211 char value[PROPERTY_VALUE_MAX] = {};
212 property_get("debug.sf.treble_testing_override", value, "false");
213 ALOGI("Treble testing override: '%s'", value);
214 return std::string(value) == "true";
215}
216
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
218 switch(displayColorSetting) {
219 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800221 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700222 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700224 return std::string("Enhanced");
225 default:
226 return std::string("Unknown ") +
227 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229}
230
Lloyd Pique99d3da52018-01-22 17:48:03 -0800231NativeWindowSurface::~NativeWindowSurface() = default;
232
233namespace impl {
234
235class NativeWindowSurface final : public android::NativeWindowSurface {
236public:
237 static std::unique_ptr<android::NativeWindowSurface> create(
238 const sp<IGraphicBufferProducer>& producer) {
239 return std::make_unique<NativeWindowSurface>(producer);
240 }
241
242 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
243 : surface(new Surface(producer, false)) {}
244
245 ~NativeWindowSurface() override = default;
246
247private:
248 sp<ANativeWindow> getNativeWindow() const override { return surface; }
249
250 void preallocateBuffers() override { surface->allocateBuffers(); }
251
252 sp<Surface> surface;
253};
254
255} // namespace impl
256
David Sodmanbc815282017-11-05 18:57:52 -0800257SurfaceFlingerBE::SurfaceFlingerBE()
258 : mHwcServiceName(getHwcServiceName()),
259 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800260 mFrameBuckets(),
261 mTotalTime(0),
262 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800263 mComposerSequenceId(0) {
264}
265
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800266SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800267 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700269 mTransactionPending(false),
270 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700271 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700272 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700273 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700275 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800277 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800278 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800279 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700281 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700282 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700283 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700284 mDebugInTransaction(0),
285 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700286 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700287 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700288 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800289 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800290 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800291 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700292 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800293 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800294 mCreateBufferQueue(&BufferQueue::createBufferQueue),
295 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800296
297SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800299
300 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
302
303 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
305
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
307 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
310 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
311
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700312 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
313 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
314
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
316 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
317
Steven Thomas050b2c82017-03-06 11:45:16 -0800318 // Vr flinger is only enabled on Daydream ready devices.
319 useVrFlinger = getBool< ISurfaceFlingerConfigs,
320 &ISurfaceFlingerConfigs::useVrFlinger>(false);
321
Fabien Sanglard1971b632017-03-10 14:50:03 -0800322 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
323 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
324
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325 hasWideColorDisplay =
326 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700327 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getBool<V1_2::ISurfaceFlingerConfigs,
329 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
330
331 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
332 if (surfaceFlingerConfigsServiceV1_2) {
333 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
334 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
335 compositionDataSpace = tmpDataSpace;
336 compositionPixelFormat = tmpPixelFormat;
337 });
338 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600339
Peiyong Linb3839ad2018-09-05 15:37:19 -0700340 useContextPriority = getBool<ISurfaceFlingerConfigs,
341 &ISurfaceFlingerConfigs::useContextPriority>(true);
342
Iris Chang7501ed62018-04-30 14:45:42 +0800343 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700344 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
345 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800346 V1_1::DisplayOrientation::ORIENTATION_0);
347
348 switch (primaryDisplayOrientation) {
349 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700350 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800351 break;
352 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700353 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800354 break;
355 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700356 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800357 break;
358 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700359 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800360 break;
361 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700362 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800363
Lloyd Pique41be5d22018-06-21 13:11:48 -0700364 // Note: We create a local temporary with the real DispSync implementation
365 // type temporarily so we can initialize it with the configured values,
366 // before storing it for more generic use using the interface type.
367 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
368 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
369 SurfaceFlinger::dispSyncPresentTimeOffset);
370 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 // debugging stuff...
373 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianb4b17302013-03-20 18:36:41 -0700375 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700376 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378 property_get("debug.sf.showupdates", value, "0");
379 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700381 property_get("debug.sf.ddms", value, "0");
382 mDebugDDMS = atoi(value);
383 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700384 if (!startDdmConnection()) {
385 // start failed, and DDMS debugging not enabled
386 mDebugDDMS = 0;
387 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700388 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700389 ALOGI_IF(mDebugRegion, "showupdates enabled");
390 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700391
392 property_get("debug.sf.disable_backpressure", value, "0");
393 mPropagateBackpressure = !atoi(value);
394 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700395
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800396 property_get("debug.sf.enable_hwc_vds", value, "0");
397 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800398 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800399
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800400 property_get("ro.sf.disable_triple_buffer", value, "1");
401 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800402 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700403
Yiwei Zhang243b3782018-05-15 17:40:04 -0700404 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700405 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
406 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
407
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200408 property_get("debug.sf.early_phase_offset_ns", value, "-1");
409 const int earlySfOffsetNs = atoi(value);
410
411 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
412 const int earlyGlSfOffsetNs = atoi(value);
413
414 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
415 const int earlyAppOffsetNs = atoi(value);
416
417 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
418 const int earlyGlAppOffsetNs = atoi(value);
419
Ana Krulec98b5b242018-08-10 15:03:23 -0700420 property_get("debug.sf.use_scheduler", value, "0");
421 mUseScheduler = atoi(value);
422
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200423 const VSyncModulator::Offsets earlyOffsets =
424 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
425 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
426 const VSyncModulator::Offsets earlyGlOffsets =
427 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
428 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
429 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
430 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700431
Romain Guy11d63f42017-07-20 12:47:14 -0700432 // We should be reading 'persist.sys.sf.color_saturation' here
433 // but since /data may be encrypted, we need to wait until after vold
434 // comes online to attempt to read the property. The property is
435 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800436
437 if (useTrebleTestingOverride()) {
438 // Without the override SurfaceFlinger cannot connect to HIDL
439 // services that are not listed in the manifests. Considered
440 // deriving the setting from the set service name, but it
441 // would be brittle if the name that's not 'default' is used
442 // for production purposes later on.
443 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445}
446
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800447void SurfaceFlinger::onFirstRef()
448{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800449 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800450}
451
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452SurfaceFlinger::~SurfaceFlinger()
453{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
Dan Stozac7014012014-02-14 15:03:43 -0800456void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457{
458 // the window manager died on us. prepare its eulogy.
459
Andy McFadden13a082e2012-08-24 10:16:42 -0700460 // restore initial conditions (default device unblank, etc)
461 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800462
463 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700464 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465}
466
Robert Carr1db73f62016-12-21 12:58:51 -0800467static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700468 status_t err = client->initCheck();
469 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800470 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800471 }
Robert Carr1db73f62016-12-21 12:58:51 -0800472 return nullptr;
473}
474
475sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
476 return initClient(new Client(this));
477}
478
479sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
480 const sp<IGraphicBufferProducer>& gbp) {
481 if (authenticateSurfaceTexture(gbp) == false) {
482 return nullptr;
483 }
484 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
485 if (layer == nullptr) {
486 return nullptr;
487 }
488
489 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490}
491
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700492sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
493 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494{
495 class DisplayToken : public BBinder {
496 sp<SurfaceFlinger> flinger;
497 virtual ~DisplayToken() {
498 // no more references, this display must be terminated
499 Mutex::Autolock _l(flinger->mStateLock);
500 flinger->mCurrentState.displays.removeItem(this);
501 flinger->setTransactionFlags(eDisplayTransactionNeeded);
502 }
503 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700504 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 : flinger(flinger) {
506 }
507 };
508
509 sp<BBinder> token = new DisplayToken(this);
510
511 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700512 DisplayDeviceState info;
513 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700514 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700515 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800517 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 return token;
519}
520
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700521void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700522 Mutex::Autolock _l(mStateLock);
523
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700525 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700526 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
529
530 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700531 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700532 ALOGE("destroyDisplay called for non-virtual display");
533 return;
534 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700535 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700536 mCurrentState.displays.removeItemsAt(idx);
537 setTransactionFlags(eDisplayTransactionNeeded);
538}
539
Mathias Agopiane57f2922012-08-09 16:29:12 -0700540sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700541 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700542 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800543 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700544 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700545 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700546}
547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548void SurfaceFlinger::bootFinished()
549{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550 if (mStartPropertySetThread->join() != NO_ERROR) {
551 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 const nsecs_t now = systemTime();
554 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000555 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
557 // wait patiently for the window manager death
558 const String16 name("window");
559 sp<IBinder> window(defaultServiceManager()->getService(name));
560 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
563
Steven Thomas050b2c82017-03-06 11:45:16 -0800564 if (mVrFlinger) {
565 mVrFlinger->OnBootFinished();
566 }
567
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700569 // formerly we would just kill the process, but we now ask it to exit so it
570 // can choose where to stop the animation.
571 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700572
573 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
574 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
575 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700576
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800577 postMessageAsync(new LambdaMessage([this] {
578 readPersistentProperties();
579 mBootStage = BootStage::FINISHED;
580 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581}
582
Dan Stoza436ccf32018-06-21 12:10:12 -0700583uint32_t SurfaceFlinger::getNewTexture() {
584 {
585 std::lock_guard lock(mTexturePoolMutex);
586 if (!mTexturePool.empty()) {
587 uint32_t name = mTexturePool.back();
588 mTexturePool.pop_back();
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
590 return name;
591 }
592
593 // The pool was too small, so increase it for the future
594 ++mTexturePoolSize;
595 }
596
597 // The pool was empty, so we need to get a new texture name directly using a
598 // blocking call to the main thread
599 uint32_t name = 0;
600 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
601 return name;
602}
603
Mathias Agopian3f844832013-08-07 21:24:32 -0700604void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700605 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Thierry Strudel2924d012017-08-14 15:19:37 -0700614 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 if (mUseScheduler) {
620 mScheduler = std::make_unique<Scheduler>();
621 mAppConnectionHandle =
622 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
623 SurfaceFlinger::vsyncPhaseOffsetNs,
624 [this] { resyncWithRateLimit(); },
625 impl::EventThread::InterceptVSyncsCallback());
626 mSfConnectionHandle =
627 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
628 SurfaceFlinger::sfVsyncPhaseOffsetNs,
629 [this] { resyncWithRateLimit(); },
630 [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800633
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
635 mVsyncModulator.setEventThreads(mScheduler->getEventThread(mSfConnectionHandle),
636 mScheduler->getEventThread(mAppConnectionHandle));
637 } else {
638 mEventThreadSource =
639 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
640 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
641 mEventThread =
642 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
643 [this] { resyncWithRateLimit(); },
644 impl::EventThread::InterceptVSyncsCallback(),
645 "appEventThread");
646 mSfEventThreadSource =
647 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
648 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
649
650 mSFEventThread =
651 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
652 [this] { resyncWithRateLimit(); },
653 [this](nsecs_t timestamp) {
654 mInterceptor->saveVSyncEvent(timestamp);
655 },
656 "sfEventThread");
657 mEventQueue->setEventThread(mSFEventThread.get());
658 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
659 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700662 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700663 renderEngineFeature |= (useColorManagement ?
664 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700665 renderEngineFeature |= (useContextPriority ?
666 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700667
668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
669 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700670 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
671 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800672 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800676 getBE().mHwc.reset(
677 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700678 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800679 // Process any initial hotplug and resulting display changes.
680 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 const auto display = getDefaultDisplayDeviceLocked();
682 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
683 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
684 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800685
Lloyd Piquefcd86612017-12-14 17:15:36 -0800686 // make the default display GLContext current so that we can create textures
687 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800689
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 // This callback is called from the vr flinger dispatch thread. We
693 // need to call signalTransaction(), which requires holding
694 // mStateLock when we're not on the main thread. Acquiring
695 // mStateLock from the vr flinger dispatch thread might trigger a
696 // deadlock in surface flinger (see b/66916578), so post a message
697 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700698 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700699 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
700 mVrFlingerRequestsDisplay = requestDisplay;
701 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700702 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
705 getHwComposer()
706 .getHwcDisplayId(display->getId())
707 .value_or(0),
708 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 if (!mVrFlinger) {
710 ALOGE("Failed to start vrflinger");
711 }
712 }
713
Lloyd Pique379adc12018-01-22 17:31:47 -0800714 mEventControlThread = std::make_unique<impl::EventControlThread>(
715 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700716
Mathias Agopian92a979a2012-08-02 18:32:23 -0700717 // initialize our drawing state
718 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700719
Andy McFadden13a082e2012-08-24 10:16:42 -0700720 // set initial conditions (e.g. unblank default device)
721 initializeDisplays();
722
David Sodmanbc815282017-11-05 18:57:52 -0800723 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700724
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725 // Inform native graphics APIs whether the present timestamp is supported:
726 if (getHwComposer().hasCapability(
727 HWC2::Capability::PresentFenceIsNotReliable)) {
728 mStartPropertySetThread = new StartPropertySetThread(false);
729 } else {
730 mStartPropertySetThread = new StartPropertySetThread(true);
731 }
732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Chia-I Wud49d6692018-06-27 07:17:41 +0800737 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
738 // is used to saturate legacy sRGB content. However, to make sure the same color under
739 // Display P3 will be saturated to the same color, we intentionally break the API spec
740 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
741 // such saturation matrix on Display P3 is understood fully, the API should always return
742 // identify matrix.
743 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
744 Dataspace::SRGB_LINEAR);
745
746 // we will apply this on Display P3.
747 if (mEnhancedSaturationMatrix != mat4()) {
748 ColorSpace srgb(ColorSpace::sRGB());
749 ColorSpace displayP3(ColorSpace::DisplayP3());
750 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
751 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
752 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
753 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800783 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800787 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Jesse Hall692c7232012-11-08 15:41:56 -0800831 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700832 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
833 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700834 type = i;
835 break;
836 }
837 }
838
839 if (type < 0) {
840 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 // TODO: Not sure if display density should handled by SF any longer
844 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700847 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700849 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851 return density;
852 }
853 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700856 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 return getDensityFromProperty("ro.sf.lcd_density"); }
858 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Steven Thomas6d8110b2017-08-31 18:24:21 -0700862 ConditionalLock _l(mStateLock,
863 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 DisplayInfo info = DisplayInfo();
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 float xdpi = hwConfig->getDpiX();
868 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870 info.w = hwConfig->getWidth();
871 info.h = hwConfig->getHeight();
872 // Default display viewport to display width and height
873 info.viewportW = info.w;
874 info.viewportH = info.h;
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 if (type == DisplayDevice::DISPLAY_PRIMARY) {
877 // The density of the device is provided by a build property
878 float density = Density::getBuildDensity() / 160.0f;
879 if (density == 0) {
880 // the build doesn't provide a density -- this is wrong!
881 // use xdpi instead
882 ALOGE("ro.sf.lcd_density must be defined as a build property");
883 density = xdpi / 160.0f;
884 }
885 if (Density::getEmuDensity()) {
886 // if "qemu.sf.lcd_density" is specified, it overrides everything
887 xdpi = ydpi = density = Density::getEmuDensity();
888 density /= 160.0f;
889 }
890 info.density = density;
891
892 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893 const auto display = getDefaultDisplayDeviceLocked();
894 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700895
896 // This is for screenrecord
897 const Rect viewport = display->getViewport();
898 if (viewport.isValid()) {
899 info.viewportW = uint32_t(viewport.getWidth());
900 info.viewportH = uint32_t(viewport.getHeight());
901 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 } else {
903 // TODO: where should this value come from?
904 static const int TV_DENSITY = 213;
905 info.density = TV_DENSITY / 160.0f;
906 info.orientation = 0;
907 }
908
Dan Stoza7f7da322014-05-02 15:26:25 -0700909 info.xdpi = xdpi;
910 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900912 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913
Andy McFadden91b2ca82014-06-13 14:04:23 -0700914 // This is how far in advance a buffer must be queued for
915 // presentation at a given time. If you want a buffer to appear
916 // on the screen at time N, you must submit the buffer before
917 // (N - presentationDeadline).
918 //
919 // Normally it's one full refresh period (to give SF a chance to
920 // latch the buffer), but this can be reduced by configuring a
921 // DispSync offset. Any additional delays introduced by the hardware
922 // composer or panel must be accounted for here.
923 //
924 // We add an additional 1ms to allow for processing time and
925 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800927 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 // All non-virtual displays are currently considered secure.
930 info.secure = true;
931
Iris Chang7501ed62018-04-30 14:45:42 +0800932 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700933 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800934 std::swap(info.w, info.h);
935 }
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700938 }
939
Dan Stoza7f7da322014-05-02 15:26:25 -0700940 return NO_ERROR;
941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
944 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return BAD_VALUE;
946 }
947
948 // FIXME for now we always return stats for the primary display
949 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700950 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
951 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 display->setActiveConfig(mode);
977 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700981 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982 Vector<DisplayInfo> configs;
983 getDisplayConfigs(displayToken, &configs);
984 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
985 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
986 configs.size());
987 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 const auto display = getDisplayDevice(displayToken);
990 if (!display) {
991 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
992 displayToken.get());
993 } else if (display->isVirtual()) {
994 ALOGW("Attempt to set active config %d for virtual display", mode);
995 } else {
996 setActiveConfigInternal(display, mode);
997 }
998 }));
999
Mathias Agopian888c8222012-08-04 21:10:38 -07001000 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001001}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1003 Vector<ColorMode>* outColorModes) {
1004 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return BAD_VALUE;
1006 }
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1010 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001011 type = i;
1012 break;
1013 }
1014 }
1015
1016 if (type < 0) {
1017 return type;
1018 }
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
1022 ConditionalLock _l(mStateLock,
1023 std::this_thread::get_id() != mMainThreadId);
1024 modes = getHwComposer().getColorModes(type);
1025 }
Michael Wright28f24d02016-07-12 13:30:53 -07001026 outColorModes->clear();
1027 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1028
1029 return NO_ERROR;
1030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1033 if (const auto display = getDisplayDevice(displayToken)) {
1034 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001035 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001036 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001037}
1038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1040 Dataspace dataSpace, RenderIntent renderIntent) {
1041 ColorMode currentMode = display->getActiveColorMode();
1042 Dataspace currentDataSpace = display->getCompositionDataSpace();
1043 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001044
Peiyong Lin38e9a562018-04-10 16:24:20 -07001045 if (mode == currentMode && dataSpace == currentDataSpace &&
1046 renderIntent == currentRenderIntent) {
1047 return;
1048 }
1049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001051 ALOGW("Trying to set config for virtual display");
1052 return;
1053 }
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 display->setActiveColorMode(mode);
1056 display->setCompositionDataSpace(dataSpace);
1057 display->setActiveRenderIntent(renderIntent);
1058 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001059
1060 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1062 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001063}
1064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 Vector<ColorMode> modes;
1068 getDisplayColorModes(displayToken, &modes);
1069 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1070 if (mode < ColorMode::NATIVE || !exists) {
1071 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1072 decodeColorMode(mode).c_str(), mode, displayToken.get());
1073 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075 const auto display = getDisplayDevice(displayToken);
1076 if (!display) {
1077 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1078 decodeColorMode(mode).c_str(), mode, displayToken.get());
1079 } else if (display->isVirtual()) {
1080 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1081 decodeColorMode(mode).c_str(), mode);
1082 } else {
1083 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1084 RenderIntent::COLORIMETRIC);
1085 }
1086 }));
1087
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return NO_ERROR;
1089}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001090
Svetoslavd85084b2014-03-20 10:28:31 -07001091status_t SurfaceFlinger::clearAnimationFrameStats() {
1092 Mutex::Autolock _l(mStateLock);
1093 mAnimFrameTracker.clearStats();
1094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.getStats(outStats);
1100 return NO_ERROR;
1101}
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1104 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 Mutex::Autolock _l(mStateLock);
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const auto display = getDisplayDeviceLocked(displayToken);
1108 if (!display) {
1109 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110 return BAD_VALUE;
1111 }
1112
Peiyong Linfb069302018-04-25 14:34:31 -07001113 // At this point the DisplayDeivce should already be set up,
1114 // meaning the luminance information is already queried from
1115 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001117 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1118 capabilities.getDesiredMaxLuminance(),
1119 capabilities.getDesiredMaxAverageLuminance(),
1120 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001121
1122 return NO_ERROR;
1123}
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 if (mInjectVSyncs == enable) {
1130 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132
Ana Krulec98b5b242018-08-10 15:03:23 -07001133 // TODO(akrulec): Part of the Injector should be refactored, so that it
1134 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 if (enable) {
1136 ALOGV("VSync Injections enabled");
1137 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001138 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001139 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001141 impl::EventThread::InterceptVSyncsCallback(),
1142 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001144 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 } else {
1146 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001147 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 }
1149
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001151 }));
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 return NO_ERROR;
1154}
1155
1156status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 Mutex::Autolock _l(mStateLock);
1158
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 if (!mInjectVSyncs) {
1160 ALOGE("VSync Injections not enabled");
1161 return BAD_VALUE;
1162 }
1163 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1164 ALOGV("Injecting VSync inside SurfaceFlinger");
1165 mVSyncInjector->onInjectSyncEvent(when);
1166 }
1167 return NO_ERROR;
1168}
1169
Lloyd Pique755e3192018-01-31 16:46:15 -08001170status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1171 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001172 // Try to acquire a lock for 1s, fail gracefully
1173 const status_t err = mStateLock.timedLock(s2ns(1));
1174 const bool locked = (err == NO_ERROR);
1175 if (!locked) {
1176 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1177 return TIMED_OUT;
1178 }
1179
1180 outLayers->clear();
1181 mCurrentState.traverseInZOrder([&](Layer* layer) {
1182 outLayers->push_back(layer->getLayerDebugInfo());
1183 });
1184
1185 mStateLock.unlock();
1186 return NO_ERROR;
1187}
1188
Peiyong Lin0256f722018-08-31 15:45:10 -07001189status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1190 ui::PixelFormat* outPixelFormat) const {
1191 *outDataSpace = compositionDataSpace;
1192 *outPixelFormat = compositionPixelFormat;
1193 return NO_ERROR;
1194}
1195
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001196// ----------------------------------------------------------------------------
1197
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1199 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001200 if (mUseScheduler) {
1201 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1202 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1203 } else {
1204 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1205 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001206 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001207 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1208 return mSFEventThread->createEventConnection();
1209 } else {
1210 return mEventThread->createEventConnection();
1211 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001212 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001213}
1214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216
1217void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001222 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001223}
1224
1225void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001230 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001235 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001240 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242 if (res == NO_ERROR) {
1243 msg->wait();
1244 }
1245 return res;
1246}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001248void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001249 do {
1250 waitForEvent();
1251 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252}
1253
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254void SurfaceFlinger::enableHardwareVsync() {
1255 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001257 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 Mutex::Autolock _l(mHWVsyncLock);
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (makeAvailable) {
1267 mHWVsyncAvailable = true;
1268 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001269 // Hardware vsync is not currently available, so abort the resync
1270 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001271 return;
1272 }
1273
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001274 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1275 if (!getHwComposer().isConnected(displayId)) {
1276 return;
1277 }
1278
1279 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001280 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281
Lloyd Pique41be5d22018-06-21 13:11:48 -07001282 mPrimaryDispSync->reset();
1283 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284
1285 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001286 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryHWVsyncEnabled = true;
1289 }
1290}
1291
Jesse Hall948fe0c2013-10-14 12:56:09 -07001292void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 Mutex::Autolock _l(mHWVsyncLock);
1294 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001296 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1317 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001318 ATRACE_NAME("SF onVsync");
1319
Steven Thomas3cfac282017-02-06 12:29:30 -08001320 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001322 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001323 return;
1324 }
1325
1326 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001327 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001328 return;
1329 }
1330
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001331 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1332 // For now, we don't do anything with external display vsyncs.
1333 return;
1334 }
1335
Jamie Gennisd1700752013-10-14 12:22:52 -07001336 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 { // Scope for the lock
1339 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001340 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001341 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001344
1345 if (needsHwVsync) {
1346 enableHardwareVsync();
1347 } else {
1348 disableHardwareVsync(false);
1349 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001350}
1351
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001353 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1354 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 // Ignore events that do not have the right sequenceId.
1363 if (sequenceId != getBE().mComposerSequenceId) {
1364 return;
1365 }
1366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Only lock if we're not on the main thread. This function is normally
1368 // called on a hwbinder thread, but for the primary display it's called on
1369 // the main thread with the state lock already held, so don't attempt to
1370 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001374
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001375 if (std::this_thread::get_id() == mMainThreadId) {
1376 // Process all pending hot plug events immediately if we are on the main thread.
1377 processDisplayHotplugEventsLocked();
1378 }
1379
Lloyd Piqueba04e622017-12-14 17:11:26 -08001380 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001388 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001389}
1390
Dan Stoza9e56aa02015-11-02 13:00:03 -08001391void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 getHwComposer().setVsyncEnabled(disp,
1395 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001396}
1397
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001399void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 // Clear the drawing state so that the logic inside of
1402 // handleTransactionLocked will fire. It will determine the delta between
1403 // mCurrentState and mDrawingState and re-apply all changes when we make the
1404 // transition.
1405 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001406 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 mDisplays.clear();
1408}
1409
Steven Thomas050b2c82017-03-06 11:45:16 -08001410void SurfaceFlinger::updateVrFlinger() {
1411 if (!mVrFlinger)
1412 return;
1413 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001414 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001415 return;
1416 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 ALOGE("Vr flinger is only supported for remote hardware composer"
1420 " service connections. Ignoring request to transition to vr"
1421 " flinger.");
1422 mVrFlingerRequestsDisplay = false;
1423 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001424 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001425
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Steven Thomas0123ac62018-07-12 11:32:34 -07001428 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001429 LOG_ALWAYS_FATAL_IF(!display);
1430 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001431 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1432 // called below. Clear the reference now so we don't accidentally use it
1433 // later.
1434 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001442 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1443 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001444 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445
David Sodman105b7dc2017-11-04 20:28:14 -07001446 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1447 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001448
1449 if (vrFlingerRequestsDisplay) {
1450 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
1453 mVisibleRegionsDirty = true;
1454 invalidateHwcGeometry();
1455
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001457 display = getDefaultDisplayDeviceLocked();
1458 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001459 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001462 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 const nsecs_t period = activeConfig->getVsyncPeriod();
1464 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001465
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001466 // The present fences returned from vr_hwc are not an accurate
1467 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001468 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1469 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Use phase of 0 since phase is not known.
1472 // Use latency of 0, which will snap to the ideal latency.
1473 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001474
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 resyncToHardwareVsync(false);
1476
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477 android_atomic_or(1, &mRepaintEverything);
1478 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479}
1480
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001482 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001485 bool frameMissed = !mHadClientComposition &&
1486 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 (mPreviousPresentFence->getSignalTime() ==
1488 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001489 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001490 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001492 mTimeStats.incrementMissedFrames();
1493 if (mPropagateBackpressure) {
1494 signalLayerUpdate();
1495 break;
1496 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 }
Dan Stoza50182882016-07-08 12:02:20 -07001498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499 // Now that we're going to make it to the handleMessageTransaction()
1500 // call below it's safe to call updateVrFlinger(), which will
1501 // potentially trigger a display handoff.
1502 updateVrFlinger();
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 bool refreshNeeded = handleMessageTransaction();
1505 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001506 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001507 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001508 // Signal a refresh if a transaction modified the window state,
1509 // a new buffer was latched, or if HWC has requested a full
1510 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 signalRefresh();
1512 }
1513 break;
1514 }
1515 case MessageQueue::REFRESH: {
1516 handleMessageRefresh();
1517 break;
1518 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 }
1520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001523 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
David Sodmanfa9b2af2017-12-24 13:28:59 -08001536 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001537 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001538 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001539 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001540
David Sodmanfa9b2af2017-12-24 13:28:59 -08001541 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001542 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001543 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001544 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1545 setUpHWComposer(compositionInfo);
1546 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001547 prepareFrame(display);
1548 doDebugFlashRegions(display, repaintEverything);
1549 doComposition(display, repaintEverything);
1550 }
1551
Adrian Roos1e1a1282017-11-01 19:05:31 +01001552 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001553 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001554
1555 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001556 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001557
Dan Stozabfbffeb2016-07-21 14:49:33 -07001558 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001559 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001560 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001561 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001562 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001563
Jorim Jaggi90535212018-05-23 23:44:06 +02001564 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001565
David Sodman7e4ae112018-02-09 15:02:28 -08001566 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001567 for (const auto& [token, display] : mDisplays) {
1568 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001569 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001570 compositionInfo.hwc.hwcLayer = nullptr;
1571 }
David Sodmanba340492018-08-05 21:51:33 -07001572 }
David Sodman7e4ae112018-02-09 15:02:28 -08001573
1574 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576
David Sodmanfa9b2af2017-12-24 13:28:59 -08001577
1578bool SurfaceFlinger::handleMessageInvalidate() {
1579 ATRACE_CALL();
1580 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581}
1582
David Sodman79bba0e2018-08-05 18:07:49 -07001583void SurfaceFlinger::calculateWorkingSet() {
1584 ATRACE_CALL();
1585 ALOGV(__FUNCTION__);
1586
David Sodman79bba0e2018-08-05 18:07:49 -07001587 // build the h/w work list
1588 if (CC_UNLIKELY(mGeometryInvalid)) {
1589 mGeometryInvalid = false;
1590 for (const auto& [token, display] : mDisplays) {
1591 const auto displayId = display->getId();
1592 if (displayId >= 0) {
1593 const Vector<sp<Layer>>& currentLayers(
1594 display->getVisibleLayersSortedByZ());
1595 for (size_t i = 0; i < currentLayers.size(); i++) {
1596 const auto& layer = currentLayers[i];
1597
1598 if (!layer->hasHwcLayer(displayId)) {
1599 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1600 layer->forceClientComposition(displayId);
1601 continue;
1602 }
1603 }
1604
1605 layer->setGeometry(display, i);
1606 if (mDebugDisableHWC || mDebugRegion) {
1607 layer->forceClientComposition(displayId);
1608 }
1609 }
1610 }
1611 }
1612 }
1613
1614 // Set the per-frame data
1615 for (const auto& [token, display] : mDisplays) {
1616 const auto displayId = display->getId();
1617 if (displayId < 0) {
1618 continue;
1619 }
1620
1621 if (mDrawingState.colorMatrixChanged) {
1622 display->setColorTransform(mDrawingState.colorMatrix);
1623 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1624 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1625 "display %d: %d", displayId, result);
1626 }
1627 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1628 if (layer->isHdrY410()) {
1629 layer->forceClientComposition(displayId);
1630 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1631 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1632 !display->hasHDR10Support()) {
1633 layer->forceClientComposition(displayId);
1634 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1635 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1636 !display->hasHLGSupport()) {
1637 layer->forceClientComposition(displayId);
1638 }
1639
1640 if (layer->getForceClientComposition(displayId)) {
1641 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1642 layer->setCompositionType(displayId, HWC2::Composition::Client);
1643 continue;
1644 }
1645
1646 layer->setPerFrameData(display);
1647 }
1648
Peiyong Lin13effd12018-07-24 17:01:47 -07001649 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001650 ColorMode colorMode;
1651 Dataspace dataSpace;
1652 RenderIntent renderIntent;
1653 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1654 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1655 }
1656 }
1657
1658 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001659
1660 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001661 const auto displayId = display->getId();
1662 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001663 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1664 auto displayId = display->getId();
1665 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1666 if (!layer->setHwcLayer(displayId)) {
1667 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1668 }
David Sodman15fb96e2018-01-07 10:23:24 -08001669 layer->getBE().compositionInfo.hwc.displayId = displayId;
1670 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001671 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1672 }
1673 }
David Sodman79bba0e2018-08-05 18:07:49 -07001674}
1675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001678 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 // is debugging enabled
1680 if (CC_LIKELY(!mDebugRegion))
1681 return;
1682
David Sodmanfa9b2af2017-12-24 13:28:59 -08001683 if (display->isPoweredOn()) {
1684 // transform the dirty region into this screen's coordinate space
1685 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1686 if (!dirtyRegion.isEmpty()) {
1687 // redraw the whole screen
1688 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690 // and draw the dirty region
1691 const int32_t height = display->getHeight();
1692 auto& engine(getRenderEngine());
1693 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001694
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696 }
1697 }
1698
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700
1701 if (mDebugRegion > 1) {
1702 usleep(mDebugRegion * 1000);
1703 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001704
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001706 status_t result = display->prepareFrame(
1707 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 ALOGE_IF(result != NO_ERROR,
1709 "prepareFrame for display %d failed:"
1710 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001711 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001712 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713}
1714
Adrian Roos1e1a1282017-11-01 19:05:31 +01001715void SurfaceFlinger::doTracing(const char* where) {
1716 ATRACE_CALL();
1717 ATRACE_NAME(where);
1718 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001719 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001720 }
1721}
1722
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001723void SurfaceFlinger::logLayerStats() {
1724 ATRACE_CALL();
1725 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001726 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001727 if (display->isPrimary()) {
1728 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001729 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001730 }
1731 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001732
1733 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001734 }
1735}
1736
David Sodman2b406362017-12-15 13:33:47 -08001737void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001739 ATRACE_CALL();
1740 ALOGV("preComposition");
1741
David Sodman2b406362017-12-15 13:33:47 -08001742 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1743
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001745 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001746 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 needExtraInvalidate = true;
1748 }
Robert Carr2047fae2016-11-28 14:09:09 -08001749 });
1750
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751 if (needExtraInvalidate) {
1752 signalLayerUpdate();
1753 }
1754}
1755
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756void SurfaceFlinger::updateCompositorTiming(
1757 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1758 std::shared_ptr<FenceTime>& presentFenceTime) {
1759 // Update queue of past composite+present times and determine the
1760 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001761 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001763 while (!getBE().mCompositePresentTimes.empty()) {
1764 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765 // Cached values should have been updated before calling this method,
1766 // which helps avoid duplicate syscalls.
1767 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1768 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1769 break;
1770 }
1771 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001772 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 }
1774
1775 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001776 while (getBE().mCompositePresentTimes.size() > 16) {
1777 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 }
1779
Brian Andersond0010582017-03-07 13:20:31 -08001780 setCompositorTimingSnapped(
1781 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1782}
1783
1784void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1785 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 // Integer division and modulo round toward 0 not -inf, so we need to
1787 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001788 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1790 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1791
Brian Andersond0010582017-03-07 13:20:31 -08001792 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1793 if (idealLatency <= 0) {
1794 idealLatency = vsyncInterval;
1795 }
1796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Snap the latency to a value that removes scheduling jitter from the
1798 // composition and present times, which often have >1ms of jitter.
1799 // Reducing jitter is important if an app attempts to extrapolate
1800 // something (such as user input) to an accurate diasplay time.
1801 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1802 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001803 nsecs_t bias = vsyncInterval / 2;
1804 int64_t extraVsyncs =
1805 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1806 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1807 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001808
David Sodman99974d22017-11-28 12:04:33 -08001809 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1810 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1811 getBE().mCompositorTiming.interval = vsyncInterval;
1812 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813}
1814
David Sodman2b406362017-12-15 13:33:47 -08001815void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 ATRACE_CALL();
1818 ALOGV("postComposition");
1819
Brian Anderson3546a3f2016-07-14 11:51:14 -07001820 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001821 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001822 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001823 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001824 }
1825
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001826 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001827 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001828
David Sodman73beded2017-11-15 11:56:06 -08001829 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001830 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001831 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001832 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001833 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835 } else {
1836 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1837 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838
David Sodman73beded2017-11-15 11:56:06 -08001839 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001840 mPreviousPresentFence =
1841 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1842 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001843 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001844
Lloyd Pique41be5d22018-06-21 13:11:48 -07001845 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1846 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847
David Sodman2b406362017-12-15 13:33:47 -08001848 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 // when we started doing work for this frame, but that should be okay
1850 // since updateCompositorTiming has snapping logic.
1851 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001852 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001853 CompositorTiming compositorTiming;
1854 {
David Sodman99974d22017-11-28 12:04:33 -08001855 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1856 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001857 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001858
Robert Carr2047fae2016-11-28 14:09:09 -08001859 mDrawingState.traverseInZOrder([&](Layer* layer) {
1860 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001861 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001862 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001863 recordBufferingStats(layer->getName().string(),
1864 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001865 }
Robert Carr2047fae2016-11-28 14:09:09 -08001866 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001867
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001868 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001869 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001870 enableHardwareVsync();
1871 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001872 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001873 }
1874 }
1875
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001876 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001877 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001878 enableHardwareVsync();
1879 }
1880 }
1881
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001882 if (mAnimCompositionPending) {
1883 mAnimCompositionPending = false;
1884
Brian Anderson4e606e32017-03-16 15:34:57 -07001885 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001886 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001887 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001888 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001889 // The HWC doesn't support present fences, so use the refresh
1890 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001891 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001892 mAnimFrameTracker.setActualPresentTime(presentTime);
1893 }
1894 mAnimFrameTracker.advanceFrame();
1895 }
Dan Stozab90cf072015-03-05 11:05:59 -08001896
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001897 mTimeStats.incrementTotalFrames();
1898 if (mHadClientComposition) {
1899 mTimeStats.incrementClientCompositionFrames();
1900 }
1901
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001903 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001904 return;
1905 }
1906
1907 nsecs_t currentTime = systemTime();
1908 if (mHasPoweredOff) {
1909 mHasPoweredOff = false;
1910 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001911 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001913 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1914 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001915 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001916 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001917 }
David Sodman4a36e932017-11-07 14:29:47 -08001918 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001919 }
David Sodman4a36e932017-11-07 14:29:47 -08001920 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001921
1922 {
1923 std::lock_guard lock(mTexturePoolMutex);
1924 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1925 if (refillCount > 0) {
1926 const size_t offset = mTexturePool.size();
1927 mTexturePool.resize(mTexturePoolSize);
1928 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1929 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1930 }
1931 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932}
1933
1934void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 ATRACE_CALL();
1936 ALOGV("rebuildLayerStacks");
1937
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001939 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001940 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001941 mVisibleRegionsDirty = false;
1942 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001943
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001944 for (const auto& pair : mDisplays) {
1945 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001946 Region opaqueRegion;
1947 Region dirtyRegion;
1948 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001949 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001950 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001951 const Rect bounds = display->getBounds();
1952 if (display->isPoweredOn()) {
1953 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001954
Jeff Sharkey76488112017-02-27 14:15:18 -07001955 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001956 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 Region drawRegion(tr.transform(
1959 layer->visibleNonTransparentRegion));
1960 drawRegion.andSelf(bounds);
1961 if (!drawRegion.isEmpty()) {
1962 layersSortedByZ.add(layer);
1963 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001964 // Clear out the HWC layer if this layer was
1965 // previously visible, but no longer is
1966 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001968 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001969 // WM changes display->layerStack upon sleep/awake.
1970 // Here we make sure we delete the HWC layers even if
1971 // WM changed their layer stack.
1972 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001973 }
1974
1975 // If a layer is not going to get a release fence because
1976 // it is invisible, but it is also going to release its
1977 // old buffer, add it to the list of layers needing
1978 // fences.
1979 if (hwcLayerDestroyed) {
1980 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1981 mLayersWithQueuedFrames.cend(), layer);
1982 if (found != mLayersWithQueuedFrames.cend()) {
1983 layersNeedingFences.add(layer);
1984 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001985 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001986 });
1987 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988 display->setVisibleLayersSortedByZ(layersSortedByZ);
1989 display->setLayersNeedingFences(layersNeedingFences);
1990 display->undefinedRegion.set(bounds);
1991 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1992 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001993 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001994 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001995}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001996
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001997// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001998// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001999// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002000// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002001// The returned HDR data space is one of
2002// - Dataspace::UNKNOWN
2003// - Dataspace::BT2020_HLG
2004// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2006 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002007 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002008 *outHdrDataSpace = Dataspace::UNKNOWN;
2009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002010 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002011 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002012 case Dataspace::V0_SCRGB:
2013 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002015 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002016 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002017 case Dataspace::BT2020_PQ:
2018 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002019 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002020 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002021 case Dataspace::BT2020_HLG:
2022 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002023 // When there's mixed PQ content and HLG content, we set the HDR
2024 // data space to be BT2020_PQ and convert HLG to PQ.
2025 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2026 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002027 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002028 break;
2029 default:
2030 break;
2031 }
Romain Guy54f154a2017-10-24 21:40:32 +01002032 }
2033
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002035}
2036
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002037// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002038void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2039 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2041 *outMode = ColorMode::NATIVE;
2042 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002043 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002044 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002045 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002046
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002047 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002049
Peiyong Lindfde5112018-06-05 10:58:41 -07002050 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002051 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002052 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002053 if (isHdr) {
2054 bestDataSpace = hdrDataSpace;
2055 }
2056
Chia-I Wu0d711262018-05-21 15:19:35 -07002057 RenderIntent intent;
2058 switch (mDisplayColorSetting) {
2059 case DisplayColorSetting::MANAGED:
2060 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002061 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002062 break;
2063 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002064 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002065 break;
2066 default: // vendor display color setting
2067 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2068 break;
2069 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002071 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002072}
2073
David Sodman10a41ff2018-08-05 12:14:17 -07002074void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2075{
2076 HWC2::Error error;
2077 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2078 "CompositionType is sideband, but sideband stream is nullptr");
2079 error = (compositionInfo.hwc.hwcLayer)
2080 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2081 if (error != HWC2::Error::None) {
2082 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2083 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2084 static_cast<int32_t>(error));
2085 }
2086}
2087
2088void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2089{
2090 HWC2::Error error;
2091
2092 if (!compositionInfo.hwc.skipGeometry) {
2093 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2094 ALOGE_IF(error != HWC2::Error::None,
2095 "[SF] Failed to set blend mode %s:"
2096 " %s (%d)",
2097 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2098 static_cast<int32_t>(error));
2099
2100 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2101 ALOGE_IF(error != HWC2::Error::None,
2102 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2103 compositionInfo.hwc.displayFrame.left,
2104 compositionInfo.hwc.displayFrame.right,
2105 compositionInfo.hwc.displayFrame.top,
2106 compositionInfo.hwc.displayFrame.bottom,
2107 to_string(error).c_str(), static_cast<int32_t>(error));
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2112 compositionInfo.hwc.sourceCrop.left,
2113 compositionInfo.hwc.sourceCrop.right,
2114 compositionInfo.hwc.sourceCrop.top,
2115 compositionInfo.hwc.sourceCrop.bottom,
2116 to_string(error).c_str(), static_cast<int32_t>(error));
2117
2118 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2119 ALOGE_IF(error != HWC2::Error::None,
2120 "[SF] Failed to set plane alpha %.3f: "
2121 "%s (%d)",
2122 compositionInfo.hwc.alpha,
2123 to_string(error).c_str(), static_cast<int32_t>(error));
2124
2125
2126 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2127 ALOGE_IF(error != HWC2::Error::None,
2128 "[SF] Failed to set Z %u: %s (%d)",
2129 compositionInfo.hwc.z,
2130 to_string(error).c_str(), static_cast<int32_t>(error));
2131
2132 error = (compositionInfo.hwc.hwcLayer)
2133 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2134 ALOGE_IF(error != HWC2::Error::None,
2135 "[SF] Failed to set info (%d)",
2136 static_cast<int32_t>(error));
2137
2138 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2139 ALOGE_IF(error != HWC2::Error::None,
2140 "[SF] Failed to set transform %s: "
2141 "%s (%d)",
2142 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2143 static_cast<int32_t>(error));
2144 }
2145
2146 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2147 ALOGE_IF(error != HWC2::Error::None,
2148 "[SF] Failed to set composition type: %s (%d)",
2149 to_string(error).c_str(), static_cast<int32_t>(error));
2150
2151 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2152 ALOGE_IF(error != HWC2::Error::None,
2153 "[SF] Failed to set dataspace: %s (%d)",
2154 to_string(error).c_str(), static_cast<int32_t>(error));
2155
2156 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2157 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2158 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2159 "[SF] Failed to set hdrMetadata: %s (%d)",
2160 to_string(error).c_str(), static_cast<int32_t>(error));
2161
2162 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2163 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2164 ALOGE_IF(error != HWC2::Error::None,
2165 "[SF] Failed to set color: %s (%d)",
2166 to_string(error).c_str(), static_cast<int32_t>(error));
2167 }
2168
2169 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2170 ALOGE_IF(error != HWC2::Error::None,
2171 "[SF] Failed to set visible region: %s (%d)",
2172 to_string(error).c_str(), static_cast<int32_t>(error));
2173
2174 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2175 ALOGE_IF(error != HWC2::Error::None,
2176 "[SF] Failed to set surface damage: %s (%d)",
2177 to_string(error).c_str(), static_cast<int32_t>(error));
2178}
2179
2180void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2181{
2182 HWC2::Error error;
2183
2184 if (compositionInfo.hwc.fence) {
2185 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2186 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2187 ALOGE_IF(error != HWC2::Error::None,
2188 "[SF] Failed to set buffer: %s (%d)",
2189 to_string(error).c_str(), static_cast<int32_t>(error));
2190 }
2191}
2192
David Sodmanfa9b2af2017-12-24 13:28:59 -08002193void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002194{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002195 bool dirty = !display->getDirtyRegion(false).isEmpty();
2196 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2197 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002198
David Sodmanfa9b2af2017-12-24 13:28:59 -08002199 // If nothing has changed (!dirty), don't recompose.
2200 // If something changed, but we don't currently have any visible layers,
2201 // and didn't when we last did a composition, then skip it this time.
2202 // The second rule does two things:
2203 // - When all layers are removed from a display, we'll emit one black
2204 // frame, then nothing more until we get new layers.
2205 // - When a display is created with a private layer stack, we won't
2206 // emit any black frames until a layer is added to the layer stack.
2207 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002208
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002209 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2210 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211 mustRecompose ? "doing" : "skipping",
2212 dirty ? "+" : "-",
2213 empty ? "+" : "-",
2214 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002215
David Sodmanfa9b2af2017-12-24 13:28:59 -08002216 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 if (mustRecompose) {
2219 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002220 }
2221}
2222
David Sodmanfa9b2af2017-12-24 13:28:59 -08002223void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002224{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002225 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002226 if (!display->isPoweredOn()) {
2227 return;
David Sodman2b406362017-12-15 13:33:47 -08002228 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002229
David Sodmanfb95bcc2017-12-22 15:45:30 -08002230 status_t result = display->prepareFrame(
2231 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232 ALOGE_IF(result != NO_ERROR,
2233 "prepareFrame for display %d failed:"
2234 " %d (%s)",
2235 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002236}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002237
David Sodman10a41ff2018-08-05 12:14:17 -07002238void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2239 ATRACE_CALL();
2240 ALOGV("setUpHWComposer");
2241
2242 switch (compositionInfo.compositionType)
2243 {
2244 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002245 break;
2246
David Sodman10a41ff2018-08-05 12:14:17 -07002247 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002248 if (compositionInfo.hwc.hwcLayer) {
2249 auto error = (compositionInfo.hwc.hwcLayer)->
2250 setCompositionType(compositionInfo.compositionType);
2251 ALOGE_IF(error != HWC2::Error::None,
2252 "[SF] Failed to set composition type: %s (%d)",
2253 to_string(error).c_str(), static_cast<int32_t>(error));
2254 }
David Sodman10a41ff2018-08-05 12:14:17 -07002255 break;
2256
2257 case HWC2::Composition::Sideband:
2258 configureHwcCommonData(compositionInfo);
2259 configureSidebandComposition(compositionInfo);
2260 break;
2261
2262 case HWC2::Composition::SolidColor:
2263 configureHwcCommonData(compositionInfo);
2264 break;
2265
2266 case HWC2::Composition::Device:
2267 case HWC2::Composition::Cursor:
2268 configureHwcCommonData(compositionInfo);
2269 configureDeviceComposition(compositionInfo);
2270 break;
2271 }
2272}
2273
David Sodmanfa9b2af2017-12-24 13:28:59 -08002274void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002275 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002276 ALOGV("doComposition");
2277
David Sodmanfa9b2af2017-12-24 13:28:59 -08002278 if (display->isPoweredOn()) {
2279 // transform the dirty region into this screen's coordinate space
2280 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002281
David Sodmanfa9b2af2017-12-24 13:28:59 -08002282 // repaint the framebuffer (if needed)
2283 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002284
David Sodmanfa9b2af2017-12-24 13:28:59 -08002285 display->dirtyRegion.clear();
2286 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002287 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002288 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289}
2290
David Sodmanfa9b2af2017-12-24 13:28:59 -08002291void SurfaceFlinger::postFrame()
2292{
2293 // |mStateLock| not needed as we are on the main thread
2294 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2295 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2296 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2297 logFrameStats();
2298 }
2299 }
2300}
2301
2302void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303{
Mathias Agopian841cde52012-03-01 15:44:37 -08002304 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002306
David Sodmanfa9b2af2017-12-24 13:28:59 -08002307 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002308
David Sodmanfa9b2af2017-12-24 13:28:59 -08002309 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002310 const auto displayId = display->getId();
2311 if (displayId >= 0) {
2312 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002313 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 display->onSwapBuffersCompleted();
2315 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002316 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002317 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002318 // The layer buffer from the previous frame (if any) is released
2319 // by HWC only when the release fence from this frame (if any) is
2320 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002321 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2322 if ((displayId >= 0) && hwcLayer) {
2323 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002324 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002325
2326 // If the layer was client composited in the previous frame, we
2327 // need to merge with the previous client target acquire fence.
2328 // Since we do not track that, always merge with the current
2329 // client target acquire fence when it is available, even though
2330 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002331 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002332 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002334 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002335
David Sodman10a41ff2018-08-05 12:14:17 -07002336 if (compositionInfo.layer) {
2337 compositionInfo.layer->onLayerDisplayed(releaseFence);
2338 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002339 }
Chia-I Wu83806892017-11-16 10:50:20 -08002340
2341 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002343 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002345 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002347 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002348 }
2349 }
2350
Dominik Laskowski7e045462018-05-30 13:02:02 -07002351 if (displayId >= 0) {
2352 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002353 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355}
2356
Mathias Agopian87baae12012-07-31 12:38:26 -07002357void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358{
Mathias Agopian841cde52012-03-01 15:44:37 -08002359 ATRACE_CALL();
2360
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002361 // here we keep a copy of the drawing state (that is the state that's
2362 // going to be overwritten by handleTransactionLocked()) outside of
2363 // mStateLock so that the side-effects of the State assignment
2364 // don't happen with mStateLock held (which can cause deadlocks).
2365 State drawingState(mDrawingState);
2366
Mathias Agopianca4d3602011-05-19 15:38:14 -07002367 Mutex::Autolock _l(mStateLock);
2368 const nsecs_t now = systemTime();
2369 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370
Mathias Agopianca4d3602011-05-19 15:38:14 -07002371 // Here we're guaranteed that some transaction flags are set
2372 // so we can call handleTransactionLocked() unconditionally.
2373 // We call getTransactionFlags(), which will also clear the flags,
2374 // with mStateLock held to guarantee that mCurrentState won't change
2375 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002376
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002377 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002378 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002379 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002380
Mathias Agopianca4d3602011-05-19 15:38:14 -07002381 mLastTransactionTime = systemTime() - now;
2382 mDebugInTransaction = 0;
2383 invalidateHwcGeometry();
2384 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002385}
2386
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002389 // Figure out whether the event is for the primary display or an
2390 // external display by matching the Hwc display id against one for a
2391 // connected display. If we did not find a match, we then check what
2392 // displays are not already connected to determine the type. If we don't
2393 // have a connected primary display, we assume the new display is meant to
2394 // be the primary display, and then if we don't have an external display,
2395 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2397 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002398 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002400 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002401 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002402 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002403 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002404 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002405 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002406 return DisplayDevice::DISPLAY_EXTERNAL;
2407 }
2408
2409 return DisplayDevice::DISPLAY_ID_INVALID;
2410}
2411
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2413 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002414 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002415 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002416 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002417 continue;
2418 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002419
2420 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2421 ALOGE("External displays are not supported by the vr hardware composer.");
2422 continue;
2423 }
2424
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002425 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002426 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002427 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002428 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002429 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430
2431 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002433 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002435 DisplayDeviceState info;
2436 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002437 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2438 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002439 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002441 mInterceptor->saveDisplayCreation(info);
2442 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002444 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002445
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002447 if (idx >= 0) {
2448 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002449 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002450 mCurrentState.displays.removeItemsAt(idx);
2451 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453 }
2454
2455 processDisplayChangesLocked();
2456 }
2457
2458 mPendingHotplugEvents.clear();
2459}
2460
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002462 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002464 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002465 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002466 HdrCapabilities hdrCapabilities;
2467 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002468
Peiyong Lin13effd12018-07-24 17:01:47 -07002469 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002470 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002472 if (isWideColorMode(colorMode)) {
2473 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002475
Dominik Laskowski7e045462018-05-30 13:02:02 -07002476 std::vector<RenderIntent> renderIntents =
2477 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002478 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479 }
tangrobin6753a022018-08-10 10:58:54 +08002480 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002481
tangrobin6753a022018-08-10 10:58:54 +08002482 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002483 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2484 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2485 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486
2487 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2488 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2489
2490 /*
2491 * Create our display's surface
2492 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002493 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002495 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496 renderSurface->setNativeWindow(nativeWindow.get());
2497 const int displayWidth = renderSurface->queryWidth();
2498 const int displayHeight = renderSurface->queryHeight();
2499
2500 // Make sure that composition can never be stalled by a virtual display
2501 // consumer that isn't processing buffers fast enough. We have to do this
2502 // in two places:
2503 // * Here, in case the display is composed entirely by HWC.
2504 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2505 // window's swap interval in eglMakeCurrent, so they'll override the
2506 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002507 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2509 }
2510
Chia-I Wua02871c2018-08-27 14:38:23 -07002511 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2512 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2513
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002515 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002517 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002518 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2519 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002520 displayHeight, displayInstallOrientation, hasWideColorGamut,
2521 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2522 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523
2524 if (maxFrameBufferAcquiredBuffers >= 3) {
2525 nativeWindowSurface->preallocateBuffers();
2526 }
2527
2528 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002529 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2530 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002532 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002534 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002535 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002536 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002538 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 display->setLayerStack(state.layerStack);
2540 display->setProjection(state.orientation, state.viewport, state.frame);
2541 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002543 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544}
2545
Lloyd Pique347200f2017-12-14 17:00:15 -08002546void SurfaceFlinger::processDisplayChangesLocked() {
2547 // here we take advantage of Vector's copy-on-write semantics to
2548 // improve performance by skipping the transaction entirely when
2549 // know that the lists are identical
2550 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2551 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2552 if (!curr.isIdenticalTo(draw)) {
2553 mVisibleRegionsDirty = true;
2554 const size_t cc = curr.size();
2555 size_t dc = draw.size();
2556
2557 // find the displays that were removed
2558 // (ie: in drawing state but not in current state)
2559 // also handle displays that changed
2560 // (ie: displays that are in both lists)
2561 for (size_t i = 0; i < dc;) {
2562 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2563 if (j < 0) {
2564 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002565 // Call makeCurrent() on the primary display so we can
2566 // be sure that nothing associated with this display
2567 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002568 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2569 defaultDisplay->makeCurrent();
2570 }
2571 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2572 display->disconnect(getHwComposer());
2573 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002574 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002575 if (mUseScheduler) {
2576 mScheduler->hotplugReceived(mAppConnectionHandle,
2577 EventThread::DisplayType::Primary, false);
2578 } else {
2579 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2580 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002581 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002582 if (mUseScheduler) {
2583 mScheduler->hotplugReceived(mAppConnectionHandle,
2584 EventThread::DisplayType::External, false);
2585 } else {
2586 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2587 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002588 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002589 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 } else {
2591 // this display is in both lists. see if something changed.
2592 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002593 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2595 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2596 if (state_binder != draw_binder) {
2597 // changing the surface is like destroying and
2598 // recreating the DisplayDevice, so we just remove it
2599 // from the drawing state, so that it get re-added
2600 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002601 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2602 display->disconnect(getHwComposer());
2603 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 mDrawingState.displays.removeItemsAt(i);
2606 dc--;
2607 // at this point we must loop to the next item
2608 continue;
2609 }
2610
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002611 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 }
2615 if ((state.orientation != draw[i].orientation) ||
2616 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002617 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002618 }
2619 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 }
2622 }
2623 }
2624 ++i;
2625 }
2626
2627 // find displays that were added
2628 // (ie: in current state but not in drawing state)
2629 for (size_t i = 0; i < cc; i++) {
2630 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2631 const DisplayDeviceState& state(curr[i]);
2632
2633 sp<DisplaySurface> dispSurface;
2634 sp<IGraphicBufferProducer> producer;
2635 sp<IGraphicBufferProducer> bqProducer;
2636 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002637 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638
Dominik Laskowski7e045462018-05-30 13:02:02 -07002639 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002640 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002641 // Virtual displays without a surface are dormant:
2642 // they have external state (layer stack, projection,
2643 // etc.) but no internal state (i.e. a DisplayDevice).
2644 if (state.surface != nullptr) {
2645 // Allow VR composer to use virtual displays.
2646 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2647 int width = 0;
2648 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2649 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2650 int height = 0;
2651 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2652 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2653 int intFormat = 0;
2654 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2655 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002656 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002657
Dominik Laskowski7e045462018-05-30 13:02:02 -07002658 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2659 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 }
2661
2662 // TODO: Plumb requested format back up to consumer
2663
2664 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002665 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 bqProducer, bqConsumer,
2667 state.displayName);
2668
2669 dispSurface = vds;
2670 producer = vds;
2671 }
2672 } else {
2673 ALOGE_IF(state.surface != nullptr,
2674 "adding a supported display, but rendering "
2675 "surface is provided (%p), ignoring it",
2676 state.surface.get());
2677
Dominik Laskowski7e045462018-05-30 13:02:02 -07002678 displayId = state.type;
2679 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 producer = bqProducer;
2681 }
2682
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002685 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002686 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002688 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002689 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002690 if (mUseScheduler) {
2691 mScheduler->hotplugReceived(mAppConnectionHandle,
2692 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002693 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002694 } else {
2695 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2696 true);
2697 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002698 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002699 if (mUseScheduler) {
2700 mScheduler->hotplugReceived(mAppConnectionHandle,
2701 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002702 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002703 } else {
2704 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2705 true);
2706 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002707 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
2709 }
2710 }
2711 }
2712 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002713
2714 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002715}
2716
Mathias Agopian87baae12012-07-31 12:38:26 -07002717void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002718{
Dan Stoza7dde5992015-05-22 09:51:44 -07002719 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002720 mCurrentState.traverseInZOrder([](Layer* layer) {
2721 layer->notifyAvailableFrames();
2722 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 /*
2725 * Traversal of the children
2726 * (perform the transaction for each of them if needed)
2727 */
2728
Mathias Agopian3559b072012-08-15 13:46:03 -07002729 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002730 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002732 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733
2734 const uint32_t flags = layer->doTransaction(0);
2735 if (flags & Layer::eVisibleRegion)
2736 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002737 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 }
2739
2740 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 */
2743
Mathias Agopiane57f2922012-08-09 16:29:12 -07002744 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002746 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002749 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002750 // The transform hint might have changed for some layers
2751 // (either because a display has changed, or because a layer
2752 // as changed).
2753 //
2754 // Walk through all the layers in currentLayers,
2755 // and update their transform hint.
2756 //
2757 // If a layer is visible only on a single display, then that
2758 // display is used to calculate the hint, otherwise we use the
2759 // default display.
2760 //
2761 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2762 // the hint is set before we acquire a buffer from the surface texture.
2763 //
2764 // NOTE: layer transactions have taken place already, so we use their
2765 // drawing state. However, SurfaceFlinger's own transaction has not
2766 // happened yet, so we must use the current state layer list
2767 // (soon to become the drawing state list).
2768 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002770 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002771 bool first = true;
2772 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002773 // NOTE: we rely on the fact that layers are sorted by
2774 // layerStack first (so we don't have to traverse the list
2775 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002776 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002777 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002778 currentlayerStack = layerStack;
2779 // figure out if this layerstack is mirrored
2780 // (more than one display) if so, pick the default display,
2781 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 hintDisplay = nullptr;
2783 for (const auto& [token, display] : mDisplays) {
2784 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2785 if (hintDisplay) {
2786 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002787 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002788 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002789 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002790 }
2791 }
2792 }
2793 }
Chet Haase91d25932013-04-11 15:24:55 -07002794
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002795 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002796 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2797 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002798
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002799 // could be null when this layer is using a layerStack
2800 // that is not visible on any display. Also can occur at
2801 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002803 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002804
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002806 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002807 if (hintDisplay) {
2808 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002809 }
Robert Carr2047fae2016-11-28 14:09:09 -08002810
2811 first = false;
2812 });
Mathias Agopian84300952012-11-21 16:02:13 -08002813 }
2814
2815
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 /*
2817 * Perform our own transaction if needed
2818 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819
2820 if (mLayersAdded) {
2821 mLayersAdded = false;
2822 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 mVisibleRegionsDirty = true;
2824 }
2825
2826 // some layers might have been removed, so
2827 // we need to update the regions they're exposing.
2828 if (mLayersRemoved) {
2829 mLayersRemoved = false;
2830 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002833 // this layer is not visible anymore
2834 // TODO: we could traverse the tree from front to back and
2835 // compute the actual visible region
2836 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 Region visibleReg;
2838 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002839 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002840 }
Robert Carr2047fae2016-11-28 14:09:09 -08002841 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 }
2843
2844 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002845
2846 updateCursorAsync();
2847}
2848
2849void SurfaceFlinger::updateCursorAsync()
2850{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002852 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002853 continue;
2854 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2857 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002858 }
2859 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860}
2861
2862void SurfaceFlinger::commitTransaction()
2863{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002864 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002865 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 for (const auto& l : mLayersPendingRemoval) {
2867 recordBufferingStats(l->getName().string(),
2868 l->getOccupancyHistory(true));
2869 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002870 }
2871 mLayersPendingRemoval.clear();
2872 }
2873
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002874 // If this transaction is part of a window animation then the next frame
2875 // we composite should be considered an animation as well.
2876 mAnimCompositionPending = mAnimTransactionPending;
2877
Mathias Agopian4fec8732012-06-29 14:12:52 -07002878 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002879 // clear the "changed" flags in current state
2880 mCurrentState.colorMatrixChanged = false;
2881
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 mDrawingState.traverseInZOrder([](Layer* layer) {
2883 layer->commitChildList();
2884 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002885 mTransactionPending = false;
2886 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002887 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2891 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002892 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002894
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 Region aboveOpaqueLayers;
2896 Region aboveCoveredLayers;
2897 Region dirty;
2898
Mathias Agopian87baae12012-07-31 12:38:26 -07002899 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900
Robert Carr2047fae2016-11-28 14:09:09 -08002901 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002903 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904
Jesse Hall01e29052013-02-19 16:13:35 -08002905 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002906 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002907 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002908 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002909
Mathias Agopianab028732010-03-16 16:41:46 -07002910 /*
2911 * opaqueRegion: area of a surface that is fully opaque.
2912 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002914
2915 /*
2916 * visibleRegion: area of a surface that is visible on screen
2917 * and not fully transparent. This is essentially the layer's
2918 * footprint minus the opaque regions above it.
2919 * Areas covered by a translucent surface are considered visible.
2920 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002922
2923 /*
2924 * coveredRegion: area of a surface that is covered by all
2925 * visible regions above it (which includes the translucent areas).
2926 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002928
Jesse Halla8026d22012-09-25 13:25:04 -07002929 /*
2930 * transparentRegion: area of a surface that is hinted to be completely
2931 * transparent. This is only used to tell when the layer has no visible
2932 * non-transparent regions and can be removed from the layer list. It
2933 * does not affect the visibleRegion of this layer or any layers
2934 * beneath it. The hint may not be correct if apps don't respect the
2935 * SurfaceView restrictions (which, sadly, some don't).
2936 */
2937 Region transparentRegion;
2938
Mathias Agopianab028732010-03-16 16:41:46 -07002939
2940 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002941 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002942 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002945 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002946 if (!visibleRegion.isEmpty()) {
2947 // Remove the transparent area from the visible region
2948 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002949 if (tr.preserveRects()) {
2950 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002951 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002953 // transformation too complex, can't do the
2954 // transparent region optimization.
2955 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002956 }
Mathias Agopianab028732010-03-16 16:41:46 -07002957 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958
Mathias Agopianab028732010-03-16 16:41:46 -07002959 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002960 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002961 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002962 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002963 // the opaque region is the layer's footprint
2964 opaqueRegion = visibleRegion;
2965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 }
2967 }
2968
Robert Carre5f4f692018-01-12 13:12:28 -08002969 if (visibleRegion.isEmpty()) {
2970 layer->clearVisibilityRegions();
2971 return;
2972 }
2973
Mathias Agopianab028732010-03-16 16:41:46 -07002974 // Clip the covered region to the visible region
2975 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2976
2977 // Update aboveCoveredLayers for next (lower) layer
2978 aboveCoveredLayers.orSelf(visibleRegion);
2979
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 // subtract the opaque region covered by the layers above us
2981 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982
2983 // compute this layer's dirty region
2984 if (layer->contentDirty) {
2985 // we need to invalidate the whole region
2986 dirty = visibleRegion;
2987 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002988 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 layer->contentDirty = false;
2990 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002991 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002992 * the exposed region consists of two components:
2993 * 1) what's VISIBLE now and was COVERED before
2994 * 2) what's EXPOSED now less what was EXPOSED before
2995 *
2996 * note that (1) is conservative, we start with the whole
2997 * visible region but only keep what used to be covered by
2998 * something -- which mean it may have been exposed.
2999 *
3000 * (2) handles areas that were not covered by anything but got
3001 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003002 */
Mathias Agopianab028732010-03-16 16:41:46 -07003003 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003004 const Region oldVisibleRegion = layer->visibleRegion;
3005 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003006 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3007 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 }
3009 dirty.subtractSelf(aboveOpaqueLayers);
3010
3011 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003012 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013
Mathias Agopianab028732010-03-16 16:41:46 -07003014 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003016
Jesse Halla8026d22012-09-25 13:25:04 -07003017 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018 layer->setVisibleRegion(visibleRegion);
3019 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003020 layer->setVisibleNonTransparentRegion(
3021 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003022 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023
Mathias Agopian87baae12012-07-31 12:38:26 -07003024 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025}
3026
Chia-I Wuab0c3192017-08-01 11:29:00 -07003027void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003028 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003029 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3030 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003031 }
3032 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003033}
3034
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003037 ALOGV("handlePageFlip");
3038
Brian Andersond6927fb2016-07-23 23:37:30 -07003039 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040
Mathias Agopian4fec8732012-06-29 14:12:52 -07003041 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003042 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003043 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003044
3045 // Store the set of layers that need updates. This set must not change as
3046 // buffers are being latched, as this could result in a deadlock.
3047 // Example: Two producers share the same command stream and:
3048 // 1.) Layer 0 is latched
3049 // 2.) Layer 0 gets a new frame
3050 // 2.) Layer 1 gets a new frame
3051 // 3.) Layer 1 is latched.
3052 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3053 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003054 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003055 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003056 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003057 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003058 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003059 } else {
3060 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003061 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003062 } else {
3063 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003064 }
Robert Carr2047fae2016-11-28 14:09:09 -08003065 });
3066
Dan Stoza9e56aa02015-11-02 13:00:03 -08003067 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003068 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003069 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003070 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003071 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003072 newDataLatched = true;
3073 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003074 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003075
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003076 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003077
3078 // If we will need to wake up at some time in the future to deal with a
3079 // queued frame that shouldn't be displayed during this vsync period, wake
3080 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003081 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 signalLayerUpdate();
3083 }
3084
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003085 // enter boot animation on first buffer latch
3086 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3087 ALOGI("Enter boot animation");
3088 mBootStage = BootStage::BOOTANIMATION;
3089 }
3090
Dan Stoza6b9454d2014-11-07 16:00:59 -08003091 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003092 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Mathias Agopianad456f92011-01-13 17:53:01 -08003095void SurfaceFlinger::invalidateHwcGeometry()
3096{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003097 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003098}
3099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003100void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3101 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003102 // We only need to actually compose the display if:
3103 // 1) It is being handled by hardware composer, which may need this to
3104 // keep its virtual display state machine in sync, or
3105 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003106 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003107 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003109 return;
3110 }
3111
Dan Stoza9e56aa02015-11-02 13:00:03 -08003112 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003113 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003114
3115 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003116 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117}
3118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003119bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003120 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003122 const Region bounds(display->bounds());
3123 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003124 const auto displayId = display->getId();
3125 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003126 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003127
Chia-I Wu8e50e692018-05-04 10:12:37 -07003128 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003129 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003130
Dan Stoza9e56aa02015-11-02 13:00:03 -08003131 if (hasClientComposition) {
3132 ALOGV("hasClientComposition");
3133
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003134 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003135 if (display->hasWideColorGamut()) {
3136 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003137 }
3138 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003139 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003140 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003141
Dominik Laskowski7e045462018-05-30 13:02:02 -07003142 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003143 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3144 HWC2::Capability::SkipClientColorTransform);
3145
Chia-I Wud49d6692018-06-27 07:17:41 +08003146 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003147 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3148 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003149 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003150 }
3151
Chia-I Wud49d6692018-06-27 07:17:41 +08003152 // The current enhanced saturation matrix is designed to enhance Display P3,
3153 // thus we only apply this matrix when the render intent is not colorimetric
3154 // and the output color space is Display P3.
3155 needsEnhancedColorMatrix =
3156 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3157 outputDataspace == Dataspace::DISPLAY_P3);
3158 if (needsEnhancedColorMatrix) {
3159 colorMatrix *= mEnhancedSaturationMatrix;
3160 }
3161
3162 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003164 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003165 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003166 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003167 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003168
3169 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003170 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3171 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3172 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003173 }
3174 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003175 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003176
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003177 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003178 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003179 // when using overlays, we assume a fully transparent framebuffer
3180 // NOTE: we could reduce how much we need to clear, for instance
3181 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003182 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003183 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003184 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003185 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003186 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003187 // we're left with the letterbox region
3188 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003189 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003190
3191 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003192 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003193
Mathias Agopianb9494d52012-04-18 02:28:45 -07003194 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003195 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003196 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003197 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003198 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003199 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003200
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003201 const Rect& bounds = display->getBounds();
3202 const Rect& scissor = display->getScissor();
3203 if (scissor != bounds) {
3204 // scissor doesn't match the screen's dimensions, so we
3205 // need to clear everything outside of it and enable
3206 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003207
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003208 // enable scissor for this frame
3209 const uint32_t height = display->getHeight();
3210 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3211 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003212 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003213 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003214
Mathias Agopian85d751c2012-08-29 16:59:24 -07003215 /*
3216 * and then, render the layers targeted at the framebuffer
3217 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003218
Dan Stoza9e56aa02015-11-02 13:00:03 -08003219 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003220 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003221 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003222 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3223 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003224 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003225 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3226 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003228 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003229 case HWC2::Composition::Cursor:
3230 case HWC2::Composition::Device:
3231 case HWC2::Composition::Sideband:
3232 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003233 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
David Sodman7772dad2018-09-07 13:50:20 -07003234 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state) &&
3235 compositionInfo.layer->mLayer->getAlpha() == 1.0f;
3236 if (compositionInfo.hwc.clearClientTarget && !firstLayer && opaque &&
3237 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003238 // never clear the very first layer since we're
3239 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003240 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003241 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003242 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003243 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003245 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003246 break;
3247 }
3248 default:
3249 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003250 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003251 } else {
3252 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003253 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003254 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003255 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003256
Chia-I Wud49d6692018-06-27 07:17:41 +08003257 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003258 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003259 }
3260
Mathias Agopianf45c5102012-10-24 16:29:17 -07003261 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003262 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003263 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264}
3265
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003266void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3267 const Region& region) const {
3268 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003269 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003270 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271}
3272
Dan Stoza7d89d062015-04-30 13:29:25 -07003273status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003274 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003275 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003276 const sp<Layer>& lbc,
3277 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003278{
Dan Stoza7d89d062015-04-30 13:29:25 -07003279 // add this layer to the current state list
3280 {
3281 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003282 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003283 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3284 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003285 return NO_MEMORY;
3286 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003287 if (parent == nullptr) {
3288 mCurrentState.layersSortedByZ.add(lbc);
3289 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003290 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003291 ALOGE("addClientLayer called with a removed parent");
3292 return NAME_NOT_FOUND;
3293 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003294 parent->addChild(lbc);
3295 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003296
Yiwei Zhang243b3782018-05-15 17:40:04 -07003297 if (gbc != nullptr) {
3298 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3299 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3300 mMaxGraphicBufferProducerListSize,
3301 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3302 mGraphicBufferProducerList.size(),
3303 mMaxGraphicBufferProducerListSize, mNumLayers);
3304 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003305 mLayersAdded = true;
3306 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003307 }
3308
Mathias Agopian96f08192010-06-02 23:28:45 -07003309 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003310 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003311
Dan Stoza7d89d062015-04-30 13:29:25 -07003312 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003313}
3314
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003315status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003316 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003317 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3318}
Robert Carr7f9b8992017-03-10 11:08:39 -08003319
chaviwca27f252018-02-06 16:46:39 -08003320status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3321 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003322 if (layer->isPendingRemoval()) {
3323 return NO_ERROR;
3324 }
3325
Robert Carr1f0a16a2016-10-24 16:27:39 -07003326 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003327 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003328 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003329 if (topLevelOnly) {
3330 return NO_ERROR;
3331 }
3332
Chia-I Wu98f1c102017-05-30 14:54:08 -07003333 sp<Layer> ancestor = p;
3334 while (ancestor->getParent() != nullptr) {
3335 ancestor = ancestor->getParent();
3336 }
3337 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3338 ALOGE("removeLayer called with a layer whose parent has been removed");
3339 return NAME_NOT_FOUND;
3340 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003341
3342 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003343 } else {
3344 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003345 }
3346
Robert Carr136e2f62017-02-08 17:54:29 -08003347 // As a matter of normal operation, the LayerCleaner will produce a second
3348 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3349 // so we will succeed in promoting it, but it's already been removed
3350 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3351 // otherwise something has gone wrong and we are leaking the layer.
3352 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003353 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3354 layer->getName().string(),
3355 (p != nullptr) ? p->getName().string() : "no-parent");
3356 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003357 } else if (index < 0) {
3358 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003359 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003360
Chia-I Wuc6657022017-08-15 11:18:17 -07003361 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003362 mLayersPendingRemoval.add(layer);
3363 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003364 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003365 setTransactionFlags(eTransactionNeeded);
3366 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367}
3368
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003369uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003370 return android_atomic_release_load(&mTransactionFlags);
3371}
3372
Mathias Agopian3f844832013-08-07 21:24:32 -07003373uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003374 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3375}
3376
Mathias Agopian3f844832013-08-07 21:24:32 -07003377uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003378 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3379}
3380
3381uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3382 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003383 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003384 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003385 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003386 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003387 }
3388 return old;
3389}
3390
chaviwca27f252018-02-06 16:46:39 -08003391bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3392 for (const ComposerState& state : states) {
3393 // Here we need to check that the interface we're given is indeed
3394 // one of our own. A malicious client could give us a nullptr
3395 // IInterface, or one of its own or even one of our own but a
3396 // different type. All these situations would cause us to crash.
3397 if (state.client == nullptr) {
3398 return true;
3399 }
3400
3401 sp<IBinder> binder = IInterface::asBinder(state.client);
3402 if (binder == nullptr) {
3403 return true;
3404 }
3405
3406 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3407 return true;
3408 }
3409 }
3410 return false;
3411}
3412
Mathias Agopian8b33f032012-07-24 20:43:54 -07003413void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003414 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003415 const Vector<DisplayState>& displays,
3416 uint32_t flags)
3417{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003418 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003419 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003420 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421
chaviwca27f252018-02-06 16:46:39 -08003422 if (containsAnyInvalidClientState(states)) {
3423 return;
3424 }
3425
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003426 if (flags & eAnimation) {
3427 // For window updates that are part of an animation we must wait for
3428 // previous animation "frames" to be handled.
3429 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003430 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003431 if (CC_UNLIKELY(err != NO_ERROR)) {
3432 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003433 // caller after a few seconds.
3434 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3435 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003436 mAnimTransactionPending = false;
3437 break;
3438 }
3439 }
3440 }
3441
chaviwca27f252018-02-06 16:46:39 -08003442 for (const DisplayState& display : displays) {
3443 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003444 }
3445
chaviwca27f252018-02-06 16:46:39 -08003446 for (const ComposerState& state : states) {
3447 transactionFlags |= setClientStateLocked(state);
3448 }
3449
3450 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3451 // as destroyed should only occur after setting all other states. This is to allow for a
3452 // child re-parent to happen before marking its original parent as destroyed (which would
3453 // then mark the child as destroyed).
3454 for (const ComposerState& state : states) {
3455 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003456 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003457
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003458 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3459 // anyway. This can be used as a flush mechanism for previous async transactions.
3460 // Empty animation transaction can be used to simulate back-pressure, so also force a
3461 // transaction for empty animation transactions.
3462 if (transactionFlags == 0 &&
3463 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003464 transactionFlags = eTransactionNeeded;
3465 }
3466
Mathias Agopian386aa982011-11-07 21:58:03 -08003467 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003468 if (mInterceptor->isEnabled()) {
3469 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003470 }
Irvel468051e2016-06-13 16:44:44 -07003471
Mathias Agopian386aa982011-11-07 21:58:03 -08003472 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003473 const auto start = (flags & eEarlyWakeup)
3474 ? VSyncModulator::TransactionStart::EARLY
3475 : VSyncModulator::TransactionStart::NORMAL;
3476 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003477
3478 // if this is a synchronous transaction, wait for it to take effect
3479 // before returning.
3480 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003481 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003482 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003483 if (flags & eAnimation) {
3484 mAnimTransactionPending = true;
3485 }
3486 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003487 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3488 if (CC_UNLIKELY(err != NO_ERROR)) {
3489 // just in case something goes wrong in SF, return to the
3490 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003491 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3492 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003493 break;
3494 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 }
3497}
3498
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003499uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3500 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3501 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003502
Mathias Agopiane57f2922012-08-09 16:29:12 -07003503 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003504 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3505
3506 const uint32_t what = s.what;
3507 if (what & DisplayState::eSurfaceChanged) {
3508 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3509 state.surface = s.surface;
3510 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003511 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003512 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003513 if (what & DisplayState::eLayerStackChanged) {
3514 if (state.layerStack != s.layerStack) {
3515 state.layerStack = s.layerStack;
3516 flags |= eDisplayTransactionNeeded;
3517 }
3518 }
3519 if (what & DisplayState::eDisplayProjectionChanged) {
3520 if (state.orientation != s.orientation) {
3521 state.orientation = s.orientation;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 if (state.frame != s.frame) {
3525 state.frame = s.frame;
3526 flags |= eDisplayTransactionNeeded;
3527 }
3528 if (state.viewport != s.viewport) {
3529 state.viewport = s.viewport;
3530 flags |= eDisplayTransactionNeeded;
3531 }
3532 }
3533 if (what & DisplayState::eDisplaySizeChanged) {
3534 if (state.width != s.width) {
3535 state.width = s.width;
3536 flags |= eDisplayTransactionNeeded;
3537 }
3538 if (state.height != s.height) {
3539 state.height = s.height;
3540 flags |= eDisplayTransactionNeeded;
3541 }
3542 }
3543
Mathias Agopiane57f2922012-08-09 16:29:12 -07003544 return flags;
3545}
3546
Robert Carrd4ae7f32018-06-07 16:10:57 -07003547bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3548 IPCThreadState* ipc = IPCThreadState::self();
3549 const int pid = ipc->getCallingPid();
3550 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003551 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003552 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003553 return false;
3554 }
3555 return true;
3556}
3557
chaviwca27f252018-02-06 16:46:39 -08003558uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3559 const layer_state_t& s = composerState.state;
3560 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3561
Mathias Agopian13127d82013-03-05 17:47:11 -08003562 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003563 if (layer == nullptr) {
3564 return 0;
3565 }
3566
3567 if (layer->isPendingRemoval()) {
3568 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3569 return 0;
3570 }
3571
3572 uint32_t flags = 0;
3573
3574 const uint32_t what = s.what;
3575 bool geometryAppliesWithResize =
3576 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003577
3578 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3579 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003580 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003581 layer->pushPendingState();
3582 }
3583
chaviw8b3871a2017-11-01 17:41:01 -07003584 if (what & layer_state_t::ePositionChanged) {
3585 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3586 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 }
chaviw8b3871a2017-11-01 17:41:01 -07003588 }
3589 if (what & layer_state_t::eLayerChanged) {
3590 // NOTE: index needs to be calculated before we update the state
3591 const auto& p = layer->getParent();
3592 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003593 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003594 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003595 mCurrentState.layersSortedByZ.removeAt(idx);
3596 mCurrentState.layersSortedByZ.add(layer);
3597 // we need traversal (state changed)
3598 // AND transaction (list changed)
3599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
chaviw8b3871a2017-11-01 17:41:01 -07003601 } else {
3602 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003603 flags |= eTransactionNeeded|eTraversalNeeded;
3604 }
3605 }
chaviw8b3871a2017-11-01 17:41:01 -07003606 }
3607 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003608 // NOTE: index needs to be calculated before we update the state
3609 const auto& p = layer->getParent();
3610 if (p == nullptr) {
3611 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3612 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3613 mCurrentState.layersSortedByZ.removeAt(idx);
3614 mCurrentState.layersSortedByZ.add(layer);
3615 // we need traversal (state changed)
3616 // AND transaction (list changed)
3617 flags |= eTransactionNeeded|eTraversalNeeded;
3618 }
3619 } else {
3620 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3621 flags |= eTransactionNeeded|eTraversalNeeded;
3622 }
chaviw8b3871a2017-11-01 17:41:01 -07003623 }
3624 }
3625 if (what & layer_state_t::eSizeChanged) {
3626 if (layer->setSize(s.w, s.h)) {
3627 flags |= eTraversalNeeded;
3628 }
3629 }
3630 if (what & layer_state_t::eAlphaChanged) {
3631 if (layer->setAlpha(s.alpha))
3632 flags |= eTraversalNeeded;
3633 }
3634 if (what & layer_state_t::eColorChanged) {
3635 if (layer->setColor(s.color))
3636 flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003639 // TODO: b/109894387
3640 //
3641 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3642 // rotation. To see the problem observe that if we have a square parent, and a child
3643 // of the same size, then we rotate the child 45 degrees around it's center, the child
3644 // must now be cropped to a non rectangular 8 sided region.
3645 //
3646 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3647 // private API, and the WindowManager only uses rotation in one case, which is on a top
3648 // level layer in which cropping is not an issue.
3649 //
3650 // However given that abuse of rotation matrices could lead to surfaces extending outside
3651 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3652 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3653 // transformations.
3654 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003655 flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eTransparentRegionChanged) {
3658 if (layer->setTransparentRegionHint(s.transparentRegion))
3659 flags |= eTraversalNeeded;
3660 }
3661 if (what & layer_state_t::eFlagsChanged) {
3662 if (layer->setFlags(s.flags, s.mask))
3663 flags |= eTraversalNeeded;
3664 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003665 if (what & layer_state_t::eCropChanged_legacy) {
3666 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003667 flags |= eTraversalNeeded;
3668 }
chaviw8b3871a2017-11-01 17:41:01 -07003669 if (what & layer_state_t::eLayerStackChanged) {
3670 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3671 // We only allow setting layer stacks for top level layers,
3672 // everything else inherits layer stack from its parent.
3673 if (layer->hasParent()) {
3674 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3675 layer->getName().string());
3676 } else if (idx < 0) {
3677 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3678 "that also does not appear in the top level layer list. Something"
3679 " has gone wrong.", layer->getName().string());
3680 } else if (layer->setLayerStack(s.layerStack)) {
3681 mCurrentState.layersSortedByZ.removeAt(idx);
3682 mCurrentState.layersSortedByZ.add(layer);
3683 // we need traversal (state changed)
3684 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003685 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003686 }
3687 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003688 if (what & layer_state_t::eDeferTransaction_legacy) {
3689 if (s.barrierHandle_legacy != nullptr) {
3690 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3691 } else if (s.barrierGbp_legacy != nullptr) {
3692 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003693 if (authenticateSurfaceTextureLocked(gbp)) {
3694 const auto& otherLayer =
3695 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003696 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003697 } else {
3698 ALOGE("Attempt to defer transaction to to an"
3699 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003700 }
3701 }
chaviw8b3871a2017-11-01 17:41:01 -07003702 // We don't trigger a traversal here because if no other state is
3703 // changed, we don't want this to cause any more work
3704 }
3705 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003706 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003707 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003708 if (!hadParent) {
3709 mCurrentState.layersSortedByZ.remove(layer);
3710 }
chaviw8b3871a2017-11-01 17:41:01 -07003711 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003712 }
chaviw8b3871a2017-11-01 17:41:01 -07003713 }
3714 if (what & layer_state_t::eReparentChildren) {
3715 if (layer->reparentChildren(s.reparentHandle)) {
3716 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003717 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 }
chaviw8b3871a2017-11-01 17:41:01 -07003719 if (what & layer_state_t::eDetachChildren) {
3720 layer->detachChildren();
3721 }
3722 if (what & layer_state_t::eOverrideScalingModeChanged) {
3723 layer->setOverrideScalingMode(s.overrideScalingMode);
3724 // We don't trigger a traversal here because if no other state is
3725 // changed, we don't want this to cause any more work
3726 }
Marissa Wall61c58622018-07-18 10:12:20 -07003727 if (what & layer_state_t::eTransformChanged) {
3728 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3731 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3732 flags |= eTraversalNeeded;
3733 }
3734 if (what & layer_state_t::eCropChanged) {
3735 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3736 }
3737 if (what & layer_state_t::eBufferChanged) {
3738 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3739 }
3740 if (what & layer_state_t::eAcquireFenceChanged) {
3741 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3742 }
3743 if (what & layer_state_t::eDataspaceChanged) {
3744 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3745 }
3746 if (what & layer_state_t::eHdrMetadataChanged) {
3747 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3748 }
3749 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3750 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3751 }
3752 if (what & layer_state_t::eApiChanged) {
3753 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3754 }
3755 if (what & layer_state_t::eSidebandStreamChanged) {
3756 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3757 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003758 return flags;
3759}
3760
chaviwca27f252018-02-06 16:46:39 -08003761void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3762 const layer_state_t& state = composerState.state;
3763 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3764
3765 sp<Layer> layer(client->getLayerUser(state.surface));
3766 if (layer == nullptr) {
3767 return;
3768 }
3769
3770 if (layer->isPendingRemoval()) {
3771 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3772 return;
3773 }
3774
3775 if (state.what & layer_state_t::eDestroySurface) {
3776 removeLayerLocked(mStateLock, layer);
3777 }
3778}
3779
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003780status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003781 const String8& name,
3782 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003783 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003784 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003785 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003787 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003788 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003789 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003790 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003791 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003792
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003793 status_t result = NO_ERROR;
3794
3795 sp<Layer> layer;
3796
Cody Northropbc755282017-03-31 12:00:08 -06003797 String8 uniqueName = getUniqueLayerName(name);
3798
Mathias Agopian3165cc22012-08-08 19:42:09 -07003799 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003800 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003801 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3802 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003805 case ISurfaceComposerClient::eFXSurfaceBufferState:
3806 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3807 break;
chaviw13fdc492017-06-27 12:40:18 -07003808 case ISurfaceComposerClient::eFXSurfaceColor:
3809 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003810 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003811 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003812 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003813 case ISurfaceComposerClient::eFXSurfaceContainer:
3814 result = createContainerLayer(client,
3815 uniqueName, w, h, flags,
3816 handle, &layer);
3817 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003818 default:
3819 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 break;
3821 }
3822
Dan Stoza7d89d062015-04-30 13:29:25 -07003823 if (result != NO_ERROR) {
3824 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003826
Chia-I Wuab0c3192017-08-01 11:29:00 -07003827 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3828 // TODO b/64227542
3829 if (windowType == 441731) {
3830 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3831 layer->setPrimaryDisplayOnly();
3832 }
3833
Albert Chaulk479c60c2017-01-27 14:21:34 -05003834 layer->setInfo(windowType, ownerUid);
3835
Robert Carr1f0a16a2016-10-24 16:27:39 -07003836 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003837 if (result != NO_ERROR) {
3838 return result;
3839 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003840 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003841
3842 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003844}
3845
Cody Northropbc755282017-03-31 12:00:08 -06003846String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3847{
3848 bool matchFound = true;
3849 uint32_t dupeCounter = 0;
3850
3851 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3852 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3853
Dan Stoza436ccf32018-06-21 12:10:12 -07003854 // Grab the state lock since we're accessing mCurrentState
3855 Mutex::Autolock lock(mStateLock);
3856
Cody Northropbc755282017-03-31 12:00:08 -06003857 // Loop over layers until we're sure there is no matching name
3858 while (matchFound) {
3859 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003860 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003861 if (layer->getName() == uniqueName) {
3862 matchFound = true;
3863 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3864 }
3865 });
3866 }
3867
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003868 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3869 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003870
3871 return uniqueName;
3872}
3873
Marissa Wallfd668622018-05-10 10:21:13 -07003874status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3875 uint32_t w, uint32_t h, uint32_t flags,
3876 PixelFormat& format, sp<IBinder>* handle,
3877 sp<IGraphicBufferProducer>* gbp,
3878 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003880 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003881 case PIXEL_FORMAT_TRANSPARENT:
3882 case PIXEL_FORMAT_TRANSLUCENT:
3883 format = PIXEL_FORMAT_RGBA_8888;
3884 break;
3885 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003886 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 break;
3888 }
3889
Marissa Wallfd668622018-05-10 10:21:13 -07003890 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3891 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003892 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003893 *handle = layer->getHandle();
3894 *gbp = layer->getProducer();
3895 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003897
Marissa Wallfd668622018-05-10 10:21:13 -07003898 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003899 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900}
3901
Marissa Wall61c58622018-07-18 10:12:20 -07003902status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3903 uint32_t w, uint32_t h, uint32_t flags,
3904 sp<IBinder>* handle, sp<Layer>* outLayer) {
3905 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3906 *handle = layer->getHandle();
3907 *outLayer = layer;
3908
3909 return NO_ERROR;
3910}
3911
chaviw13fdc492017-06-27 12:40:18 -07003912status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003913 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003914 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915{
chaviw13fdc492017-06-27 12:40:18 -07003916 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003917 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003918 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003919}
3920
Robert Carr6b3f6c52018-08-13 13:05:17 -07003921status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3922 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3923 sp<IBinder>* handle, sp<Layer>* outLayer)
3924{
3925 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3926 *handle = (*outLayer)->getHandle();
3927 return NO_ERROR;
3928}
3929
3930
Mathias Agopianac9fa422013-02-11 16:40:36 -08003931status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932{
Robert Carr9524cb32017-02-13 11:32:32 -08003933 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003934 status_t err = NO_ERROR;
3935 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003936 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003937 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003938 err = removeLayer(l);
3939 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3940 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003941 }
3942 return err;
3943}
3944
Mathias Agopian13127d82013-03-05 17:47:11 -08003945status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003946{
Mathias Agopian67106042013-03-14 19:18:13 -07003947 // called by ~LayerCleaner() when all references to the IBinder (handle)
3948 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003949 sp<Layer> l = layer.promote();
3950 if (l == nullptr) {
3951 // The layer has already been removed, carry on
3952 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003953 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003954 // If we have a parent, then we can continue to live as long as it does.
3955 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956}
3957
Mathias Agopianb60314a2012-04-10 22:09:54 -07003958// ---------------------------------------------------------------------------
3959
Andy McFadden13a082e2012-08-24 10:16:42 -07003960void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003961 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3962 if (!displayToken) return;
3963
Jesse Hall01e29052013-02-19 16:13:35 -08003964 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003965 Vector<ComposerState> state;
3966 Vector<DisplayState> displays;
3967 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003968 d.what = DisplayState::eDisplayProjectionChanged |
3969 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003970 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003971 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003972 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003973 d.frame.makeInvalid();
3974 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003975 d.width = 0;
3976 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003977 displays.add(d);
3978 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003979
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003980 const auto display = getDisplayDevice(displayToken);
3981 if (!display) return;
3982
3983 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3984
3985 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003986 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003988
Brian Andersond0010582017-03-07 13:20:31 -08003989 // Use phase of 0 since phase is not known.
3990 // Use latency of 0, which will snap to the ideal latency.
3991 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003992}
3993
3994void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003995 // Async since we may be called from the main thread.
3996 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003997}
3998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003999void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4000 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004001 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004005 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004006 return;
4007 }
4008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004009 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004010 ALOGW("Trying to set power mode for virtual display");
4011 return;
4012 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004014 display->setPowerMode(mode);
4015
Lloyd Pique4dccc412018-01-22 17:21:36 -08004016 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004017 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004018 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004019 if (idx < 0) {
4020 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4021 return;
4022 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004023 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004024 }
4025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004026 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004027 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004028 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004029 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004030 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004031 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004032 if (mUseScheduler) {
4033 mScheduler->onScreenAcquired(mAppConnectionHandle);
4034 } else {
4035 mEventThread->onScreenAcquired();
4036 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004037 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004039
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004040 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004041 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004042 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004043
4044 struct sched_param param = {0};
4045 param.sched_priority = 1;
4046 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4047 ALOGW("Couldn't set SCHED_FIFO on display on");
4048 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004049 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004050 // Turn off the display
4051 struct sched_param param = {0};
4052 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4053 ALOGW("Couldn't set SCHED_OTHER on display off");
4054 }
4055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004056 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004057 disableHardwareVsync(true); // also cancels any in-progress resync
4058
Mathias Agopiancde87a32012-09-13 14:09:01 -07004059 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004060 if (mUseScheduler) {
4061 mScheduler->onScreenReleased(mAppConnectionHandle);
4062 } else {
4063 mEventThread->onScreenReleased();
4064 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004065 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004066
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004067 getHwComposer().setPowerMode(type, mode);
4068 mVisibleRegionsDirty = true;
4069 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004070 } else if (mode == HWC_POWER_MODE_DOZE ||
4071 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004072 // Update display while dozing
4073 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004074 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004075 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004076 if (mUseScheduler) {
4077 mScheduler->onScreenAcquired(mAppConnectionHandle);
4078 } else {
4079 mEventThread->onScreenAcquired();
4080 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004081 resyncToHardwareVsync(true);
4082 }
4083 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4084 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004085 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004086 disableHardwareVsync(true); // also cancels any in-progress resync
4087 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004088 if (mUseScheduler) {
4089 mScheduler->onScreenReleased(mAppConnectionHandle);
4090 } else {
4091 mEventThread->onScreenReleased();
4092 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004093 }
4094 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004095 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004096 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004097 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099
4100 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101}
4102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004103void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004104 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004105 const auto display = getDisplayDevice(displayToken);
4106 if (!display) {
4107 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4108 displayToken.get());
4109 } else if (display->isVirtual()) {
4110 ALOGW("Attempt to set power mode %d for virtual display", mode);
4111 } else {
4112 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004113 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004114 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004115}
4116
4117// ---------------------------------------------------------------------------
4118
Lloyd Pique755e3192018-01-31 16:46:15 -08004119status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4120 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004122
Mathias Agopianbd115332013-04-18 16:41:04 -07004123 IPCThreadState* ipc = IPCThreadState::self();
4124 const int pid = ipc->getCallingPid();
4125 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004126
Mathias Agopianbd115332013-04-18 16:41:04 -07004127 if ((uid != AID_SHELL) &&
4128 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004129 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004130 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004132 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004133 // (this would indicate SF is stuck, but we want to be able to
4134 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004135 status_t err = mStateLock.timedLock(s2ns(1));
4136 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004137 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004138 result.appendFormat(
4139 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4140 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004141 }
4142
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143 bool dumpAll = true;
4144 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004145 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004146
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004148 if ((index < numArgs) &&
4149 (args[index] == String16("--list"))) {
4150 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004151 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004152 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153 }
4154
4155 if ((index < numArgs) &&
4156 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004157 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004158 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004159 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004160 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004161
4162 if ((index < numArgs) &&
4163 (args[index] == String16("--latency-clear"))) {
4164 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004165 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004166 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004167 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004168
4169 if ((index < numArgs) &&
4170 (args[index] == String16("--dispsync"))) {
4171 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004172 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004173 dumpAll = false;
4174 }
Dan Stozab90cf072015-03-05 11:05:59 -08004175
4176 if ((index < numArgs) &&
4177 (args[index] == String16("--static-screen"))) {
4178 index++;
4179 dumpStaticScreenStats(result);
4180 dumpAll = false;
4181 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004182
4183 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004184 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004185 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004186 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004187 dumpAll = false;
4188 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004189
4190 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4191 index++;
4192 dumpWideColorInfo(result);
4193 dumpAll = false;
4194 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004195
4196 if ((index < numArgs) &&
4197 (args[index] == String16("--enable-layer-stats"))) {
4198 index++;
4199 mLayerStats.enable();
4200 dumpAll = false;
4201 }
4202
4203 if ((index < numArgs) &&
4204 (args[index] == String16("--disable-layer-stats"))) {
4205 index++;
4206 mLayerStats.disable();
4207 dumpAll = false;
4208 }
4209
4210 if ((index < numArgs) &&
4211 (args[index] == String16("--clear-layer-stats"))) {
4212 index++;
4213 mLayerStats.clear();
4214 dumpAll = false;
4215 }
4216
4217 if ((index < numArgs) &&
4218 (args[index] == String16("--dump-layer-stats"))) {
4219 index++;
4220 mLayerStats.dump(result);
4221 dumpAll = false;
4222 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004223
4224 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004225 (args[index] == String16("--frame-composition"))) {
4226 index++;
4227 dumpFrameCompositionInfo(result);
4228 dumpAll = false;
4229 }
4230
4231 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004232 (args[index] == String16("--display-identification"))) {
4233 index++;
4234 dumpDisplayIdentificationData(result);
4235 dumpAll = false;
4236 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004237
4238 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4239 index++;
4240 mTimeStats.parseArgs(asProto, args, index, result);
4241 dumpAll = false;
4242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004244
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004246 if (asProto) {
4247 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4248 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4249 } else {
4250 dumpAllLocked(args, index, result);
4251 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004252 }
4253
Mathias Agopian9795c422009-08-26 16:36:26 -07004254 if (locked) {
4255 mStateLock.unlock();
4256 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004257 }
4258 write(fd, result.string(), result.size());
4259 return NO_ERROR;
4260}
4261
Dan Stozac7014012014-02-14 15:03:43 -08004262void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4263 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004264{
Robert Carr2047fae2016-11-28 14:09:09 -08004265 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004266 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004267 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004268}
4269
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004271 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272{
4273 String8 name;
4274 if (index < args.size()) {
4275 name = String8(args[index]);
4276 index++;
4277 }
4278
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004279 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4280 getHwComposer().isConnected(displayId)) {
4281 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4282 const nsecs_t period = activeConfig->getVsyncPeriod();
4283 result.appendFormat("%" PRId64 "\n", period);
4284 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004285
4286 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004287 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004288 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004289 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004290 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004291 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004292 }
Robert Carr2047fae2016-11-28 14:09:09 -08004293 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294 }
4295}
4296
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004297void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004298 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004299{
4300 String8 name;
4301 if (index < args.size()) {
4302 name = String8(args[index]);
4303 index++;
4304 }
4305
Robert Carr2047fae2016-11-28 14:09:09 -08004306 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004307 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004308 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004309 }
Robert Carr2047fae2016-11-28 14:09:09 -08004310 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004311
Svetoslavd85084b2014-03-20 10:28:31 -07004312 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004313}
4314
Jamie Gennis6547ff42013-07-16 20:12:42 -07004315// This should only be called from the main thread. Otherwise it would need
4316// the lock and should use mCurrentState rather than mDrawingState.
4317void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004318 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004319 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004320 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004321
4322 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4323}
4324
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004325void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004326{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004327 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004328
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004329 if (isLayerTripleBufferingDisabled())
4330 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004331
4332 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004333 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004334 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004335 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004336 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4337 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004338 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004339}
4340
Dan Stozab90cf072015-03-05 11:05:59 -08004341void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4342{
4343 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004344 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4345 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004346 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004347 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004348 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4349 b + 1, bucketTimeSec, percent);
4350 }
David Sodman4a36e932017-11-07 14:29:47 -08004351 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004352 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004353 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004354 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004355 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004356}
4357
Dan Stozae77c7662016-05-13 11:37:28 -07004358void SurfaceFlinger::recordBufferingStats(const char* layerName,
4359 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004360 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4361 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004362 for (const auto& segment : history) {
4363 if (!segment.usedThirdBuffer) {
4364 stats.twoBufferTime += segment.totalTime;
4365 }
4366 if (segment.occupancyAverage < 1.0f) {
4367 stats.doubleBufferedTime += segment.totalTime;
4368 } else if (segment.occupancyAverage < 2.0f) {
4369 stats.tripleBufferedTime += segment.totalTime;
4370 }
4371 ++stats.numSegments;
4372 stats.totalTime += segment.totalTime;
4373 }
4374}
4375
Brian Andersond6927fb2016-07-23 23:37:30 -07004376void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4377 result.appendFormat("Layer frame timestamps:\n");
4378
4379 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4380 const size_t count = currentLayers.size();
4381 for (size_t i=0 ; i<count ; i++) {
4382 currentLayers[i]->dumpFrameEvents(result);
4383 }
4384}
4385
Dan Stozae77c7662016-05-13 11:37:28 -07004386void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4387 result.append("Buffering stats:\n");
4388 result.append(" [Layer name] <Active time> <Two buffer> "
4389 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004390 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004391 typedef std::tuple<std::string, float, float, float> BufferTuple;
4392 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004393 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004394 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004395 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004396 if (stats.numSegments == 0) {
4397 continue;
4398 }
4399 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4400 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4401 stats.totalTime;
4402 float doubleBufferRatio = static_cast<float>(
4403 stats.doubleBufferedTime) / stats.totalTime;
4404 float tripleBufferRatio = static_cast<float>(
4405 stats.tripleBufferedTime) / stats.totalTime;
4406 sorted.insert({activeTime, {name, twoBufferRatio,
4407 doubleBufferRatio, tripleBufferRatio}});
4408 }
4409 for (const auto& sortedPair : sorted) {
4410 float activeTime = sortedPair.first;
4411 const BufferTuple& values = sortedPair.second;
4412 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4413 std::get<0>(values).c_str(), activeTime,
4414 std::get<1>(values), std::get<2>(values),
4415 std::get<3>(values));
4416 }
4417 result.append("\n");
4418}
4419
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004421 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004422 const int32_t displayId = display->getId();
4423 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4424 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004425 continue;
4426 }
4427
Dominik Laskowski7e045462018-05-30 13:02:02 -07004428 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004429 uint8_t port;
4430 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004431 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 result.append("no identification data\n");
4433 continue;
4434 }
4435
4436 if (!isEdid(data)) {
4437 result.append("unknown identification data: ");
4438 for (uint8_t byte : data) {
4439 result.appendFormat("%x ", byte);
4440 }
4441 result.append("\n");
4442 continue;
4443 }
4444
4445 const auto edid = parseEdid(data);
4446 if (!edid) {
4447 result.append("invalid EDID: ");
4448 for (uint8_t byte : data) {
4449 result.appendFormat("%x ", byte);
4450 }
4451 result.append("\n");
4452 continue;
4453 }
4454
4455 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4456 result.append(edid->displayName.data(), edid->displayName.length());
4457 result.append("\"\n");
4458 }
4459 result.append("\n");
4460}
4461
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004462void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004463 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4464 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004465 result.appendFormat("DisplayColorSetting: %s\n",
4466 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004467
4468 // TODO: print out if wide-color mode is active or not
4469
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004470 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004471 const int32_t displayId = display->getId();
4472 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004473 continue;
4474 }
4475
Dominik Laskowski7e045462018-05-30 13:02:02 -07004476 result.appendFormat("Display %d color modes:\n", displayId);
4477 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004478 for (auto&& mode : modes) {
4479 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4480 }
4481
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004482 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004483 result.appendFormat(" Current color mode: %s (%d)\n",
4484 decodeColorMode(currentMode).c_str(), currentMode);
4485 }
4486 result.append("\n");
4487}
4488
David Sodman7e4ae112018-02-09 15:02:28 -08004489void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4490 std::string stringResult;
4491
4492 for (const auto& [token, display] : mDisplays) {
4493 const auto displayId = display->getId();
4494 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4495 continue;
4496 }
4497
4498 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4499 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4500 break;
4501 }
4502 const auto& compositionInfoList = compositionInfoIt->second;
4503 stringResult += base::StringPrintf("Display: %d\n", displayId);
4504 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4505 for (const auto& compositionInfo : compositionInfoList) {
4506 compositionInfo.dump(stringResult, nullptr);
4507 stringResult += base::StringPrintf("\n");
4508 }
4509 }
4510
4511 result.append(stringResult.c_str());
4512}
4513
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004514LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004515 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004516 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4517 const State& state = useDrawing ? mDrawingState : mCurrentState;
4518 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004519 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004520 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004521 });
4522
4523 return layersProto;
4524}
4525
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004526LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004527 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004528
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004529 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 resolution->set_w(display.getWidth());
4531 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004532
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4534 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4535 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004536
Dominik Laskowski7e045462018-05-30 13:02:02 -07004537 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004538 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004539 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004540 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004541 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004542 }
4543 });
4544
4545 return layersProto;
4546}
4547
Mathias Agopian74d211a2013-04-22 16:55:35 +02004548void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4549 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004551 bool colorize = false;
4552 if (index < args.size()
4553 && (args[index] == String16("--color"))) {
4554 colorize = true;
4555 index++;
4556 }
4557
4558 Colorizer colorizer(colorize);
4559
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560 // figure out if we're stuck somewhere
4561 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004562 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4564
4565 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004566 * Dump library configuration.
4567 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004568
4569 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004570 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004572 appendSfConfigString(result);
4573 appendUiConfigString(result);
4574 appendGuiConfigString(result);
4575 result.append("\n");
4576
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004577 result.append("\nDisplay identification data:\n");
4578 dumpDisplayIdentificationData(result);
4579
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004580 result.append("\nWide-Color information:\n");
4581 dumpWideColorInfo(result);
4582
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004583 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004584 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004585 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004586 result.append(SyncFeatures::getInstance().toString());
4587 result.append("\n");
4588
Andy McFadden41d67d72014-04-25 16:58:34 -07004589 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004590 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004591 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004592
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004593 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4594 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004595 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4596 getHwComposer().isConnected(displayId)) {
4597 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004598 result.appendFormat("Display %d: "
4599 "app phase %" PRId64 " ns, "
4600 "sf phase %" PRId64 " ns, "
4601 "early app phase %" PRId64 " ns, "
4602 "early sf phase %" PRId64 " ns, "
4603 "early app gl phase %" PRId64 " ns, "
4604 "early sf gl phase %" PRId64 " ns, "
4605 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4606 displayId,
4607 vsyncPhaseOffsetNs,
4608 sfVsyncPhaseOffsetNs,
4609 appEarlyOffset,
4610 sfEarlyOffset,
4611 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004612 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004613 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004614 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004615 result.append("\n");
4616
Dan Stozab90cf072015-03-05 11:05:59 -08004617 // Dump static screen stats
4618 result.append("\n");
4619 dumpStaticScreenStats(result);
4620 result.append("\n");
4621
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004622 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4623
Dan Stozae77c7662016-05-13 11:37:28 -07004624 dumpBufferingStats(result);
4625
Andy McFadden4803b742012-09-24 19:07:20 -07004626 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627 * Dump the visible layer list
4628 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004630 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004631 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4632 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004634
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004635 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004636 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004637 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004638 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004639
David Sodman7e4ae112018-02-09 15:02:28 -08004640 result.append("\nFrame-Composition information:\n");
4641 dumpFrameCompositionInfo(result);
4642 result.append("\n");
4643
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004645 * Dump Display state
4646 */
4647
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004649 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004650 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004651 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004652 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004653 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004654 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004655
4656 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004657 * Dump SurfaceFlinger global state
4658 */
4659
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004660 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004661 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004662 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004663
Mathias Agopian888c8222012-08-04 21:10:38 -07004664 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004665 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004666
David Sodmanbc815282017-11-05 18:57:52 -08004667 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004669 if (display) {
4670 display->undefinedRegion.dump(result, "undefinedRegion");
4671 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4672 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004673 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004674 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004675 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004676 mTransactionFlags, !mGpuToCpuSupported);
4677
4678 if (display) {
4679 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4680 result.appendFormat(" refresh-rate : %f fps\n"
4681 " x-dpi : %f\n"
4682 " y-dpi : %f\n",
4683 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4684 activeConfig->getDpiY());
4685 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686
Mathias Agopian74d211a2013-04-22 16:55:35 +02004687 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004689
Ana Krulec98b5b242018-08-10 15:03:23 -07004690 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691 /*
4692 * VSYNC state
4693 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004694 if (mUseScheduler) {
4695 mScheduler->dump(mAppConnectionHandle, result);
4696 } else {
4697 mEventThread->dump(result);
4698 }
Dan Stozae22aec72016-08-01 13:20:59 -07004699 result.append("\n");
4700
4701 /*
4702 * HWC layer minidump
4703 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004704 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004705 const int32_t displayId = display->getId();
4706 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004707 continue;
4708 }
4709
Dominik Laskowski7e045462018-05-30 13:02:02 -07004710 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004711 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004712 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004713 result.append("\n");
4714 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715
4716 /*
4717 * Dump HWComposer state
4718 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004720 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004722 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004723 result.appendFormat(" h/w composer %s\n",
4724 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004725 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726
4727 /*
4728 * Dump gralloc state
4729 */
4730 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4731 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004732
4733 /*
4734 * Dump VrFlinger state if in use.
4735 */
4736 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4737 result.append("VrFlinger state:\n");
4738 result.append(mVrFlinger->Dump().c_str());
4739 result.append("\n");
4740 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741}
4742
Dominik Laskowski7e045462018-05-30 13:02:02 -07004743const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004744 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004745 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004746 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004747 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004748 }
4749 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004750
4751 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4752 static const Vector<sp<Layer>> empty;
4753 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004754}
4755
Keun young Park63f165f2012-08-31 10:53:36 -07004756bool SurfaceFlinger::startDdmConnection()
4757{
4758 void* libddmconnection_dso =
4759 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4760 if (!libddmconnection_dso) {
4761 return false;
4762 }
4763 void (*DdmConnection_start)(const char* name);
4764 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004765 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004766 if (!DdmConnection_start) {
4767 dlclose(libddmconnection_dso);
4768 return false;
4769 }
4770 (*DdmConnection_start)(getServiceName());
4771 return true;
4772}
4773
Chia-I Wu28f320b2018-05-03 11:02:56 -07004774void SurfaceFlinger::updateColorMatrixLocked() {
4775 mat4 colorMatrix;
4776 if (mGlobalSaturationFactor != 1.0f) {
4777 // Rec.709 luma coefficients
4778 float3 luminance{0.213f, 0.715f, 0.072f};
4779 luminance *= 1.0f - mGlobalSaturationFactor;
4780 mat4 saturationMatrix = mat4(
4781 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4782 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4783 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4784 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4785 );
4786 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4787 } else {
4788 colorMatrix = mClientColorMatrix * mDaltonizer();
4789 }
4790
4791 if (mCurrentState.colorMatrix != colorMatrix) {
4792 mCurrentState.colorMatrix = colorMatrix;
4793 mCurrentState.colorMatrixChanged = true;
4794 setTransactionFlags(eTransactionNeeded);
4795 }
4796}
4797
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004798status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799#pragma clang diagnostic push
4800#pragma clang diagnostic error "-Wswitch-enum"
4801 switch (static_cast<ISurfaceComposerTag>(code)) {
4802 // These methods should at minimum make sure that the client requested
4803 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004804 case BOOT_FINISHED:
4805 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806 case CREATE_CONNECTION:
4807 case CREATE_DISPLAY:
4808 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004809 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 case GET_ACTIVE_COLOR_MODE:
4811 case GET_ANIMATION_FRAME_STATS:
4812 case GET_HDR_CAPABILITIES:
4813 case SET_ACTIVE_CONFIG:
4814 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004815 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004816 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004817 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4818 IPCThreadState* ipc = IPCThreadState::self();
4819 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4820 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004821 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004822 }
Robert Carr1db73f62016-12-21 12:58:51 -08004823 return OK;
4824 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004825 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004826 IPCThreadState* ipc = IPCThreadState::self();
4827 const int pid = ipc->getCallingPid();
4828 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004829 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4830 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004831 return PERMISSION_DENIED;
4832 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004834 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 // Used by apps to hook Choreographer to SurfaceFlinger.
4836 case CREATE_DISPLAY_EVENT_CONNECTION:
4837 // The following calls are currently used by clients that do not
4838 // request necessary permissions. However, they do not expose any secret
4839 // information, so it is OK to pass them.
4840 case AUTHENTICATE_SURFACE:
4841 case GET_ACTIVE_CONFIG:
4842 case GET_BUILT_IN_DISPLAY:
4843 case GET_DISPLAY_COLOR_MODES:
4844 case GET_DISPLAY_CONFIGS:
4845 case GET_DISPLAY_STATS:
4846 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4847 // Calling setTransactionState is safe, because you need to have been
4848 // granted a reference to Client* and Handle* to do anything with it.
4849 case SET_TRANSACTION_STATE:
4850 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004851 case CREATE_SCOPED_CONNECTION:
4852 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 return OK;
4854 }
4855 case CAPTURE_LAYERS:
4856 case CAPTURE_SCREEN: {
4857 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004858 IPCThreadState* ipc = IPCThreadState::self();
4859 const int pid = ipc->getCallingPid();
4860 const int uid = ipc->getCallingUid();
4861 if ((uid != AID_GRAPHICS) &&
4862 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4863 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4864 return PERMISSION_DENIED;
4865 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 return OK;
4867 }
4868 // The following codes are deprecated and should never be allowed to access SF.
4869 case CONNECT_DISPLAY_UNUSED:
4870 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4871 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4872 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004874 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004875
4876 // These codes are used for the IBinder protocol to either interrogate the recipient
4877 // side of the transaction for its canonical interface descriptor or to dump its state.
4878 // We let them pass by default.
4879 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4880 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4881 code == IBinder::SYSPROPS_TRANSACTION) {
4882 return OK;
4883 }
4884 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4885 // in onTransact verifies that the user is root, and has access to use SF.
4886 if (code >= 1000 && code <= 1029) {
4887 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4888 return OK;
4889 }
4890 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4891 return PERMISSION_DENIED;
4892#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004893}
4894
Ana Krulec13be8ad2018-08-21 02:43:56 +00004895status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4896 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004897 status_t credentialCheck = CheckTransactCodeCredentials(code);
4898 if (credentialCheck != OK) {
4899 return credentialCheck;
4900 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004901
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004902 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4903 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004904 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004905 IPCThreadState* ipc = IPCThreadState::self();
4906 const int uid = ipc->getCallingUid();
4907 if (CC_UNLIKELY(uid != AID_SYSTEM
4908 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004909 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004910 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004911 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 return PERMISSION_DENIED;
4913 }
4914 int n;
4915 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004916 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004917 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 return NO_ERROR;
4919 case 1002: // SHOW_UPDATES
4920 n = data.readInt32();
4921 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004922 invalidateHwcGeometry();
4923 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004925 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004926 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004929 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004930 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004931 setTransactionFlags(
4932 eTransactionNeeded|
4933 eDisplayTransactionNeeded|
4934 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004935 return NO_ERROR;
4936 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004937 case 1006:{ // send empty update
4938 signalRefresh();
4939 return NO_ERROR;
4940 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004941 case 1008: // toggle use of hw composer
4942 n = data.readInt32();
4943 mDebugDisableHWC = n ? 1 : 0;
4944 invalidateHwcGeometry();
4945 repaintEverything();
4946 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004947 case 1009: // toggle use of transform hint
4948 n = data.readInt32();
4949 mDebugDisableTransformHint = n ? 1 : 0;
4950 invalidateHwcGeometry();
4951 repaintEverything();
4952 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004954 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 reply->writeInt32(0);
4956 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004957 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004958 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004959 return NO_ERROR;
4960 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004961 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004962 if (!display) {
4963 return NAME_NOT_FOUND;
4964 }
4965
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004966 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004967 return NO_ERROR;
4968 }
4969 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004970 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004971 // daltonize
4972 n = data.readInt32();
4973 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004974 case 1:
4975 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4976 break;
4977 case 2:
4978 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4979 break;
4980 case 3:
4981 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4982 break;
4983 default:
4984 mDaltonizer.setType(ColorBlindnessType::None);
4985 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004986 }
4987 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004988 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004989 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004990 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004991 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004992
4993 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004995 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004996 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004997 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004998 // apply a color matrix
4999 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005000 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005001 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005002 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005003 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005004 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005005 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005006 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005008 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005009 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005010
5011 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5012 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005013 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005014 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5015 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5016 }
5017
Chia-I Wu28f320b2018-05-03 11:02:56 -07005018 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005019 return NO_ERROR;
5020 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005021 // This is an experimental interface
5022 // Needs to be shifted to proper binder interface when we productize
5023 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005024 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005025 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005026 return NO_ERROR;
5027 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005028 case 1017: {
5029 n = data.readInt32();
5030 mForceFullDamage = static_cast<bool>(n);
5031 return NO_ERROR;
5032 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005033 case 1018: { // Modify Choreographer's phase offset
5034 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005035 if (mUseScheduler) {
5036 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5037 } else {
5038 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5039 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005040 return NO_ERROR;
5041 }
5042 case 1019: { // Modify SurfaceFlinger's phase offset
5043 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005044 if (mUseScheduler) {
5045 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5046 } else {
5047 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5048 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005049 return NO_ERROR;
5050 }
Irvel468051e2016-06-13 16:44:44 -07005051 case 1020: { // Layer updates interceptor
5052 n = data.readInt32();
5053 if (n) {
5054 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005055 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005056 }
5057 else{
5058 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005059 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005060 }
5061 return NO_ERROR;
5062 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005063 case 1021: { // Disable HWC virtual displays
5064 n = data.readInt32();
5065 mUseHwcVirtualDisplays = !n;
5066 return NO_ERROR;
5067 }
Romain Guy0147a172017-06-01 13:53:56 -07005068 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005070 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005071
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005073 return NO_ERROR;
5074 }
Romain Guy54f154a2017-10-24 21:40:32 +01005075 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005076 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005077 invalidateHwcGeometry();
5078 repaintEverything();
5079 return NO_ERROR;
5080 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005081 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5082 // deprecate 1024 if they can.
5083 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005084 reply->writeBool(hasWideColorDisplay);
5085 return NO_ERROR;
5086 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005087 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005088 n = data.readInt32();
5089 if (n) {
5090 ALOGV("LayerTracing enabled");
5091 mTracing.enable();
5092 doTracing("tracing.enable");
5093 reply->writeInt32(NO_ERROR);
5094 } else {
5095 ALOGV("LayerTracing disabled");
5096 status_t err = mTracing.disable();
5097 reply->writeInt32(err);
5098 }
5099 return NO_ERROR;
5100 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005101 case 1026: { // Get layer tracing status
5102 reply->writeBool(mTracing.isEnabled());
5103 return NO_ERROR;
5104 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005105 // Is a DisplayColorSetting supported?
5106 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005107 const auto display = getDefaultDisplayDevice();
5108 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005109 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005110 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005111
5112 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5113 switch (setting) {
5114 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005115 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005116 break;
5117 case DisplayColorSetting::UNMANAGED:
5118 reply->writeBool(true);
5119 break;
5120 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005121 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005122 break;
5123 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005124 reply->writeBool(
5125 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005126 break;
5127 }
5128 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005129 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005130 // Is VrFlinger active?
5131 case 1028: {
5132 Mutex::Autolock _l(mStateLock);
5133 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5134 return NO_ERROR;
5135 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005136 case 1029: {
5137 // Code 1029 is an experimental feature that allows applications to
5138 // simulate a high frequency panel by setting a multiplier and divisor
5139 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005140 // 0, then the code simply return the current multiplier and divisor.
5141 HWC2::Device::FrequencyScaler frequencyScaler;
5142 frequencyScaler.multiplier = data.readInt32();
5143 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005144
David Sodman44b5de02018-08-21 16:28:53 -07005145 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5146 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5147 reply->writeInt32(frequencyScaler.multiplier);
5148 reply->writeInt32(frequencyScaler.divisor);
5149 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005150 }
5151
David Sodman44b5de02018-08-21 16:28:53 -07005152 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005153 enableHardwareVsync();
5154 } else {
5155 disableHardwareVsync(true);
5156 }
David Sodman44b5de02018-08-21 16:28:53 -07005157 mPrimaryDispSync->scalePeriod(frequencyScaler);
5158 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005159
David Sodman44b5de02018-08-21 16:28:53 -07005160 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5161 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5162
5163 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5164 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5165
5166 onHotplugReceived(getBE().mComposerSequenceId,
5167 hwcDisplayId, HWC2::Connection::Disconnected);
5168 onHotplugReceived(getBE().mComposerSequenceId,
5169 hwcDisplayId, HWC2::Connection::Connected);
5170 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5171 reply->writeInt32(frequencyScaler.multiplier);
5172 reply->writeInt32(frequencyScaler.divisor);
5173
David Sodman6d46c1e2018-07-13 12:59:48 -07005174 return NO_ERROR;
5175 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005176 // Is device color managed?
5177 case 1030: {
5178 reply->writeBool(useColorManagement);
5179 return NO_ERROR;
5180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005181 }
5182 }
5183 return err;
5184}
5185
Steven Thomas6d8110b2017-08-31 18:24:21 -07005186void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005187 android_atomic_or(1, &mRepaintEverything);
5188 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005189}
5190
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005191// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5192class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005193public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005194 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5195 ~WindowDisconnector() {
5196 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005197 }
5198
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005199private:
5200 ANativeWindow* mWindow;
5201 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005202};
5203
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005204status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5205 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5206 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5207 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005208 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005209 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005211 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005212
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005213 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5214
Chia-I Wu20261cb2018-08-23 12:55:44 -07005215 sp<DisplayDevice> display;
5216 {
5217 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005218
Chia-I Wu20261cb2018-08-23 12:55:44 -07005219 display = getDisplayDeviceLocked(displayToken);
5220 if (!display) return BAD_VALUE;
5221
Chia-I Wu8730ba82018-08-29 09:25:59 -07005222 // ignore sourceCrop (i.e., use the projected logical display
5223 // viewport) until the framework is fixed
5224 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005225
5226 // set the requested width/height to the logical display viewport size
5227 // by default
5228 if (reqWidth == 0 || reqHeight == 0) {
5229 reqWidth = uint32_t(display->getViewport().width());
5230 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005231 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005232 }
5233
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005234 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005235
5236 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005238 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005239}
5240
5241status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005242 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005243 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005244 ATRACE_CALL();
5245
5246 class LayerRenderArea : public RenderArea {
5247 public:
Robert Carr578038f2018-03-09 12:25:24 -08005248 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5249 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005250 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005251 mLayer(layer),
5252 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005253 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005254 mFlinger(flinger),
5255 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005256 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005257 Rect getBounds() const override {
5258 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005259 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005260 }
Marissa Wall61c58622018-07-18 10:12:20 -07005261 int getHeight() const override {
5262 return mLayer->getActiveHeight(mLayer->getDrawingState());
5263 }
5264 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005265 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005266 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005267 Rect getSourceCrop() const override {
5268 if (mCrop.isEmpty()) {
5269 return getBounds();
5270 } else {
5271 return mCrop;
5272 }
5273 }
Robert Carr578038f2018-03-09 12:25:24 -08005274 class ReparentForDrawing {
5275 public:
5276 const sp<Layer>& oldParent;
5277 const sp<Layer>& newParent;
5278
5279 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5280 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005281 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005282 }
Robert Carr15eae092018-03-23 13:43:53 -07005283 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005284 };
5285
5286 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005287 const Rect sourceCrop = getSourceCrop();
5288 // no need to check rotation because there is none
5289 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5290 sourceCrop.height() != getReqHeight();
5291
Robert Carr578038f2018-03-09 12:25:24 -08005292 if (!mChildrenOnly) {
5293 mTransform = mLayer->getTransform().inverse();
5294 drawLayers();
5295 } else {
5296 Rect bounds = getBounds();
5297 screenshotParentLayer =
5298 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5299 bounds.getWidth(), bounds.getHeight(), 0);
5300
5301 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5302 drawLayers();
5303 }
5304 }
chaviwa76b2712017-09-20 12:02:26 -07005305
chaviwa76b2712017-09-20 12:02:26 -07005306 private:
chaviw7206d492017-11-10 16:16:12 -08005307 const sp<Layer> mLayer;
5308 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005309
5310 // In the "childrenOnly" case we reparent the children to a screenshot
5311 // layer which has no properties set and which does not draw.
5312 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005313 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005314 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005315
5316 SurfaceFlinger* mFlinger;
5317 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005318 };
5319
5320 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5321 auto parent = layerHandle->owner.promote();
5322
chaviw7206d492017-11-10 16:16:12 -08005323 if (parent == nullptr || parent->isPendingRemoval()) {
5324 ALOGE("captureLayers called with a removed parent");
5325 return NAME_NOT_FOUND;
5326 }
5327
Robert Carr578038f2018-03-09 12:25:24 -08005328 const int uid = IPCThreadState::self()->getCallingUid();
5329 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5330 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5331 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5332 return PERMISSION_DENIED;
5333 }
5334
chaviw7206d492017-11-10 16:16:12 -08005335 Rect crop(sourceCrop);
5336 if (sourceCrop.width() <= 0) {
5337 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005338 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005339 }
5340
5341 if (sourceCrop.height() <= 0) {
5342 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005343 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005344 }
5345
5346 int32_t reqWidth = crop.width() * frameScale;
5347 int32_t reqHeight = crop.height() * frameScale;
5348
Chia-I Wu20261cb2018-08-23 12:55:44 -07005349 // really small crop or frameScale
5350 if (reqWidth <= 0) {
5351 reqWidth = 1;
5352 }
5353 if (reqHeight <= 0) {
5354 reqHeight = 1;
5355 }
5356
Robert Carr578038f2018-03-09 12:25:24 -08005357 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005358
Robert Carr578038f2018-03-09 12:25:24 -08005359 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005360 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5361 if (!layer->isVisible()) {
5362 return;
Robert Carr578038f2018-03-09 12:25:24 -08005363 } else if (childrenOnly && layer == parent.get()) {
5364 return;
chaviwa76b2712017-09-20 12:02:26 -07005365 }
5366 visitor(layer);
5367 });
5368 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005369 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005370}
5371
5372status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5373 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005374 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005375 bool useIdentityTransform) {
5376 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005377
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005378 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5379 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5380 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5381 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382
5383 // This mutex protects syncFd and captureResult for communication of the return values from the
5384 // main thread back to this Binder thread
5385 std::mutex captureMutex;
5386 std::condition_variable captureCondition;
5387 std::unique_lock<std::mutex> captureLock(captureMutex);
5388 int syncFd = -1;
5389 std::optional<status_t> captureResult;
5390
Robert Carr03480e22018-01-04 16:02:06 -08005391 const int uid = IPCThreadState::self()->getCallingUid();
5392 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5393
Dominik Laskowski8c001672018-05-30 16:52:06 -07005394 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395 // If there is a refresh pending, bug out early and tell the binder thread to try again
5396 // after the refresh.
5397 if (mRefreshPending) {
5398 ATRACE_NAME("Skipping screenshot for now");
5399 std::unique_lock<std::mutex> captureLock(captureMutex);
5400 captureResult = std::make_optional<status_t>(EAGAIN);
5401 captureCondition.notify_one();
5402 return;
5403 }
5404
5405 status_t result = NO_ERROR;
5406 int fd = -1;
5407 {
5408 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005409 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005410 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5411 useIdentityTransform, forSystem, &fd);
5412 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 }
5414
5415 {
5416 std::unique_lock<std::mutex> captureLock(captureMutex);
5417 syncFd = fd;
5418 captureResult = std::make_optional<status_t>(result);
5419 captureCondition.notify_one();
5420 }
5421 });
5422
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005423 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005425 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426 while (*captureResult == EAGAIN) {
5427 captureResult.reset();
5428 result = postMessageAsync(message);
5429 if (result != NO_ERROR) {
5430 return result;
5431 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005432 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005433 }
5434 result = *captureResult;
5435 }
5436
5437 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005438 sync_wait(syncFd, -1);
5439 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005440 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005441
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005443}
5444
chaviwa76b2712017-09-20 12:02:26 -07005445void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005446 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005447 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005448 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005449
Lloyd Pique144e1162017-12-20 16:44:52 -08005450 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005451
chaviwa76b2712017-09-20 12:02:26 -07005452 const auto reqWidth = renderArea.getReqWidth();
5453 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005454 const auto sourceCrop = renderArea.getSourceCrop();
5455 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005456
Chia-I Wu36574d92018-05-16 10:54:36 -07005457 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5458 engine.setOutputDataSpace(Dataspace::SRGB);
5459 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005460
Mathias Agopian180f10d2013-04-10 22:55:41 -07005461 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005462 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463
5464 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005465 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005466 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005467
chaviw50da5042018-04-09 13:49:37 -07005468 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005469 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005470 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005471
chaviwa76b2712017-09-20 12:02:26 -07005472 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005473 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005474 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005475}
5476
chaviwa76b2712017-09-20 12:02:26 -07005477status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5478 TraverseLayersFunction traverseLayers,
5479 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005480 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005481 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005482 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005483 ATRACE_CALL();
5484
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005485 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005486
5487 traverseLayers([&](Layer* layer) {
5488 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5489 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005490
Robert Carr03480e22018-01-04 16:02:06 -08005491 // We allow the system server to take screenshots of secure layers for
5492 // use in situations like the Screen-rotation animation and place
5493 // the impetus on WindowManager to not persist them.
5494 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005495 ALOGW("FB is protected: PERMISSION_DENIED");
5496 return PERMISSION_DENIED;
5497 }
5498
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005499 // this binds the given EGLImage as a framebuffer for the
5500 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005501 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005502 if (bufferBond.getStatus() != NO_ERROR) {
5503 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005504 return INVALID_OPERATION;
5505 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005506
Dan Stozaabcda352017-06-01 14:37:39 -07005507 // this will in fact render into our dequeued buffer
5508 // via an FBO, which means we didn't have to create
5509 // an EGLSurface and therefore we're not
5510 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005511 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005512
Dan Stozaabcda352017-06-01 14:37:39 -07005513 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005514 getRenderEngine().finish();
5515 *outSyncFd = -1;
5516
chaviwa76b2712017-09-20 12:02:26 -07005517 const auto reqWidth = renderArea.getReqWidth();
5518 const auto reqHeight = renderArea.getReqHeight();
5519
Dan Stozaabcda352017-06-01 14:37:39 -07005520 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5521 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005522 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005523 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005524 } else {
5525 base::unique_fd syncFd = getRenderEngine().flush();
5526 if (syncFd < 0) {
5527 getRenderEngine().finish();
5528 }
5529 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005530 }
5531
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005532 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005533}
5534
Mathias Agopiand5556842013-09-19 17:08:37 -07005535void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005536 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005537 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005538 for (size_t y = 0; y < h; y++) {
5539 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5540 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005541 if (p[x] != 0xFF000000) return;
5542 }
5543 }
chaviwa76b2712017-09-20 12:02:26 -07005544 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005545
Robert Carr2047fae2016-11-28 14:09:09 -08005546 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005547 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005548 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005549 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5550 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5551 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5552 static_cast<float>(state.color.a));
5553 i++;
5554 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005555 }
5556}
5557
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005558// ---------------------------------------------------------------------------
5559
Dan Stoza412903f2017-04-27 13:42:17 -07005560void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5561 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005562}
5563
Dan Stoza412903f2017-04-27 13:42:17 -07005564void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5565 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005566}
5567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005568void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5569 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005570 const LayerVector::Visitor& visitor) {
5571 // We loop through the first level of layers without traversing,
5572 // as we need to interpret min/max layer Z in the top level Z space.
5573 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005574 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005575 continue;
5576 }
5577 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005578 // relative layers are traversed in Layer::traverseInZOrder
5579 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005580 continue;
5581 }
5582 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005583 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005584 return;
5585 }
chaviwa76b2712017-09-20 12:02:26 -07005586 if (!layer->isVisible()) {
5587 return;
5588 }
5589 visitor(layer);
5590 });
5591 }
5592}
5593
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005594}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005595
Lloyd Pique074e8122018-07-26 12:57:23 -07005596
Mathias Agopian3f844832013-08-07 21:24:32 -07005597#if defined(__gl_h_)
5598#error "don't include gl/gl.h in this file"
5599#endif
5600
5601#if defined(__gl2_h_)
5602#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005603#endif