blob: a5bd73a532a64a8b97db9d2498c8982555b99461 [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 =
670 renderengine::impl::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());
3234 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3235 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3236 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003237 // never clear the very first layer since we're
3238 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003239 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003240 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003241 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003242 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003243 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003244 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003245 break;
3246 }
3247 default:
3248 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003249 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003250 } else {
3251 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003252 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003253 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003254 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003255
Chia-I Wud49d6692018-06-27 07:17:41 +08003256 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003257 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003258 }
3259
Mathias Agopianf45c5102012-10-24 16:29:17 -07003260 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003261 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003262 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003265void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3266 const Region& region) const {
3267 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003268 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003269 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270}
3271
Dan Stoza7d89d062015-04-30 13:29:25 -07003272status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003273 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003274 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 const sp<Layer>& lbc,
3276 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003277{
Dan Stoza7d89d062015-04-30 13:29:25 -07003278 // add this layer to the current state list
3279 {
3280 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003281 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003282 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3283 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003284 return NO_MEMORY;
3285 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003286 if (parent == nullptr) {
3287 mCurrentState.layersSortedByZ.add(lbc);
3288 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003289 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003290 ALOGE("addClientLayer called with a removed parent");
3291 return NAME_NOT_FOUND;
3292 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003293 parent->addChild(lbc);
3294 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003295
Yiwei Zhang243b3782018-05-15 17:40:04 -07003296 if (gbc != nullptr) {
3297 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3298 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3299 mMaxGraphicBufferProducerListSize,
3300 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3301 mGraphicBufferProducerList.size(),
3302 mMaxGraphicBufferProducerListSize, mNumLayers);
3303 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003304 mLayersAdded = true;
3305 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003306 }
3307
Mathias Agopian96f08192010-06-02 23:28:45 -07003308 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003309 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003310
Dan Stoza7d89d062015-04-30 13:29:25 -07003311 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003312}
3313
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003314status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003315 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003316 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3317}
Robert Carr7f9b8992017-03-10 11:08:39 -08003318
chaviwca27f252018-02-06 16:46:39 -08003319status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3320 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003321 if (layer->isPendingRemoval()) {
3322 return NO_ERROR;
3323 }
3324
Robert Carr1f0a16a2016-10-24 16:27:39 -07003325 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003326 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003327 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003328 if (topLevelOnly) {
3329 return NO_ERROR;
3330 }
3331
Chia-I Wu98f1c102017-05-30 14:54:08 -07003332 sp<Layer> ancestor = p;
3333 while (ancestor->getParent() != nullptr) {
3334 ancestor = ancestor->getParent();
3335 }
3336 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3337 ALOGE("removeLayer called with a layer whose parent has been removed");
3338 return NAME_NOT_FOUND;
3339 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003340
3341 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003342 } else {
3343 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003344 }
3345
Robert Carr136e2f62017-02-08 17:54:29 -08003346 // As a matter of normal operation, the LayerCleaner will produce a second
3347 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3348 // so we will succeed in promoting it, but it's already been removed
3349 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3350 // otherwise something has gone wrong and we are leaking the layer.
3351 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003352 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3353 layer->getName().string(),
3354 (p != nullptr) ? p->getName().string() : "no-parent");
3355 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003356 } else if (index < 0) {
3357 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003358 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003359
Chia-I Wuc6657022017-08-15 11:18:17 -07003360 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 mLayersPendingRemoval.add(layer);
3362 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003363 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003364 setTransactionFlags(eTransactionNeeded);
3365 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366}
3367
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003368uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003369 return android_atomic_release_load(&mTransactionFlags);
3370}
3371
Mathias Agopian3f844832013-08-07 21:24:32 -07003372uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3374}
3375
Mathias Agopian3f844832013-08-07 21:24:32 -07003376uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003377 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3378}
3379
3380uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3381 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003383 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003385 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003386 }
3387 return old;
3388}
3389
chaviwca27f252018-02-06 16:46:39 -08003390bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3391 for (const ComposerState& state : states) {
3392 // Here we need to check that the interface we're given is indeed
3393 // one of our own. A malicious client could give us a nullptr
3394 // IInterface, or one of its own or even one of our own but a
3395 // different type. All these situations would cause us to crash.
3396 if (state.client == nullptr) {
3397 return true;
3398 }
3399
3400 sp<IBinder> binder = IInterface::asBinder(state.client);
3401 if (binder == nullptr) {
3402 return true;
3403 }
3404
3405 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3406 return true;
3407 }
3408 }
3409 return false;
3410}
3411
Mathias Agopian8b33f032012-07-24 20:43:54 -07003412void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003413 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003414 const Vector<DisplayState>& displays,
3415 uint32_t flags)
3416{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003417 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003418 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003419 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003420
chaviwca27f252018-02-06 16:46:39 -08003421 if (containsAnyInvalidClientState(states)) {
3422 return;
3423 }
3424
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003425 if (flags & eAnimation) {
3426 // For window updates that are part of an animation we must wait for
3427 // previous animation "frames" to be handled.
3428 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003429 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003430 if (CC_UNLIKELY(err != NO_ERROR)) {
3431 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003432 // caller after a few seconds.
3433 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3434 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003435 mAnimTransactionPending = false;
3436 break;
3437 }
3438 }
3439 }
3440
chaviwca27f252018-02-06 16:46:39 -08003441 for (const DisplayState& display : displays) {
3442 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003443 }
3444
chaviwca27f252018-02-06 16:46:39 -08003445 for (const ComposerState& state : states) {
3446 transactionFlags |= setClientStateLocked(state);
3447 }
3448
3449 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3450 // as destroyed should only occur after setting all other states. This is to allow for a
3451 // child re-parent to happen before marking its original parent as destroyed (which would
3452 // then mark the child as destroyed).
3453 for (const ComposerState& state : states) {
3454 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003455 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003456
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003457 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3458 // anyway. This can be used as a flush mechanism for previous async transactions.
3459 // Empty animation transaction can be used to simulate back-pressure, so also force a
3460 // transaction for empty animation transactions.
3461 if (transactionFlags == 0 &&
3462 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003463 transactionFlags = eTransactionNeeded;
3464 }
3465
Mathias Agopian386aa982011-11-07 21:58:03 -08003466 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003467 if (mInterceptor->isEnabled()) {
3468 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003469 }
Irvel468051e2016-06-13 16:44:44 -07003470
Mathias Agopian386aa982011-11-07 21:58:03 -08003471 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003472 const auto start = (flags & eEarlyWakeup)
3473 ? VSyncModulator::TransactionStart::EARLY
3474 : VSyncModulator::TransactionStart::NORMAL;
3475 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003476
3477 // if this is a synchronous transaction, wait for it to take effect
3478 // before returning.
3479 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003480 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003481 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003482 if (flags & eAnimation) {
3483 mAnimTransactionPending = true;
3484 }
3485 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003486 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3487 if (CC_UNLIKELY(err != NO_ERROR)) {
3488 // just in case something goes wrong in SF, return to the
3489 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003490 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3491 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003492 break;
3493 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495 }
3496}
3497
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003498uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3499 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3500 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003501
Mathias Agopiane57f2922012-08-09 16:29:12 -07003502 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003503 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3504
3505 const uint32_t what = s.what;
3506 if (what & DisplayState::eSurfaceChanged) {
3507 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3508 state.surface = s.surface;
3509 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003510 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003511 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003512 if (what & DisplayState::eLayerStackChanged) {
3513 if (state.layerStack != s.layerStack) {
3514 state.layerStack = s.layerStack;
3515 flags |= eDisplayTransactionNeeded;
3516 }
3517 }
3518 if (what & DisplayState::eDisplayProjectionChanged) {
3519 if (state.orientation != s.orientation) {
3520 state.orientation = s.orientation;
3521 flags |= eDisplayTransactionNeeded;
3522 }
3523 if (state.frame != s.frame) {
3524 state.frame = s.frame;
3525 flags |= eDisplayTransactionNeeded;
3526 }
3527 if (state.viewport != s.viewport) {
3528 state.viewport = s.viewport;
3529 flags |= eDisplayTransactionNeeded;
3530 }
3531 }
3532 if (what & DisplayState::eDisplaySizeChanged) {
3533 if (state.width != s.width) {
3534 state.width = s.width;
3535 flags |= eDisplayTransactionNeeded;
3536 }
3537 if (state.height != s.height) {
3538 state.height = s.height;
3539 flags |= eDisplayTransactionNeeded;
3540 }
3541 }
3542
Mathias Agopiane57f2922012-08-09 16:29:12 -07003543 return flags;
3544}
3545
Robert Carrd4ae7f32018-06-07 16:10:57 -07003546bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3547 IPCThreadState* ipc = IPCThreadState::self();
3548 const int pid = ipc->getCallingPid();
3549 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003550 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003551 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003552 return false;
3553 }
3554 return true;
3555}
3556
chaviwca27f252018-02-06 16:46:39 -08003557uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3558 const layer_state_t& s = composerState.state;
3559 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3560
Mathias Agopian13127d82013-03-05 17:47:11 -08003561 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (layer == nullptr) {
3563 return 0;
3564 }
3565
3566 if (layer->isPendingRemoval()) {
3567 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3568 return 0;
3569 }
3570
3571 uint32_t flags = 0;
3572
3573 const uint32_t what = s.what;
3574 bool geometryAppliesWithResize =
3575 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003576
3577 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3578 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003579 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003580 layer->pushPendingState();
3581 }
3582
chaviw8b3871a2017-11-01 17:41:01 -07003583 if (what & layer_state_t::ePositionChanged) {
3584 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3585 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 }
3588 if (what & layer_state_t::eLayerChanged) {
3589 // NOTE: index needs to be calculated before we update the state
3590 const auto& p = layer->getParent();
3591 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003592 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003593 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594 mCurrentState.layersSortedByZ.removeAt(idx);
3595 mCurrentState.layersSortedByZ.add(layer);
3596 // we need traversal (state changed)
3597 // AND transaction (list changed)
3598 flags |= eTransactionNeeded|eTraversalNeeded;
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 } else {
3601 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003602 flags |= eTransactionNeeded|eTraversalNeeded;
3603 }
3604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003607 // NOTE: index needs to be calculated before we update the state
3608 const auto& p = layer->getParent();
3609 if (p == nullptr) {
3610 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3611 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3612 mCurrentState.layersSortedByZ.removeAt(idx);
3613 mCurrentState.layersSortedByZ.add(layer);
3614 // we need traversal (state changed)
3615 // AND transaction (list changed)
3616 flags |= eTransactionNeeded|eTraversalNeeded;
3617 }
3618 } else {
3619 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3620 flags |= eTransactionNeeded|eTraversalNeeded;
3621 }
chaviw8b3871a2017-11-01 17:41:01 -07003622 }
3623 }
3624 if (what & layer_state_t::eSizeChanged) {
3625 if (layer->setSize(s.w, s.h)) {
3626 flags |= eTraversalNeeded;
3627 }
3628 }
3629 if (what & layer_state_t::eAlphaChanged) {
3630 if (layer->setAlpha(s.alpha))
3631 flags |= eTraversalNeeded;
3632 }
3633 if (what & layer_state_t::eColorChanged) {
3634 if (layer->setColor(s.color))
3635 flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003638 // TODO: b/109894387
3639 //
3640 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3641 // rotation. To see the problem observe that if we have a square parent, and a child
3642 // of the same size, then we rotate the child 45 degrees around it's center, the child
3643 // must now be cropped to a non rectangular 8 sided region.
3644 //
3645 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3646 // private API, and the WindowManager only uses rotation in one case, which is on a top
3647 // level layer in which cropping is not an issue.
3648 //
3649 // However given that abuse of rotation matrices could lead to surfaces extending outside
3650 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3651 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3652 // transformations.
3653 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003654 flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eTransparentRegionChanged) {
3657 if (layer->setTransparentRegionHint(s.transparentRegion))
3658 flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eFlagsChanged) {
3661 if (layer->setFlags(s.flags, s.mask))
3662 flags |= eTraversalNeeded;
3663 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003664 if (what & layer_state_t::eCropChanged_legacy) {
3665 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003666 flags |= eTraversalNeeded;
3667 }
chaviw8b3871a2017-11-01 17:41:01 -07003668 if (what & layer_state_t::eLayerStackChanged) {
3669 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3670 // We only allow setting layer stacks for top level layers,
3671 // everything else inherits layer stack from its parent.
3672 if (layer->hasParent()) {
3673 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3674 layer->getName().string());
3675 } else if (idx < 0) {
3676 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3677 "that also does not appear in the top level layer list. Something"
3678 " has gone wrong.", layer->getName().string());
3679 } else if (layer->setLayerStack(s.layerStack)) {
3680 mCurrentState.layersSortedByZ.removeAt(idx);
3681 mCurrentState.layersSortedByZ.add(layer);
3682 // we need traversal (state changed)
3683 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003684 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003685 }
3686 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003687 if (what & layer_state_t::eDeferTransaction_legacy) {
3688 if (s.barrierHandle_legacy != nullptr) {
3689 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3690 } else if (s.barrierGbp_legacy != nullptr) {
3691 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003692 if (authenticateSurfaceTextureLocked(gbp)) {
3693 const auto& otherLayer =
3694 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003695 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003696 } else {
3697 ALOGE("Attempt to defer transaction to to an"
3698 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003699 }
3700 }
chaviw8b3871a2017-11-01 17:41:01 -07003701 // We don't trigger a traversal here because if no other state is
3702 // changed, we don't want this to cause any more work
3703 }
3704 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003705 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003706 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003707 if (!hadParent) {
3708 mCurrentState.layersSortedByZ.remove(layer);
3709 }
chaviw8b3871a2017-11-01 17:41:01 -07003710 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003711 }
chaviw8b3871a2017-11-01 17:41:01 -07003712 }
3713 if (what & layer_state_t::eReparentChildren) {
3714 if (layer->reparentChildren(s.reparentHandle)) {
3715 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003716 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003717 }
chaviw8b3871a2017-11-01 17:41:01 -07003718 if (what & layer_state_t::eDetachChildren) {
3719 layer->detachChildren();
3720 }
3721 if (what & layer_state_t::eOverrideScalingModeChanged) {
3722 layer->setOverrideScalingMode(s.overrideScalingMode);
3723 // We don't trigger a traversal here because if no other state is
3724 // changed, we don't want this to cause any more work
3725 }
Marissa Wall61c58622018-07-18 10:12:20 -07003726 if (what & layer_state_t::eTransformChanged) {
3727 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3728 }
3729 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3730 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3731 flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eCropChanged) {
3734 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eBufferChanged) {
3737 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eAcquireFenceChanged) {
3740 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3741 }
3742 if (what & layer_state_t::eDataspaceChanged) {
3743 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eHdrMetadataChanged) {
3746 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3749 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eApiChanged) {
3752 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3753 }
3754 if (what & layer_state_t::eSidebandStreamChanged) {
3755 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3756 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003757 return flags;
3758}
3759
chaviwca27f252018-02-06 16:46:39 -08003760void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3761 const layer_state_t& state = composerState.state;
3762 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3763
3764 sp<Layer> layer(client->getLayerUser(state.surface));
3765 if (layer == nullptr) {
3766 return;
3767 }
3768
3769 if (layer->isPendingRemoval()) {
3770 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3771 return;
3772 }
3773
3774 if (state.what & layer_state_t::eDestroySurface) {
3775 removeLayerLocked(mStateLock, layer);
3776 }
3777}
3778
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003780 const String8& name,
3781 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003782 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003783 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003784 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003786 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003787 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003788 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003789 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003790 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003791
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003792 status_t result = NO_ERROR;
3793
3794 sp<Layer> layer;
3795
Cody Northropbc755282017-03-31 12:00:08 -06003796 String8 uniqueName = getUniqueLayerName(name);
3797
Mathias Agopian3165cc22012-08-08 19:42:09 -07003798 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003799 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003800 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3801 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003804 case ISurfaceComposerClient::eFXSurfaceBufferState:
3805 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3806 break;
chaviw13fdc492017-06-27 12:40:18 -07003807 case ISurfaceComposerClient::eFXSurfaceColor:
3808 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003809 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003810 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003811 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003812 case ISurfaceComposerClient::eFXSurfaceContainer:
3813 result = createContainerLayer(client,
3814 uniqueName, w, h, flags,
3815 handle, &layer);
3816 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003817 default:
3818 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003819 break;
3820 }
3821
Dan Stoza7d89d062015-04-30 13:29:25 -07003822 if (result != NO_ERROR) {
3823 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003825
Chia-I Wuab0c3192017-08-01 11:29:00 -07003826 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3827 // TODO b/64227542
3828 if (windowType == 441731) {
3829 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3830 layer->setPrimaryDisplayOnly();
3831 }
3832
Albert Chaulk479c60c2017-01-27 14:21:34 -05003833 layer->setInfo(windowType, ownerUid);
3834
Robert Carr1f0a16a2016-10-24 16:27:39 -07003835 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003836 if (result != NO_ERROR) {
3837 return result;
3838 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003839 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003840
3841 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003842 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843}
3844
Cody Northropbc755282017-03-31 12:00:08 -06003845String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3846{
3847 bool matchFound = true;
3848 uint32_t dupeCounter = 0;
3849
3850 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3851 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3852
Dan Stoza436ccf32018-06-21 12:10:12 -07003853 // Grab the state lock since we're accessing mCurrentState
3854 Mutex::Autolock lock(mStateLock);
3855
Cody Northropbc755282017-03-31 12:00:08 -06003856 // Loop over layers until we're sure there is no matching name
3857 while (matchFound) {
3858 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003859 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003860 if (layer->getName() == uniqueName) {
3861 matchFound = true;
3862 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3863 }
3864 });
3865 }
3866
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003867 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3868 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003869
3870 return uniqueName;
3871}
3872
Marissa Wallfd668622018-05-10 10:21:13 -07003873status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3874 uint32_t w, uint32_t h, uint32_t flags,
3875 PixelFormat& format, sp<IBinder>* handle,
3876 sp<IGraphicBufferProducer>* gbp,
3877 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003879 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 case PIXEL_FORMAT_TRANSPARENT:
3881 case PIXEL_FORMAT_TRANSLUCENT:
3882 format = PIXEL_FORMAT_RGBA_8888;
3883 break;
3884 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003885 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886 break;
3887 }
3888
Marissa Wallfd668622018-05-10 10:21:13 -07003889 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3890 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003891 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003892 *handle = layer->getHandle();
3893 *gbp = layer->getProducer();
3894 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003896
Marissa Wallfd668622018-05-10 10:21:13 -07003897 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003898 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899}
3900
Marissa Wall61c58622018-07-18 10:12:20 -07003901status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3902 uint32_t w, uint32_t h, uint32_t flags,
3903 sp<IBinder>* handle, sp<Layer>* outLayer) {
3904 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3905 *handle = layer->getHandle();
3906 *outLayer = layer;
3907
3908 return NO_ERROR;
3909}
3910
chaviw13fdc492017-06-27 12:40:18 -07003911status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003912 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003913 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914{
chaviw13fdc492017-06-27 12:40:18 -07003915 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003916 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003917 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003918}
3919
Robert Carr6b3f6c52018-08-13 13:05:17 -07003920status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3921 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3922 sp<IBinder>* handle, sp<Layer>* outLayer)
3923{
3924 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3925 *handle = (*outLayer)->getHandle();
3926 return NO_ERROR;
3927}
3928
3929
Mathias Agopianac9fa422013-02-11 16:40:36 -08003930status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931{
Robert Carr9524cb32017-02-13 11:32:32 -08003932 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003933 status_t err = NO_ERROR;
3934 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003935 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003936 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003937 err = removeLayer(l);
3938 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3939 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003940 }
3941 return err;
3942}
3943
Mathias Agopian13127d82013-03-05 17:47:11 -08003944status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003945{
Mathias Agopian67106042013-03-14 19:18:13 -07003946 // called by ~LayerCleaner() when all references to the IBinder (handle)
3947 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003948 sp<Layer> l = layer.promote();
3949 if (l == nullptr) {
3950 // The layer has already been removed, carry on
3951 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003952 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003953 // If we have a parent, then we can continue to live as long as it does.
3954 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955}
3956
Mathias Agopianb60314a2012-04-10 22:09:54 -07003957// ---------------------------------------------------------------------------
3958
Andy McFadden13a082e2012-08-24 10:16:42 -07003959void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003960 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3961 if (!displayToken) return;
3962
Jesse Hall01e29052013-02-19 16:13:35 -08003963 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003964 Vector<ComposerState> state;
3965 Vector<DisplayState> displays;
3966 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003967 d.what = DisplayState::eDisplayProjectionChanged |
3968 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003969 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003970 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003971 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003972 d.frame.makeInvalid();
3973 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003974 d.width = 0;
3975 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003976 displays.add(d);
3977 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003978
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003979 const auto display = getDisplayDevice(displayToken);
3980 if (!display) return;
3981
3982 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3983
3984 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003985 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003986 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003987
Brian Andersond0010582017-03-07 13:20:31 -08003988 // Use phase of 0 since phase is not known.
3989 // Use latency of 0, which will snap to the ideal latency.
3990 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003991}
3992
3993void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003994 // Async since we may be called from the main thread.
3995 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003996}
3997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003998void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3999 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004000 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004001 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004003 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004004 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004005 return;
4006 }
4007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004008 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004009 ALOGW("Trying to set power mode for virtual display");
4010 return;
4011 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004013 display->setPowerMode(mode);
4014
Lloyd Pique4dccc412018-01-22 17:21:36 -08004015 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004016 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004017 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004018 if (idx < 0) {
4019 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4020 return;
4021 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004022 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004023 }
4024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004025 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004026 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004027 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004028 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004029 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004030 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004031 if (mUseScheduler) {
4032 mScheduler->onScreenAcquired(mAppConnectionHandle);
4033 } else {
4034 mEventThread->onScreenAcquired();
4035 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004036 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004039 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004040 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004041 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004042
4043 struct sched_param param = {0};
4044 param.sched_priority = 1;
4045 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4046 ALOGW("Couldn't set SCHED_FIFO on display on");
4047 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004048 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004049 // Turn off the display
4050 struct sched_param param = {0};
4051 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4052 ALOGW("Couldn't set SCHED_OTHER on display off");
4053 }
4054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004055 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004056 disableHardwareVsync(true); // also cancels any in-progress resync
4057
Mathias Agopiancde87a32012-09-13 14:09:01 -07004058 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004059 if (mUseScheduler) {
4060 mScheduler->onScreenReleased(mAppConnectionHandle);
4061 } else {
4062 mEventThread->onScreenReleased();
4063 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004064 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004065
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004066 getHwComposer().setPowerMode(type, mode);
4067 mVisibleRegionsDirty = true;
4068 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004069 } else if (mode == HWC_POWER_MODE_DOZE ||
4070 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004071 // Update display while dozing
4072 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004073 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004074 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004075 if (mUseScheduler) {
4076 mScheduler->onScreenAcquired(mAppConnectionHandle);
4077 } else {
4078 mEventThread->onScreenAcquired();
4079 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004080 resyncToHardwareVsync(true);
4081 }
4082 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4083 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004084 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004085 disableHardwareVsync(true); // also cancels any in-progress resync
4086 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004087 if (mUseScheduler) {
4088 mScheduler->onScreenReleased(mAppConnectionHandle);
4089 } else {
4090 mEventThread->onScreenReleased();
4091 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004092 }
4093 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004094 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004095 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004096 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004097 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004098
4099 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004100}
4101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004103 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004104 const auto display = getDisplayDevice(displayToken);
4105 if (!display) {
4106 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4107 displayToken.get());
4108 } else if (display->isVirtual()) {
4109 ALOGW("Attempt to set power mode %d for virtual display", mode);
4110 } else {
4111 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004112 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004113 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004114}
4115
4116// ---------------------------------------------------------------------------
4117
Lloyd Pique755e3192018-01-31 16:46:15 -08004118status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4119 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004121
Mathias Agopianbd115332013-04-18 16:41:04 -07004122 IPCThreadState* ipc = IPCThreadState::self();
4123 const int pid = ipc->getCallingPid();
4124 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004125
Mathias Agopianbd115332013-04-18 16:41:04 -07004126 if ((uid != AID_SHELL) &&
4127 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004128 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004129 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004131 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004132 // (this would indicate SF is stuck, but we want to be able to
4133 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004134 status_t err = mStateLock.timedLock(s2ns(1));
4135 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004136 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004137 result.appendFormat(
4138 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4139 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004140 }
4141
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 bool dumpAll = true;
4143 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004145
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004146 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147 if ((index < numArgs) &&
4148 (args[index] == String16("--list"))) {
4149 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004150 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004151 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004152 }
4153
4154 if ((index < numArgs) &&
4155 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004157 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004158 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004159 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004160
4161 if ((index < numArgs) &&
4162 (args[index] == String16("--latency-clear"))) {
4163 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004164 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004165 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004166 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004167
4168 if ((index < numArgs) &&
4169 (args[index] == String16("--dispsync"))) {
4170 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004171 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004172 dumpAll = false;
4173 }
Dan Stozab90cf072015-03-05 11:05:59 -08004174
4175 if ((index < numArgs) &&
4176 (args[index] == String16("--static-screen"))) {
4177 index++;
4178 dumpStaticScreenStats(result);
4179 dumpAll = false;
4180 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004181
4182 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004183 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004184 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004185 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004186 dumpAll = false;
4187 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004188
4189 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4190 index++;
4191 dumpWideColorInfo(result);
4192 dumpAll = false;
4193 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004194
4195 if ((index < numArgs) &&
4196 (args[index] == String16("--enable-layer-stats"))) {
4197 index++;
4198 mLayerStats.enable();
4199 dumpAll = false;
4200 }
4201
4202 if ((index < numArgs) &&
4203 (args[index] == String16("--disable-layer-stats"))) {
4204 index++;
4205 mLayerStats.disable();
4206 dumpAll = false;
4207 }
4208
4209 if ((index < numArgs) &&
4210 (args[index] == String16("--clear-layer-stats"))) {
4211 index++;
4212 mLayerStats.clear();
4213 dumpAll = false;
4214 }
4215
4216 if ((index < numArgs) &&
4217 (args[index] == String16("--dump-layer-stats"))) {
4218 index++;
4219 mLayerStats.dump(result);
4220 dumpAll = false;
4221 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004222
4223 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004224 (args[index] == String16("--frame-composition"))) {
4225 index++;
4226 dumpFrameCompositionInfo(result);
4227 dumpAll = false;
4228 }
4229
4230 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004231 (args[index] == String16("--display-identification"))) {
4232 index++;
4233 dumpDisplayIdentificationData(result);
4234 dumpAll = false;
4235 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004236
4237 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4238 index++;
4239 mTimeStats.parseArgs(asProto, args, index, result);
4240 dumpAll = false;
4241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004242 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004243
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004245 if (asProto) {
4246 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4247 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4248 } else {
4249 dumpAllLocked(args, index, result);
4250 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004251 }
4252
Mathias Agopian9795c422009-08-26 16:36:26 -07004253 if (locked) {
4254 mStateLock.unlock();
4255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256 }
4257 write(fd, result.string(), result.size());
4258 return NO_ERROR;
4259}
4260
Dan Stozac7014012014-02-14 15:03:43 -08004261void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4262 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004263{
Robert Carr2047fae2016-11-28 14:09:09 -08004264 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004265 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004266 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004267}
4268
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004270 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271{
4272 String8 name;
4273 if (index < args.size()) {
4274 name = String8(args[index]);
4275 index++;
4276 }
4277
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004278 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4279 getHwComposer().isConnected(displayId)) {
4280 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4281 const nsecs_t period = activeConfig->getVsyncPeriod();
4282 result.appendFormat("%" PRId64 "\n", period);
4283 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004284
4285 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004286 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004287 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004288 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004289 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004290 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004291 }
Robert Carr2047fae2016-11-28 14:09:09 -08004292 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293 }
4294}
4295
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004296void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004297 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004298{
4299 String8 name;
4300 if (index < args.size()) {
4301 name = String8(args[index]);
4302 index++;
4303 }
4304
Robert Carr2047fae2016-11-28 14:09:09 -08004305 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004306 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004307 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004308 }
Robert Carr2047fae2016-11-28 14:09:09 -08004309 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004310
Svetoslavd85084b2014-03-20 10:28:31 -07004311 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312}
4313
Jamie Gennis6547ff42013-07-16 20:12:42 -07004314// This should only be called from the main thread. Otherwise it would need
4315// the lock and should use mCurrentState rather than mDrawingState.
4316void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004317 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004318 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004319 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004320
4321 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4322}
4323
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004324void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004325{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004326 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004327
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004328 if (isLayerTripleBufferingDisabled())
4329 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004330
4331 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004332 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004333 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004334 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004335 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4336 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004337 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004338}
4339
Dan Stozab90cf072015-03-05 11:05:59 -08004340void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4341{
4342 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004343 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4344 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004345 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004346 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004347 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4348 b + 1, bucketTimeSec, percent);
4349 }
David Sodman4a36e932017-11-07 14:29:47 -08004350 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004351 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004352 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004353 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004354 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004355}
4356
Dan Stozae77c7662016-05-13 11:37:28 -07004357void SurfaceFlinger::recordBufferingStats(const char* layerName,
4358 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004359 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4360 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004361 for (const auto& segment : history) {
4362 if (!segment.usedThirdBuffer) {
4363 stats.twoBufferTime += segment.totalTime;
4364 }
4365 if (segment.occupancyAverage < 1.0f) {
4366 stats.doubleBufferedTime += segment.totalTime;
4367 } else if (segment.occupancyAverage < 2.0f) {
4368 stats.tripleBufferedTime += segment.totalTime;
4369 }
4370 ++stats.numSegments;
4371 stats.totalTime += segment.totalTime;
4372 }
4373}
4374
Brian Andersond6927fb2016-07-23 23:37:30 -07004375void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4376 result.appendFormat("Layer frame timestamps:\n");
4377
4378 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4379 const size_t count = currentLayers.size();
4380 for (size_t i=0 ; i<count ; i++) {
4381 currentLayers[i]->dumpFrameEvents(result);
4382 }
4383}
4384
Dan Stozae77c7662016-05-13 11:37:28 -07004385void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4386 result.append("Buffering stats:\n");
4387 result.append(" [Layer name] <Active time> <Two buffer> "
4388 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004389 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004390 typedef std::tuple<std::string, float, float, float> BufferTuple;
4391 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004392 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004393 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004394 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004395 if (stats.numSegments == 0) {
4396 continue;
4397 }
4398 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4399 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4400 stats.totalTime;
4401 float doubleBufferRatio = static_cast<float>(
4402 stats.doubleBufferedTime) / stats.totalTime;
4403 float tripleBufferRatio = static_cast<float>(
4404 stats.tripleBufferedTime) / stats.totalTime;
4405 sorted.insert({activeTime, {name, twoBufferRatio,
4406 doubleBufferRatio, tripleBufferRatio}});
4407 }
4408 for (const auto& sortedPair : sorted) {
4409 float activeTime = sortedPair.first;
4410 const BufferTuple& values = sortedPair.second;
4411 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4412 std::get<0>(values).c_str(), activeTime,
4413 std::get<1>(values), std::get<2>(values),
4414 std::get<3>(values));
4415 }
4416 result.append("\n");
4417}
4418
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004419void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004420 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004421 const int32_t displayId = display->getId();
4422 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4423 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004424 continue;
4425 }
4426
Dominik Laskowski7e045462018-05-30 13:02:02 -07004427 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 uint8_t port;
4429 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004430 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004431 result.append("no identification data\n");
4432 continue;
4433 }
4434
4435 if (!isEdid(data)) {
4436 result.append("unknown identification data: ");
4437 for (uint8_t byte : data) {
4438 result.appendFormat("%x ", byte);
4439 }
4440 result.append("\n");
4441 continue;
4442 }
4443
4444 const auto edid = parseEdid(data);
4445 if (!edid) {
4446 result.append("invalid EDID: ");
4447 for (uint8_t byte : data) {
4448 result.appendFormat("%x ", byte);
4449 }
4450 result.append("\n");
4451 continue;
4452 }
4453
4454 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4455 result.append(edid->displayName.data(), edid->displayName.length());
4456 result.append("\"\n");
4457 }
4458 result.append("\n");
4459}
4460
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004461void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004462 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4463 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004464 result.appendFormat("DisplayColorSetting: %s\n",
4465 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004466
4467 // TODO: print out if wide-color mode is active or not
4468
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004469 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004470 const int32_t displayId = display->getId();
4471 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004472 continue;
4473 }
4474
Dominik Laskowski7e045462018-05-30 13:02:02 -07004475 result.appendFormat("Display %d color modes:\n", displayId);
4476 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 for (auto&& mode : modes) {
4478 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4479 }
4480
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004481 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004482 result.appendFormat(" Current color mode: %s (%d)\n",
4483 decodeColorMode(currentMode).c_str(), currentMode);
4484 }
4485 result.append("\n");
4486}
4487
David Sodman7e4ae112018-02-09 15:02:28 -08004488void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4489 std::string stringResult;
4490
4491 for (const auto& [token, display] : mDisplays) {
4492 const auto displayId = display->getId();
4493 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4494 continue;
4495 }
4496
4497 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4498 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4499 break;
4500 }
4501 const auto& compositionInfoList = compositionInfoIt->second;
4502 stringResult += base::StringPrintf("Display: %d\n", displayId);
4503 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4504 for (const auto& compositionInfo : compositionInfoList) {
4505 compositionInfo.dump(stringResult, nullptr);
4506 stringResult += base::StringPrintf("\n");
4507 }
4508 }
4509
4510 result.append(stringResult.c_str());
4511}
4512
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004513LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004514 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004515 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4516 const State& state = useDrawing ? mDrawingState : mCurrentState;
4517 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004518 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004519 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004520 });
4521
4522 return layersProto;
4523}
4524
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004525LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004526 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004527
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004528 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 resolution->set_w(display.getWidth());
4530 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004532 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4533 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4534 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004535
Dominik Laskowski7e045462018-05-30 13:02:02 -07004536 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004537 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004538 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004539 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004540 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004541 }
4542 });
4543
4544 return layersProto;
4545}
4546
Mathias Agopian74d211a2013-04-22 16:55:35 +02004547void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4548 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004550 bool colorize = false;
4551 if (index < args.size()
4552 && (args[index] == String16("--color"))) {
4553 colorize = true;
4554 index++;
4555 }
4556
4557 Colorizer colorizer(colorize);
4558
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559 // figure out if we're stuck somewhere
4560 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004562 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4563
4564 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004565 * Dump library configuration.
4566 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567
4568 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004569 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004570 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004571 appendSfConfigString(result);
4572 appendUiConfigString(result);
4573 appendGuiConfigString(result);
4574 result.append("\n");
4575
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 result.append("\nDisplay identification data:\n");
4577 dumpDisplayIdentificationData(result);
4578
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004579 result.append("\nWide-Color information:\n");
4580 dumpWideColorInfo(result);
4581
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004583 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004584 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004585 result.append(SyncFeatures::getInstance().toString());
4586 result.append("\n");
4587
Andy McFadden41d67d72014-04-25 16:58:34 -07004588 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004589 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004590 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004591
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004592 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4593 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004594 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4595 getHwComposer().isConnected(displayId)) {
4596 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004597 result.appendFormat("Display %d: "
4598 "app phase %" PRId64 " ns, "
4599 "sf phase %" PRId64 " ns, "
4600 "early app phase %" PRId64 " ns, "
4601 "early sf phase %" PRId64 " ns, "
4602 "early app gl phase %" PRId64 " ns, "
4603 "early sf gl phase %" PRId64 " ns, "
4604 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4605 displayId,
4606 vsyncPhaseOffsetNs,
4607 sfVsyncPhaseOffsetNs,
4608 appEarlyOffset,
4609 sfEarlyOffset,
4610 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004611 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004612 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004613 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004614 result.append("\n");
4615
Dan Stozab90cf072015-03-05 11:05:59 -08004616 // Dump static screen stats
4617 result.append("\n");
4618 dumpStaticScreenStats(result);
4619 result.append("\n");
4620
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004621 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4622
Dan Stozae77c7662016-05-13 11:37:28 -07004623 dumpBufferingStats(result);
4624
Andy McFadden4803b742012-09-24 19:07:20 -07004625 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 * Dump the visible layer list
4627 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004628 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004629 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004630 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4631 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004632 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004633
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004634 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004635 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004636 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004637 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638
David Sodman7e4ae112018-02-09 15:02:28 -08004639 result.append("\nFrame-Composition information:\n");
4640 dumpFrameCompositionInfo(result);
4641 result.append("\n");
4642
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004644 * Dump Display state
4645 */
4646
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004647 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004648 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004649 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004650 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004651 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004652 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004653 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004654
4655 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656 * Dump SurfaceFlinger global state
4657 */
4658
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004660 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004662
Mathias Agopian888c8222012-08-04 21:10:38 -07004663 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004664 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004665
David Sodmanbc815282017-11-05 18:57:52 -08004666 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004668 if (display) {
4669 display->undefinedRegion.dump(result, "undefinedRegion");
4670 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4671 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004672 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004673 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004674 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004675 mTransactionFlags, !mGpuToCpuSupported);
4676
4677 if (display) {
4678 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4679 result.appendFormat(" refresh-rate : %f fps\n"
4680 " x-dpi : %f\n"
4681 " y-dpi : %f\n",
4682 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4683 activeConfig->getDpiY());
4684 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685
Mathias Agopian74d211a2013-04-22 16:55:35 +02004686 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004687 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688
Ana Krulec98b5b242018-08-10 15:03:23 -07004689 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690 /*
4691 * VSYNC state
4692 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004693 if (mUseScheduler) {
4694 mScheduler->dump(mAppConnectionHandle, result);
4695 } else {
4696 mEventThread->dump(result);
4697 }
Dan Stozae22aec72016-08-01 13:20:59 -07004698 result.append("\n");
4699
4700 /*
4701 * HWC layer minidump
4702 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004703 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004704 const int32_t displayId = display->getId();
4705 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004706 continue;
4707 }
4708
Dominik Laskowski7e045462018-05-30 13:02:02 -07004709 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004710 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004711 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004712 result.append("\n");
4713 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
4715 /*
4716 * Dump HWComposer state
4717 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004718 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004719 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004721 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004722 result.appendFormat(" h/w composer %s\n",
4723 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004724 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725
4726 /*
4727 * Dump gralloc state
4728 */
4729 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4730 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004731
4732 /*
4733 * Dump VrFlinger state if in use.
4734 */
4735 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4736 result.append("VrFlinger state:\n");
4737 result.append(mVrFlinger->Dump().c_str());
4738 result.append("\n");
4739 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004740}
4741
Dominik Laskowski7e045462018-05-30 13:02:02 -07004742const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004743 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004744 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004745 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004746 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004747 }
4748 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004749
4750 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4751 static const Vector<sp<Layer>> empty;
4752 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004753}
4754
Keun young Park63f165f2012-08-31 10:53:36 -07004755bool SurfaceFlinger::startDdmConnection()
4756{
4757 void* libddmconnection_dso =
4758 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4759 if (!libddmconnection_dso) {
4760 return false;
4761 }
4762 void (*DdmConnection_start)(const char* name);
4763 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004764 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004765 if (!DdmConnection_start) {
4766 dlclose(libddmconnection_dso);
4767 return false;
4768 }
4769 (*DdmConnection_start)(getServiceName());
4770 return true;
4771}
4772
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773void SurfaceFlinger::updateColorMatrixLocked() {
4774 mat4 colorMatrix;
4775 if (mGlobalSaturationFactor != 1.0f) {
4776 // Rec.709 luma coefficients
4777 float3 luminance{0.213f, 0.715f, 0.072f};
4778 luminance *= 1.0f - mGlobalSaturationFactor;
4779 mat4 saturationMatrix = mat4(
4780 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4781 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4782 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4783 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4784 );
4785 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4786 } else {
4787 colorMatrix = mClientColorMatrix * mDaltonizer();
4788 }
4789
4790 if (mCurrentState.colorMatrix != colorMatrix) {
4791 mCurrentState.colorMatrix = colorMatrix;
4792 mCurrentState.colorMatrixChanged = true;
4793 setTransactionFlags(eTransactionNeeded);
4794 }
4795}
4796
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004797status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798#pragma clang diagnostic push
4799#pragma clang diagnostic error "-Wswitch-enum"
4800 switch (static_cast<ISurfaceComposerTag>(code)) {
4801 // These methods should at minimum make sure that the client requested
4802 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004803 case BOOT_FINISHED:
4804 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 case CREATE_CONNECTION:
4806 case CREATE_DISPLAY:
4807 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004808 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004809 case GET_ACTIVE_COLOR_MODE:
4810 case GET_ANIMATION_FRAME_STATS:
4811 case GET_HDR_CAPABILITIES:
4812 case SET_ACTIVE_CONFIG:
4813 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004814 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004816 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4817 IPCThreadState* ipc = IPCThreadState::self();
4818 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4819 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004820 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004821 }
Robert Carr1db73f62016-12-21 12:58:51 -08004822 return OK;
4823 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004825 IPCThreadState* ipc = IPCThreadState::self();
4826 const int pid = ipc->getCallingPid();
4827 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004828 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4829 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004830 return PERMISSION_DENIED;
4831 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004832 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004834 // Used by apps to hook Choreographer to SurfaceFlinger.
4835 case CREATE_DISPLAY_EVENT_CONNECTION:
4836 // The following calls are currently used by clients that do not
4837 // request necessary permissions. However, they do not expose any secret
4838 // information, so it is OK to pass them.
4839 case AUTHENTICATE_SURFACE:
4840 case GET_ACTIVE_CONFIG:
4841 case GET_BUILT_IN_DISPLAY:
4842 case GET_DISPLAY_COLOR_MODES:
4843 case GET_DISPLAY_CONFIGS:
4844 case GET_DISPLAY_STATS:
4845 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4846 // Calling setTransactionState is safe, because you need to have been
4847 // granted a reference to Client* and Handle* to do anything with it.
4848 case SET_TRANSACTION_STATE:
4849 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004850 case CREATE_SCOPED_CONNECTION:
4851 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004852 return OK;
4853 }
4854 case CAPTURE_LAYERS:
4855 case CAPTURE_SCREEN: {
4856 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004857 IPCThreadState* ipc = IPCThreadState::self();
4858 const int pid = ipc->getCallingPid();
4859 const int uid = ipc->getCallingUid();
4860 if ((uid != AID_GRAPHICS) &&
4861 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4862 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4863 return PERMISSION_DENIED;
4864 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 return OK;
4866 }
4867 // The following codes are deprecated and should never be allowed to access SF.
4868 case CONNECT_DISPLAY_UNUSED:
4869 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4870 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4871 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874
4875 // These codes are used for the IBinder protocol to either interrogate the recipient
4876 // side of the transaction for its canonical interface descriptor or to dump its state.
4877 // We let them pass by default.
4878 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4879 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4880 code == IBinder::SYSPROPS_TRANSACTION) {
4881 return OK;
4882 }
4883 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4884 // in onTransact verifies that the user is root, and has access to use SF.
4885 if (code >= 1000 && code <= 1029) {
4886 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4887 return OK;
4888 }
4889 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4890 return PERMISSION_DENIED;
4891#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004892}
4893
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4895 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004896 status_t credentialCheck = CheckTransactCodeCredentials(code);
4897 if (credentialCheck != OK) {
4898 return credentialCheck;
4899 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004900
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004901 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4902 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004903 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004904 IPCThreadState* ipc = IPCThreadState::self();
4905 const int uid = ipc->getCallingUid();
4906 if (CC_UNLIKELY(uid != AID_SYSTEM
4907 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004908 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004909 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004910 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 return PERMISSION_DENIED;
4912 }
4913 int n;
4914 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004915 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004916 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004917 return NO_ERROR;
4918 case 1002: // SHOW_UPDATES
4919 n = data.readInt32();
4920 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004921 invalidateHwcGeometry();
4922 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004925 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004926 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004928 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004929 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004930 setTransactionFlags(
4931 eTransactionNeeded|
4932 eDisplayTransactionNeeded|
4933 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004934 return NO_ERROR;
4935 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004936 case 1006:{ // send empty update
4937 signalRefresh();
4938 return NO_ERROR;
4939 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004940 case 1008: // toggle use of hw composer
4941 n = data.readInt32();
4942 mDebugDisableHWC = n ? 1 : 0;
4943 invalidateHwcGeometry();
4944 repaintEverything();
4945 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004946 case 1009: // toggle use of transform hint
4947 n = data.readInt32();
4948 mDebugDisableTransformHint = n ? 1 : 0;
4949 invalidateHwcGeometry();
4950 repaintEverything();
4951 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004953 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 reply->writeInt32(0);
4955 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004956 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004957 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 return NO_ERROR;
4959 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004960 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004961 if (!display) {
4962 return NAME_NOT_FOUND;
4963 }
4964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004965 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004966 return NO_ERROR;
4967 }
4968 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004969 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004970 // daltonize
4971 n = data.readInt32();
4972 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004973 case 1:
4974 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4975 break;
4976 case 2:
4977 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4978 break;
4979 case 3:
4980 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4981 break;
4982 default:
4983 mDaltonizer.setType(ColorBlindnessType::None);
4984 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004985 }
4986 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004987 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004988 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004989 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004990 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004991
4992 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004993 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004995 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004996 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004997 // apply a color matrix
4998 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004999 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005000 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005001 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005002 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005003 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005004 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005006 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005007 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005008 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005009
5010 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5011 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005012 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005013 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5014 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5015 }
5016
Chia-I Wu28f320b2018-05-03 11:02:56 -07005017 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005018 return NO_ERROR;
5019 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005020 // This is an experimental interface
5021 // Needs to be shifted to proper binder interface when we productize
5022 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005023 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005024 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005025 return NO_ERROR;
5026 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005027 case 1017: {
5028 n = data.readInt32();
5029 mForceFullDamage = static_cast<bool>(n);
5030 return NO_ERROR;
5031 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005032 case 1018: { // Modify Choreographer's phase offset
5033 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005034 if (mUseScheduler) {
5035 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5036 } else {
5037 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5038 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005039 return NO_ERROR;
5040 }
5041 case 1019: { // Modify SurfaceFlinger's phase offset
5042 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005043 if (mUseScheduler) {
5044 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5045 } else {
5046 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5047 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005048 return NO_ERROR;
5049 }
Irvel468051e2016-06-13 16:44:44 -07005050 case 1020: { // Layer updates interceptor
5051 n = data.readInt32();
5052 if (n) {
5053 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005054 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005055 }
5056 else{
5057 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005058 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005059 }
5060 return NO_ERROR;
5061 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005062 case 1021: { // Disable HWC virtual displays
5063 n = data.readInt32();
5064 mUseHwcVirtualDisplays = !n;
5065 return NO_ERROR;
5066 }
Romain Guy0147a172017-06-01 13:53:56 -07005067 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005068 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005069 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005070
Chia-I Wu28f320b2018-05-03 11:02:56 -07005071 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005072 return NO_ERROR;
5073 }
Romain Guy54f154a2017-10-24 21:40:32 +01005074 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005076 invalidateHwcGeometry();
5077 repaintEverything();
5078 return NO_ERROR;
5079 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005080 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5081 // deprecate 1024 if they can.
5082 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005083 reply->writeBool(hasWideColorDisplay);
5084 return NO_ERROR;
5085 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005086 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005087 n = data.readInt32();
5088 if (n) {
5089 ALOGV("LayerTracing enabled");
5090 mTracing.enable();
5091 doTracing("tracing.enable");
5092 reply->writeInt32(NO_ERROR);
5093 } else {
5094 ALOGV("LayerTracing disabled");
5095 status_t err = mTracing.disable();
5096 reply->writeInt32(err);
5097 }
5098 return NO_ERROR;
5099 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005100 case 1026: { // Get layer tracing status
5101 reply->writeBool(mTracing.isEnabled());
5102 return NO_ERROR;
5103 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005104 // Is a DisplayColorSetting supported?
5105 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005106 const auto display = getDefaultDisplayDevice();
5107 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005108 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005109 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005110
5111 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5112 switch (setting) {
5113 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005114 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005115 break;
5116 case DisplayColorSetting::UNMANAGED:
5117 reply->writeBool(true);
5118 break;
5119 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005120 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005121 break;
5122 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005123 reply->writeBool(
5124 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005125 break;
5126 }
5127 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005128 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005129 // Is VrFlinger active?
5130 case 1028: {
5131 Mutex::Autolock _l(mStateLock);
5132 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5133 return NO_ERROR;
5134 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005135 case 1029: {
5136 // Code 1029 is an experimental feature that allows applications to
5137 // simulate a high frequency panel by setting a multiplier and divisor
5138 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005139 // 0, then the code simply return the current multiplier and divisor.
5140 HWC2::Device::FrequencyScaler frequencyScaler;
5141 frequencyScaler.multiplier = data.readInt32();
5142 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005143
David Sodman44b5de02018-08-21 16:28:53 -07005144 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5145 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5146 reply->writeInt32(frequencyScaler.multiplier);
5147 reply->writeInt32(frequencyScaler.divisor);
5148 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005149 }
5150
David Sodman44b5de02018-08-21 16:28:53 -07005151 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005152 enableHardwareVsync();
5153 } else {
5154 disableHardwareVsync(true);
5155 }
David Sodman44b5de02018-08-21 16:28:53 -07005156 mPrimaryDispSync->scalePeriod(frequencyScaler);
5157 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005158
David Sodman44b5de02018-08-21 16:28:53 -07005159 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5160 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5161
5162 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5163 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5164
5165 onHotplugReceived(getBE().mComposerSequenceId,
5166 hwcDisplayId, HWC2::Connection::Disconnected);
5167 onHotplugReceived(getBE().mComposerSequenceId,
5168 hwcDisplayId, HWC2::Connection::Connected);
5169 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5170 reply->writeInt32(frequencyScaler.multiplier);
5171 reply->writeInt32(frequencyScaler.divisor);
5172
David Sodman6d46c1e2018-07-13 12:59:48 -07005173 return NO_ERROR;
5174 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005175 // Is device color managed?
5176 case 1030: {
5177 reply->writeBool(useColorManagement);
5178 return NO_ERROR;
5179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005180 }
5181 }
5182 return err;
5183}
5184
Steven Thomas6d8110b2017-08-31 18:24:21 -07005185void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005186 android_atomic_or(1, &mRepaintEverything);
5187 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005188}
5189
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005190// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5191class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005192public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5194 ~WindowDisconnector() {
5195 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005196 }
5197
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005198private:
5199 ANativeWindow* mWindow;
5200 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005201};
5202
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005203status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5204 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5205 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5206 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005207 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005208 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005209
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005210 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005211
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005212 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5213
Chia-I Wu20261cb2018-08-23 12:55:44 -07005214 sp<DisplayDevice> display;
5215 {
5216 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005217
Chia-I Wu20261cb2018-08-23 12:55:44 -07005218 display = getDisplayDeviceLocked(displayToken);
5219 if (!display) return BAD_VALUE;
5220
Chia-I Wu8730ba82018-08-29 09:25:59 -07005221 // ignore sourceCrop (i.e., use the projected logical display
5222 // viewport) until the framework is fixed
5223 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005224
5225 // set the requested width/height to the logical display viewport size
5226 // by default
5227 if (reqWidth == 0 || reqHeight == 0) {
5228 reqWidth = uint32_t(display->getViewport().width());
5229 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005230 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005231 }
5232
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005233 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005234
5235 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005236 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005237 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005238}
5239
5240status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005241 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005242 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005243 ATRACE_CALL();
5244
5245 class LayerRenderArea : public RenderArea {
5246 public:
Robert Carr578038f2018-03-09 12:25:24 -08005247 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5248 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005249 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005250 mLayer(layer),
5251 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005252 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005253 mFlinger(flinger),
5254 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005255 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005256 Rect getBounds() const override {
5257 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005258 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005259 }
Marissa Wall61c58622018-07-18 10:12:20 -07005260 int getHeight() const override {
5261 return mLayer->getActiveHeight(mLayer->getDrawingState());
5262 }
5263 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005264 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005265 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005266 Rect getSourceCrop() const override {
5267 if (mCrop.isEmpty()) {
5268 return getBounds();
5269 } else {
5270 return mCrop;
5271 }
5272 }
Robert Carr578038f2018-03-09 12:25:24 -08005273 class ReparentForDrawing {
5274 public:
5275 const sp<Layer>& oldParent;
5276 const sp<Layer>& newParent;
5277
5278 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5279 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005280 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005281 }
Robert Carr15eae092018-03-23 13:43:53 -07005282 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005283 };
5284
5285 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005286 const Rect sourceCrop = getSourceCrop();
5287 // no need to check rotation because there is none
5288 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5289 sourceCrop.height() != getReqHeight();
5290
Robert Carr578038f2018-03-09 12:25:24 -08005291 if (!mChildrenOnly) {
5292 mTransform = mLayer->getTransform().inverse();
5293 drawLayers();
5294 } else {
5295 Rect bounds = getBounds();
5296 screenshotParentLayer =
5297 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5298 bounds.getWidth(), bounds.getHeight(), 0);
5299
5300 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5301 drawLayers();
5302 }
5303 }
chaviwa76b2712017-09-20 12:02:26 -07005304
chaviwa76b2712017-09-20 12:02:26 -07005305 private:
chaviw7206d492017-11-10 16:16:12 -08005306 const sp<Layer> mLayer;
5307 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005308
5309 // In the "childrenOnly" case we reparent the children to a screenshot
5310 // layer which has no properties set and which does not draw.
5311 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005312 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005313 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005314
5315 SurfaceFlinger* mFlinger;
5316 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005317 };
5318
5319 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5320 auto parent = layerHandle->owner.promote();
5321
chaviw7206d492017-11-10 16:16:12 -08005322 if (parent == nullptr || parent->isPendingRemoval()) {
5323 ALOGE("captureLayers called with a removed parent");
5324 return NAME_NOT_FOUND;
5325 }
5326
Robert Carr578038f2018-03-09 12:25:24 -08005327 const int uid = IPCThreadState::self()->getCallingUid();
5328 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5329 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5330 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5331 return PERMISSION_DENIED;
5332 }
5333
chaviw7206d492017-11-10 16:16:12 -08005334 Rect crop(sourceCrop);
5335 if (sourceCrop.width() <= 0) {
5336 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005337 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005338 }
5339
5340 if (sourceCrop.height() <= 0) {
5341 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005342 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005343 }
5344
5345 int32_t reqWidth = crop.width() * frameScale;
5346 int32_t reqHeight = crop.height() * frameScale;
5347
Chia-I Wu20261cb2018-08-23 12:55:44 -07005348 // really small crop or frameScale
5349 if (reqWidth <= 0) {
5350 reqWidth = 1;
5351 }
5352 if (reqHeight <= 0) {
5353 reqHeight = 1;
5354 }
5355
Robert Carr578038f2018-03-09 12:25:24 -08005356 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005357
Robert Carr578038f2018-03-09 12:25:24 -08005358 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005359 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5360 if (!layer->isVisible()) {
5361 return;
Robert Carr578038f2018-03-09 12:25:24 -08005362 } else if (childrenOnly && layer == parent.get()) {
5363 return;
chaviwa76b2712017-09-20 12:02:26 -07005364 }
5365 visitor(layer);
5366 });
5367 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005368 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005369}
5370
5371status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5372 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005373 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005374 bool useIdentityTransform) {
5375 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005376
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005377 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5378 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5379 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5380 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005381
5382 // This mutex protects syncFd and captureResult for communication of the return values from the
5383 // main thread back to this Binder thread
5384 std::mutex captureMutex;
5385 std::condition_variable captureCondition;
5386 std::unique_lock<std::mutex> captureLock(captureMutex);
5387 int syncFd = -1;
5388 std::optional<status_t> captureResult;
5389
Robert Carr03480e22018-01-04 16:02:06 -08005390 const int uid = IPCThreadState::self()->getCallingUid();
5391 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5392
Dominik Laskowski8c001672018-05-30 16:52:06 -07005393 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005394 // If there is a refresh pending, bug out early and tell the binder thread to try again
5395 // after the refresh.
5396 if (mRefreshPending) {
5397 ATRACE_NAME("Skipping screenshot for now");
5398 std::unique_lock<std::mutex> captureLock(captureMutex);
5399 captureResult = std::make_optional<status_t>(EAGAIN);
5400 captureCondition.notify_one();
5401 return;
5402 }
5403
5404 status_t result = NO_ERROR;
5405 int fd = -1;
5406 {
5407 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005408 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005409 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5410 useIdentityTransform, forSystem, &fd);
5411 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005412 }
5413
5414 {
5415 std::unique_lock<std::mutex> captureLock(captureMutex);
5416 syncFd = fd;
5417 captureResult = std::make_optional<status_t>(result);
5418 captureCondition.notify_one();
5419 }
5420 });
5421
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005422 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005423 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005424 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005425 while (*captureResult == EAGAIN) {
5426 captureResult.reset();
5427 result = postMessageAsync(message);
5428 if (result != NO_ERROR) {
5429 return result;
5430 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005431 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005432 }
5433 result = *captureResult;
5434 }
5435
5436 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437 sync_wait(syncFd, -1);
5438 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005439 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005440
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005441 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005442}
5443
chaviwa76b2712017-09-20 12:02:26 -07005444void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005445 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005446 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005447 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005448
Lloyd Pique144e1162017-12-20 16:44:52 -08005449 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005450
chaviwa76b2712017-09-20 12:02:26 -07005451 const auto reqWidth = renderArea.getReqWidth();
5452 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005453 const auto sourceCrop = renderArea.getSourceCrop();
5454 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005455
Chia-I Wu36574d92018-05-16 10:54:36 -07005456 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5457 engine.setOutputDataSpace(Dataspace::SRGB);
5458 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005459
Mathias Agopian180f10d2013-04-10 22:55:41 -07005460 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005461 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005462
5463 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005464 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005465 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005466
chaviw50da5042018-04-09 13:49:37 -07005467 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005468 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005469 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005470
chaviwa76b2712017-09-20 12:02:26 -07005471 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005472 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005473 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005474}
5475
chaviwa76b2712017-09-20 12:02:26 -07005476status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5477 TraverseLayersFunction traverseLayers,
5478 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005479 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005480 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005481 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005482 ATRACE_CALL();
5483
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005484 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005485
5486 traverseLayers([&](Layer* layer) {
5487 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5488 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005489
Robert Carr03480e22018-01-04 16:02:06 -08005490 // We allow the system server to take screenshots of secure layers for
5491 // use in situations like the Screen-rotation animation and place
5492 // the impetus on WindowManager to not persist them.
5493 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005494 ALOGW("FB is protected: PERMISSION_DENIED");
5495 return PERMISSION_DENIED;
5496 }
5497
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005498 // this binds the given EGLImage as a framebuffer for the
5499 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005500 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005501 if (bufferBond.getStatus() != NO_ERROR) {
5502 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005503 return INVALID_OPERATION;
5504 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005505
Dan Stozaabcda352017-06-01 14:37:39 -07005506 // this will in fact render into our dequeued buffer
5507 // via an FBO, which means we didn't have to create
5508 // an EGLSurface and therefore we're not
5509 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005510 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005511
Dan Stozaabcda352017-06-01 14:37:39 -07005512 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005513 getRenderEngine().finish();
5514 *outSyncFd = -1;
5515
chaviwa76b2712017-09-20 12:02:26 -07005516 const auto reqWidth = renderArea.getReqWidth();
5517 const auto reqHeight = renderArea.getReqHeight();
5518
Dan Stozaabcda352017-06-01 14:37:39 -07005519 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5520 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005521 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005522 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005523 } else {
5524 base::unique_fd syncFd = getRenderEngine().flush();
5525 if (syncFd < 0) {
5526 getRenderEngine().finish();
5527 }
5528 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005529 }
5530
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005531 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005532}
5533
Mathias Agopiand5556842013-09-19 17:08:37 -07005534void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005535 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005536 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005537 for (size_t y = 0; y < h; y++) {
5538 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5539 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005540 if (p[x] != 0xFF000000) return;
5541 }
5542 }
chaviwa76b2712017-09-20 12:02:26 -07005543 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005544
Robert Carr2047fae2016-11-28 14:09:09 -08005545 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005546 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005547 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005548 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5549 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5550 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5551 static_cast<float>(state.color.a));
5552 i++;
5553 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005554 }
5555}
5556
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005557// ---------------------------------------------------------------------------
5558
Dan Stoza412903f2017-04-27 13:42:17 -07005559void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5560 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005561}
5562
Dan Stoza412903f2017-04-27 13:42:17 -07005563void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5564 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005565}
5566
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005567void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5568 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005569 const LayerVector::Visitor& visitor) {
5570 // We loop through the first level of layers without traversing,
5571 // as we need to interpret min/max layer Z in the top level Z space.
5572 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005573 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005574 continue;
5575 }
5576 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005577 // relative layers are traversed in Layer::traverseInZOrder
5578 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005579 continue;
5580 }
5581 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005582 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005583 return;
5584 }
chaviwa76b2712017-09-20 12:02:26 -07005585 if (!layer->isVisible()) {
5586 return;
5587 }
5588 visitor(layer);
5589 });
5590 }
5591}
5592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005593}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005594
Lloyd Pique074e8122018-07-26 12:57:23 -07005595
Mathias Agopian3f844832013-08-07 21:24:32 -07005596#if defined(__gl_h_)
5597#error "don't include gl/gl.h in this file"
5598#endif
5599
5600#if defined(__gl2_h_)
5601#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005602#endif